id
int64
0
755k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
65
repo_stars
int64
100
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
9 values
repo_extraction_date
stringclasses
92 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
3,155
DocStringParser.cpp
ethereum_solidity/libsolidity/parsing/DocStringParser.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libsolidity/parsing/DocStringParser.h> #include <libsolidity/ast/AST.h> #include <liblangutil/Common.h> #include <liblangutil/ErrorReporter.h> #include <liblangutil/Exceptions.h> #include <range/v3/algorithm/find_first_of.hpp> #include <range/v3/algorithm/find_if_not.hpp> #include <range/v3/view/subrange.hpp> using namespace solidity; using namespace solidity::langutil; using namespace solidity::frontend; namespace { std::string::const_iterator skipLineOrEOS( std::string::const_iterator _nlPos, std::string::const_iterator _end ) { return (_nlPos == _end) ? _end : ++_nlPos; } std::string::const_iterator firstNonIdentifier( std::string::const_iterator _pos, std::string::const_iterator _end ) { auto currPos = _pos; if (currPos == _pos && isIdentifierStart(*currPos)) { currPos++; currPos = ranges::find_if_not(ranges::make_subrange(currPos, _end), isIdentifierPart); } return currPos; } std::string::const_iterator firstWhitespaceOrNewline( std::string::const_iterator _pos, std::string::const_iterator _end ) { return ranges::find_first_of(ranges::make_subrange(_pos, _end), " \t\n"); } std::string::const_iterator skipWhitespace( std::string::const_iterator _pos, std::string::const_iterator _end ) { auto isWhitespace = [](char const& c) { return (c == ' ' || c == '\t'); }; return ranges::find_if_not(ranges::make_subrange(_pos, _end), isWhitespace); } } std::multimap<std::string, DocTag> DocStringParser::parse() { m_lastTag = nullptr; m_docTags = {}; solAssert(m_node.text(), ""); iter currPos = m_node.text()->begin(); iter end = m_node.text()->end(); while (currPos != end) { iter tagPos = find(currPos, end, '@'); iter nlPos = find(currPos, end, '\n'); if (tagPos != end && tagPos < nlPos) { // we found a tag iter tagNameEndPos = firstWhitespaceOrNewline(tagPos, end); std::string tagName{tagPos + 1, tagNameEndPos}; iter tagDataPos = (tagNameEndPos != end) ? tagNameEndPos + 1 : tagNameEndPos; currPos = parseDocTag(tagDataPos, end, tagName); } else if (!!m_lastTag) // continuation of the previous tag currPos = parseDocTagLine(currPos, end, true); else if (currPos != end) { // if it begins without a tag then consider it as @notice if (currPos == m_node.text()->begin()) { currPos = parseDocTag(currPos, end, "notice"); continue; } else if (nlPos == end) //end of text break; // else skip the line if a newline was found and we get here currPos = nlPos + 1; } } return std::move(m_docTags); } DocStringParser::iter DocStringParser::parseDocTagLine(iter _pos, iter _end, bool _appending) { solAssert(!!m_lastTag, ""); auto nlPos = find(_pos, _end, '\n'); if (_appending && _pos != _end && *_pos != ' ' && *_pos != '\t') m_lastTag->content += " "; else if (!_appending) _pos = skipWhitespace(_pos, _end); copy(_pos, nlPos, back_inserter(m_lastTag->content)); return skipLineOrEOS(nlPos, _end); } DocStringParser::iter DocStringParser::parseDocTagParam(iter _pos, iter _end) { // find param name start auto nameStartPos = skipWhitespace(_pos, _end); if (nameStartPos == _end) { m_errorReporter.docstringParsingError(3335_error, m_node.location(), "No param name given"); return _end; } auto nameEndPos = firstNonIdentifier(nameStartPos, _end); auto paramName = std::string(nameStartPos, nameEndPos); auto descStartPos = skipWhitespace(nameEndPos, _end); auto nlPos = find(descStartPos, _end, '\n'); if (descStartPos == nlPos) { m_errorReporter.docstringParsingError(9942_error, m_node.location(), "No description given for param " + paramName); return _end; } auto paramDesc = std::string(descStartPos, nlPos); newTag("param"); m_lastTag->paramName = paramName; m_lastTag->content = paramDesc; return skipLineOrEOS(nlPos, _end); } DocStringParser::iter DocStringParser::parseDocTag(iter _pos, iter _end, std::string const& _tag) { // TODO: need to check for @(start of a tag) between here and the end of line // for all cases. if (!m_lastTag || _tag != "") { if (_tag == "param") return parseDocTagParam(_pos, _end); else { newTag(_tag); return parseDocTagLine(_pos, _end, false); } } else return parseDocTagLine(_pos, _end, true); } void DocStringParser::newTag(std::string const& _tagName) { m_lastTag = &m_docTags.insert(make_pair(_tagName, DocTag()))->second; }
5,064
C++
.cpp
156
30.192308
118
0.716452
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
3,156
Parser.cpp
ethereum_solidity/libsolidity/parsing/Parser.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 /** * @author Christian <c@ethdev.com> * @date 2014 * Solidity parser. */ #include <libsolidity/parsing/Parser.h> #include <libsolidity/ast/UserDefinableOperators.h> #include <libsolidity/interface/Version.h> #include <libyul/AST.h> #include <libyul/AsmParser.h> #include <libyul/backends/evm/EVMDialect.h> #include <liblangutil/ErrorReporter.h> #include <liblangutil/Scanner.h> #include <liblangutil/SemVerHandler.h> #include <liblangutil/SourceLocation.h> #include <libyul/backends/evm/EVMDialect.h> #include <boost/algorithm/string/trim.hpp> #include <boost/algorithm/string/replace.hpp> #include <boost/algorithm/string/predicate.hpp> #include <cctype> #include <memory> #include <regex> #include <tuple> #include <vector> using namespace solidity::langutil; using namespace std::string_literals; namespace solidity::frontend { /// AST node factory that also tracks the begin and end position of an AST node /// while it is being parsed class Parser::ASTNodeFactory { public: explicit ASTNodeFactory(Parser& _parser): m_parser(_parser), m_location{ _parser.currentLocation().start, -1, _parser.currentLocation().sourceName } {} ASTNodeFactory(Parser& _parser, ASTPointer<ASTNode> const& _childNode): m_parser(_parser), m_location{_childNode->location()} {} void markEndPosition() { m_location.end = m_parser.currentLocation().end; } void setLocation(SourceLocation const& _location) { m_location = _location; } void setLocationEmpty() { m_location.end = m_location.start; } /// Set the end position to the one of the given node. void setEndPositionFromNode(ASTPointer<ASTNode> const& _node) { m_location.end = _node->location().end; } template <class NodeType, typename... Args> ASTPointer<NodeType> createNode(Args&& ... _args) { solAssert(m_location.sourceName, ""); if (m_location.end < 0) markEndPosition(); return std::make_shared<NodeType>(m_parser.nextID(), m_location, std::forward<Args>(_args)...); } SourceLocation const& location() const noexcept { return m_location; } private: Parser& m_parser; SourceLocation m_location; }; ASTPointer<SourceUnit> Parser::parse(CharStream& _charStream) { solAssert(!m_insideModifier, ""); try { m_recursionDepth = 0; m_scanner = std::make_shared<Scanner>(_charStream); ASTNodeFactory nodeFactory(*this); m_experimentalSolidityEnabledInCurrentSourceUnit = false; std::vector<ASTPointer<ASTNode>> nodes; while (m_scanner->currentToken() == Token::Pragma) nodes.push_back(parsePragmaDirective(false)); if (m_experimentalSolidityEnabledInCurrentSourceUnit) m_scanner->setScannerMode(ScannerKind::ExperimentalSolidity); while (m_scanner->currentToken() != Token::EOS) { switch (m_scanner->currentToken()) { case Token::Pragma: nodes.push_back(parsePragmaDirective(true)); break; case Token::Import: nodes.push_back(parseImportDirective()); break; case Token::Abstract: case Token::Interface: case Token::Contract: case Token::Library: nodes.push_back(parseContractDefinition()); break; case Token::Struct: nodes.push_back(parseStructDefinition()); break; case Token::Enum: nodes.push_back(parseEnumDefinition()); break; case Token::Type: if (m_experimentalSolidityEnabledInCurrentSourceUnit) nodes.push_back(parseTypeDefinition()); else nodes.push_back(parseUserDefinedValueTypeDefinition()); break; case Token::Using: nodes.push_back(parseUsingDirective()); break; case Token::Function: nodes.push_back(parseFunctionDefinition(true)); break; case Token::ForAll: nodes.push_back(parseQuantifiedFunctionDefinition()); break; case Token::Event: nodes.push_back(parseEventDefinition()); break; case Token::Class: solAssert(m_experimentalSolidityEnabledInCurrentSourceUnit); nodes.push_back(parseTypeClassDefinition()); break; case Token::Instantiation: solAssert(m_experimentalSolidityEnabledInCurrentSourceUnit); nodes.push_back(parseTypeClassInstantiation()); break; default: if ( // Workaround because `error` is not a keyword. m_scanner->currentToken() == Token::Identifier && currentLiteral() == "error" && m_scanner->peekNextToken() == Token::Identifier && m_scanner->peekNextNextToken() == Token::LParen ) nodes.push_back(parseErrorDefinition()); // Constant variable. else if (variableDeclarationStart() && m_scanner->peekNextToken() != Token::EOS) { VarDeclParserOptions options; options.kind = VarDeclKind::FileLevel; options.allowInitialValue = true; nodes.push_back(parseVariableDeclaration(options)); expectToken(Token::Semicolon); } else fatalParserError(7858_error, "Expected pragma, import directive or contract/interface/library/struct/enum/constant/function/error definition."); } } solAssert(m_recursionDepth == 0, ""); return nodeFactory.createNode<SourceUnit>(findLicenseString(nodes), nodes, m_experimentalSolidityEnabledInCurrentSourceUnit); } catch (FatalError const& error) { solAssert(m_errorReporter.hasErrors(), "Unreported fatal error: "s + error.what()); return nullptr; } } void Parser::parsePragmaVersion(SourceLocation const& _location, std::vector<Token> const& _tokens, std::vector<std::string> const& _literals) { SemVerMatchExpressionParser parser(_tokens, _literals); try { SemVerMatchExpression matchExpression = parser.parse(); static SemVerVersion const currentVersion{std::string(VersionString)}; // FIXME: only match for major version incompatibility if (!matchExpression.matches(currentVersion)) m_errorReporter.fatalParserError( 5333_error, _location, "Source file requires different compiler version (current compiler is " + std::string(VersionString) + ") - note that nightly builds are considered to be " "strictly less than the released version" ); } catch (SemVerError const& matchError) { m_errorReporter.fatalParserError( 1684_error, _location, "Invalid version pragma. "s + matchError.what() ); } } ASTPointer<StructuredDocumentation> Parser::parseStructuredDocumentation() { if (m_scanner->currentCommentLiteral() != "") { ASTNodeFactory nodeFactory{*this}; nodeFactory.setLocation(m_scanner->currentCommentLocation()); return nodeFactory.createNode<StructuredDocumentation>( std::make_shared<ASTString>(m_scanner->currentCommentLiteral()) ); } return nullptr; } ASTPointer<PragmaDirective> Parser::parsePragmaDirective(bool const _finishedParsingTopLevelPragmas) { RecursionGuard recursionGuard(*this); // pragma anything* ; // Currently supported: // pragma solidity ^0.4.0 || ^0.3.0; ASTNodeFactory nodeFactory(*this); expectToken(Token::Pragma); std::vector<std::string> literals; std::vector<Token> tokens; do { Token token = m_scanner->currentToken(); if (token == Token::Illegal) parserError(6281_error, "Token incompatible with Solidity parser as part of pragma directive."); else { std::string literal = m_scanner->currentLiteral(); if (literal.empty() && TokenTraits::toString(token)) literal = TokenTraits::toString(token); literals.push_back(literal); tokens.push_back(token); } advance(); } while (m_scanner->currentToken() != Token::Semicolon && m_scanner->currentToken() != Token::EOS); nodeFactory.markEndPosition(); expectToken(Token::Semicolon); if (literals.size() >= 1 && literals[0] == "solidity") { parsePragmaVersion( nodeFactory.location(), std::vector<Token>(tokens.begin() + 1, tokens.end()), std::vector<std::string>(literals.begin() + 1, literals.end()) ); } if (literals.size() >= 2 && literals[0] == "experimental" && literals[1] == "solidity") { if (m_evmVersion < EVMVersion::constantinople()) fatalParserError(7637_error, "Experimental solidity requires Constantinople EVM version at the minimum."); if (_finishedParsingTopLevelPragmas) fatalParserError(8185_error, "Experimental pragma \"solidity\" can only be set at the beginning of the source unit."); m_experimentalSolidityEnabledInCurrentSourceUnit = true; } return nodeFactory.createNode<PragmaDirective>(tokens, literals); } ASTPointer<ImportDirective> Parser::parseImportDirective() { RecursionGuard recursionGuard(*this); // import "abc" [as x]; // import * as x from "abc"; // import {a as b, c} from "abc"; ASTNodeFactory nodeFactory(*this); expectToken(Token::Import); ASTPointer<ASTString> path; ASTPointer<ASTString> unitAlias = std::make_shared<std::string>(); SourceLocation unitAliasLocation{}; ImportDirective::SymbolAliasList symbolAliases; if (isQuotedPath() || isStdlibPath()) { path = isQuotedPath() ? getLiteralAndAdvance() : getStdlibImportPathAndAdvance(); if (m_scanner->currentToken() == Token::As) { advance(); tie(unitAlias, unitAliasLocation) = expectIdentifierWithLocation(); } } else { if (m_scanner->currentToken() == Token::LBrace) { advance(); while (true) { ASTPointer<ASTString> alias; SourceLocation aliasLocation = currentLocation(); ASTPointer<Identifier> id = parseIdentifier(); if (m_scanner->currentToken() == Token::As) { expectToken(Token::As); tie(alias, aliasLocation) = expectIdentifierWithLocation(); } symbolAliases.emplace_back(ImportDirective::SymbolAlias{std::move(id), std::move(alias), aliasLocation}); if (m_scanner->currentToken() != Token::Comma) break; advance(); } expectToken(Token::RBrace); } else if (m_scanner->currentToken() == Token::Mul) { advance(); expectToken(Token::As); tie(unitAlias, unitAliasLocation) = expectIdentifierWithLocation(); } else fatalParserError(9478_error, "Expected string literal (path), \"*\" or alias list."); // "from" is not a keyword but parsed as an identifier because of backwards // compatibility and because it is a really common word. if (m_scanner->currentToken() != Token::Identifier || m_scanner->currentLiteral() != "from") fatalParserError(8208_error, "Expected \"from\"."); advance(); if (!isQuotedPath() && !isStdlibPath()) fatalParserError(6845_error, "Expected import path."); path = isQuotedPath() ? getLiteralAndAdvance() : getStdlibImportPathAndAdvance(); } if (path->empty()) fatalParserError(6326_error, "Import path cannot be empty."); nodeFactory.markEndPosition(); expectToken(Token::Semicolon); return nodeFactory.createNode<ImportDirective>(path, unitAlias, unitAliasLocation, std::move(symbolAliases)); } std::pair<ContractKind, bool> Parser::parseContractKind() { ContractKind kind; bool abstract = false; if (m_scanner->currentToken() == Token::Abstract) { abstract = true; advance(); } switch (m_scanner->currentToken()) { case Token::Interface: kind = ContractKind::Interface; break; case Token::Contract: kind = ContractKind::Contract; break; case Token::Library: kind = ContractKind::Library; break; default: parserError(3515_error, "Expected keyword \"contract\", \"interface\" or \"library\"."); return std::make_pair(ContractKind::Contract, abstract); } advance(); return std::make_pair(kind, abstract); } ASTPointer<ContractDefinition> Parser::parseContractDefinition() { RecursionGuard recursionGuard(*this); ASTNodeFactory nodeFactory(*this); ASTPointer<ASTString> name = nullptr; SourceLocation nameLocation{}; ASTPointer<StructuredDocumentation> documentation; std::vector<ASTPointer<InheritanceSpecifier>> baseContracts; std::vector<ASTPointer<ASTNode>> subNodes; std::pair<ContractKind, bool> contractKind{}; documentation = parseStructuredDocumentation(); contractKind = parseContractKind(); std::tie(name, nameLocation) = expectIdentifierWithLocation(); if (m_scanner->currentToken() == Token::Is) do { advance(); baseContracts.push_back(parseInheritanceSpecifier()); } while (m_scanner->currentToken() == Token::Comma); expectToken(Token::LBrace); while (true) { Token currentTokenValue = m_scanner->currentToken(); if (currentTokenValue == Token::RBrace) break; else if ( (currentTokenValue == Token::Function && m_scanner->peekNextToken() != Token::LParen) || currentTokenValue == Token::Constructor || currentTokenValue == Token::Receive || currentTokenValue == Token::Fallback ) subNodes.push_back(parseFunctionDefinition()); else if (currentTokenValue == Token::Struct) subNodes.push_back(parseStructDefinition()); else if (currentTokenValue == Token::Enum) subNodes.push_back(parseEnumDefinition()); else if (currentTokenValue == Token::Type) subNodes.push_back(parseUserDefinedValueTypeDefinition()); else if ( // Workaround because `error` is not a keyword. currentTokenValue == Token::Identifier && currentLiteral() == "error" && m_scanner->peekNextToken() == Token::Identifier && m_scanner->peekNextNextToken() == Token::LParen ) subNodes.push_back(parseErrorDefinition()); else if (variableDeclarationStart()) { VarDeclParserOptions options; options.kind = VarDeclKind::State; options.allowInitialValue = true; subNodes.push_back(parseVariableDeclaration(options)); expectToken(Token::Semicolon); } else if (currentTokenValue == Token::Modifier) subNodes.push_back(parseModifierDefinition()); else if (currentTokenValue == Token::Event) subNodes.push_back(parseEventDefinition()); else if (currentTokenValue == Token::Using) subNodes.push_back(parseUsingDirective()); else fatalParserError(9182_error, "Function, variable, struct or modifier declaration expected."); } nodeFactory.markEndPosition(); expectToken(Token::RBrace); return nodeFactory.createNode<ContractDefinition>( name, nameLocation, documentation, baseContracts, subNodes, contractKind.first, contractKind.second ); } ASTPointer<InheritanceSpecifier> Parser::parseInheritanceSpecifier() { RecursionGuard recursionGuard(*this); ASTNodeFactory nodeFactory(*this); ASTPointer<IdentifierPath> name(parseIdentifierPath()); std::unique_ptr<std::vector<ASTPointer<Expression>>> arguments; if (m_scanner->currentToken() == Token::LParen) { advance(); arguments = std::make_unique<std::vector<ASTPointer<Expression>>>(parseFunctionCallListArguments()); nodeFactory.markEndPosition(); expectToken(Token::RParen); } else nodeFactory.setEndPositionFromNode(name); return nodeFactory.createNode<InheritanceSpecifier>(name, std::move(arguments)); } Visibility Parser::parseVisibilitySpecifier() { Visibility visibility(Visibility::Default); Token token = m_scanner->currentToken(); switch (token) { case Token::Public: visibility = Visibility::Public; break; case Token::Internal: visibility = Visibility::Internal; break; case Token::Private: visibility = Visibility::Private; break; case Token::External: visibility = Visibility::External; break; default: solAssert(false, "Invalid visibility specifier."); } advance(); return visibility; } ASTPointer<OverrideSpecifier> Parser::parseOverrideSpecifier() { solAssert(m_scanner->currentToken() == Token::Override, ""); ASTNodeFactory nodeFactory(*this); std::vector<ASTPointer<IdentifierPath>> overrides; nodeFactory.markEndPosition(); advance(); if (m_scanner->currentToken() == Token::LParen) { advance(); while (true) { overrides.push_back(parseIdentifierPath()); if (m_scanner->currentToken() == Token::RParen) break; expectToken(Token::Comma); } nodeFactory.markEndPosition(); expectToken(Token::RParen); } return nodeFactory.createNode<OverrideSpecifier>(std::move(overrides)); } StateMutability Parser::parseStateMutability() { StateMutability stateMutability(StateMutability::NonPayable); Token token = m_scanner->currentToken(); switch (token) { case Token::Payable: stateMutability = StateMutability::Payable; break; case Token::View: stateMutability = StateMutability::View; break; case Token::Pure: stateMutability = StateMutability::Pure; break; default: solAssert(false, "Invalid state mutability specifier."); } advance(); return stateMutability; } Parser::FunctionHeaderParserResult Parser::parseFunctionHeader(bool _isStateVariable) { RecursionGuard recursionGuard(*this); FunctionHeaderParserResult result; VarDeclParserOptions options; options.allowLocationSpecifier = true; result.parameters = parseParameterList(options); while (true) { Token token = m_scanner->currentToken(); if (!_isStateVariable && token == Token::Identifier) result.modifiers.push_back(parseModifierInvocation()); else if (TokenTraits::isVisibilitySpecifier(token)) { if (result.visibility != Visibility::Default) { // There is the special case of a public state variable of function type. // Detect this and return early. if (_isStateVariable && (result.visibility == Visibility::External || result.visibility == Visibility::Internal)) break; parserError( 9439_error, "Visibility already specified as \"" + Declaration::visibilityToString(result.visibility) + "\"." ); advance(); } else result.visibility = parseVisibilitySpecifier(); } else if (TokenTraits::isStateMutabilitySpecifier(token)) { if (result.stateMutability != StateMutability::NonPayable) { parserError( 9680_error, "State mutability already specified as \"" + stateMutabilityToString(result.stateMutability) + "\"." ); advance(); } else result.stateMutability = parseStateMutability(); } else if (!_isStateVariable && token == Token::Override) { if (result.overrides) parserError(1827_error, "Override already specified."); result.overrides = parseOverrideSpecifier(); } else if (!_isStateVariable && token == Token::Virtual) { if (result.isVirtual) parserError(6879_error, "Virtual already specified."); result.isVirtual = true; advance(); } else break; } if (m_experimentalSolidityEnabledInCurrentSourceUnit) { if (m_scanner->currentToken() == Token::RightArrow) { advance(); result.experimentalReturnExpression = parseBinaryExpression(); } } else { if (m_scanner->currentToken() == Token::Returns) { bool const permitEmptyParameterList = m_experimentalSolidityEnabledInCurrentSourceUnit; advance(); result.returnParameters = parseParameterList(options, permitEmptyParameterList); } else result.returnParameters = createEmptyParameterList(); } return result; } ASTPointer<ForAllQuantifier> Parser::parseQuantifiedFunctionDefinition() { solAssert(m_experimentalSolidityEnabledInCurrentSourceUnit); RecursionGuard recursionGuard(*this); ASTNodeFactory nodeFactory(*this); expectToken(Token::ForAll); ASTPointer<ParameterList> typeVariableDeclarations = parseParameterList(); nodeFactory.markEndPosition(); if (m_scanner->currentToken() != Token::Function) fatalParserError(5709_error, "Expected a function definition."); ASTPointer<FunctionDefinition> quantifiedFunction = parseFunctionDefinition(true /* _freeFunction */, true /* _allowBody */); return nodeFactory.createNode<ForAllQuantifier>( std::move(typeVariableDeclarations), std::move(quantifiedFunction) ); } ASTPointer<FunctionDefinition> Parser::parseFunctionDefinition(bool _freeFunction, bool _allowBody) { RecursionGuard recursionGuard(*this); ASTNodeFactory nodeFactory(*this); ASTPointer<StructuredDocumentation> documentation = parseStructuredDocumentation(); Token kind = m_scanner->currentToken(); ASTPointer<ASTString> name; SourceLocation nameLocation; if (kind == Token::Function) { advance(); if ( m_scanner->currentToken() == Token::Constructor || m_scanner->currentToken() == Token::Fallback || m_scanner->currentToken() == Token::Receive ) { std::string expected = std::map<Token, std::string>{ {Token::Constructor, "constructor"}, {Token::Fallback, "fallback function"}, {Token::Receive, "receive function"}, }.at(m_scanner->currentToken()); nameLocation = currentLocation(); name = std::make_shared<ASTString>(TokenTraits::toString(m_scanner->currentToken())); std::string message{ "This function is named \"" + *name + "\" but is not the " + expected + " of the contract. " "If you intend this to be a " + expected + ", use \"" + *name + "(...) { ... }\" without " "the \"function\" keyword to define it." }; if (m_scanner->currentToken() == Token::Constructor) parserError(3323_error, message); else parserWarning(3445_error, message); advance(); } else tie(name, nameLocation) = expectIdentifierWithLocation(); } else { solAssert(kind == Token::Constructor || kind == Token::Fallback || kind == Token::Receive, ""); advance(); name = std::make_shared<ASTString>(); } FunctionHeaderParserResult header = parseFunctionHeader(false); if (m_experimentalSolidityEnabledInCurrentSourceUnit) solAssert(!header.returnParameters); else solAssert(!header.experimentalReturnExpression); ASTPointer<Block> block; nodeFactory.markEndPosition(); if (!_allowBody) expectToken(Token::Semicolon); else if (m_scanner->currentToken() == Token::Semicolon) advance(); else { block = parseBlock(); nodeFactory.setEndPositionFromNode(block); } return nodeFactory.createNode<FunctionDefinition>( name, nameLocation, header.visibility, header.stateMutability, _freeFunction, kind, header.isVirtual, header.overrides, documentation, header.parameters, header.modifiers, header.returnParameters, block, header.experimentalReturnExpression ); } ASTPointer<StructDefinition> Parser::parseStructDefinition() { RecursionGuard recursionGuard(*this); ASTNodeFactory nodeFactory(*this); ASTPointer<StructuredDocumentation> documentation = parseStructuredDocumentation(); expectToken(Token::Struct); auto [name, nameLocation] = expectIdentifierWithLocation(); std::vector<ASTPointer<VariableDeclaration>> members; expectToken(Token::LBrace); while (m_scanner->currentToken() != Token::RBrace) { members.push_back(parseVariableDeclaration()); expectToken(Token::Semicolon); } nodeFactory.markEndPosition(); expectToken(Token::RBrace); return nodeFactory.createNode<StructDefinition>(std::move(name), std::move(nameLocation), std::move(members), std::move(documentation)); } ASTPointer<EnumValue> Parser::parseEnumValue() { RecursionGuard recursionGuard(*this); ASTNodeFactory nodeFactory(*this); nodeFactory.markEndPosition(); return nodeFactory.createNode<EnumValue>(expectIdentifierToken()); } ASTPointer<EnumDefinition> Parser::parseEnumDefinition() { RecursionGuard recursionGuard(*this); ASTNodeFactory nodeFactory(*this); ASTPointer<StructuredDocumentation> documentation = parseStructuredDocumentation(); expectToken(Token::Enum); auto [name, nameLocation] = expectIdentifierWithLocation(); std::vector<ASTPointer<EnumValue>> members; expectToken(Token::LBrace); while (m_scanner->currentToken() != Token::RBrace) { members.push_back(parseEnumValue()); if (m_scanner->currentToken() == Token::RBrace) break; expectToken(Token::Comma); if (m_scanner->currentToken() != Token::Identifier) fatalParserError(1612_error, "Expected identifier after ','"); } if (members.empty()) parserError(3147_error, "Enum with no members is not allowed."); nodeFactory.markEndPosition(); expectToken(Token::RBrace); return nodeFactory.createNode<EnumDefinition>(name, nameLocation, members, documentation); } ASTPointer<VariableDeclaration> Parser::parseVariableDeclaration( VarDeclParserOptions const& _options, ASTPointer<TypeName> const& _lookAheadArrayType ) { RecursionGuard recursionGuard(*this); ASTNodeFactory nodeFactory = _lookAheadArrayType ? ASTNodeFactory(*this, _lookAheadArrayType) : ASTNodeFactory(*this); ASTPointer<StructuredDocumentation> const documentation = parseStructuredDocumentation(); ASTPointer<TypeName> type = _lookAheadArrayType ? _lookAheadArrayType : parseTypeName(); nodeFactory.setEndPositionFromNode(type); if (dynamic_cast<FunctionTypeName*>(type.get()) && _options.kind == VarDeclKind::State && m_scanner->currentToken() == Token::LBrace) fatalParserError( 2915_error, "Expected a state variable declaration. If you intended this as a fallback function " "or a function to handle plain ether transactions, use the \"fallback\" keyword " "or the \"receive\" keyword instead." ); bool isIndexed = false; VariableDeclaration::Mutability mutability = VariableDeclaration::Mutability::Mutable; ASTPointer<OverrideSpecifier> overrides = nullptr; Visibility visibility(Visibility::Default); VariableDeclaration::Location location = VariableDeclaration::Location::Unspecified; ASTPointer<ASTString> identifier; SourceLocation nameLocation{}; while (true) { Token token = m_scanner->currentToken(); if (_options.kind == VarDeclKind::State && TokenTraits::isVariableVisibilitySpecifier(token)) { nodeFactory.markEndPosition(); if (visibility != Visibility::Default) { parserError( 4110_error, "Visibility already specified as \"" + Declaration::visibilityToString(visibility) + "\"." ); advance(); } else visibility = parseVisibilitySpecifier(); } else if (_options.kind == VarDeclKind::State && token == Token::Override) { if (overrides) parserError(9125_error, "Override already specified."); overrides = parseOverrideSpecifier(); } else { if (_options.allowIndexed && token == Token::Indexed) { if (isIndexed) parserError(5399_error, "Indexed already specified."); isIndexed = true; } else if (token == Token::Constant || token == Token::Immutable) { if (mutability != VariableDeclaration::Mutability::Mutable) parserError( 3109_error, std::string("Mutability already set to ") + (mutability == VariableDeclaration::Mutability::Constant ? "\"constant\"" : "\"immutable\"") ); else if (token == Token::Constant) mutability = VariableDeclaration::Mutability::Constant; else if (token == Token::Immutable) mutability = VariableDeclaration::Mutability::Immutable; } else if (_options.allowLocationSpecifier && TokenTraits::isLocationSpecifier(token)) { if (location != VariableDeclaration::Location::Unspecified) parserError(3548_error, "Location already specified."); else { switch (token) { case Token::Storage: location = VariableDeclaration::Location::Storage; break; case Token::Memory: location = VariableDeclaration::Location::Memory; break; case Token::CallData: location = VariableDeclaration::Location::CallData; break; default: solAssert(false, "Unknown data location."); } } } else if ( _options.kind == VarDeclKind::State && token == Token::Identifier && m_scanner->currentLiteral() == "transient" && m_scanner->peekNextToken() != Token::Assign && m_scanner->peekNextToken() != Token::Semicolon ) { if (location != VariableDeclaration::Location::Unspecified) parserError(ErrorId{3548}, "Location already specified."); else location = VariableDeclaration::Location::Transient; } else break; nodeFactory.markEndPosition(); advance(); } } if (_options.allowEmptyName && m_scanner->currentToken() != Token::Identifier) identifier = std::make_shared<ASTString>(""); else { nodeFactory.markEndPosition(); tie(identifier, nameLocation) = expectIdentifierWithLocation(); } ASTPointer<Expression> value; if (_options.allowInitialValue) { if (m_scanner->currentToken() == Token::Assign) { advance(); value = parseExpression(); nodeFactory.setEndPositionFromNode(value); } } return nodeFactory.createNode<VariableDeclaration>( type, identifier, nameLocation, value, visibility, documentation, isIndexed, mutability, overrides, location ); } ASTPointer<ModifierDefinition> Parser::parseModifierDefinition() { RecursionGuard recursionGuard(*this); ScopeGuard resetModifierFlag([this]() { m_insideModifier = false; }); m_insideModifier = true; ASTNodeFactory nodeFactory(*this); ASTPointer<StructuredDocumentation> documentation = parseStructuredDocumentation(); expectToken(Token::Modifier); auto [name, nameLocation] = expectIdentifierWithLocation(); ASTPointer<ParameterList> parameters; if (m_scanner->currentToken() == Token::LParen) { VarDeclParserOptions options; options.allowLocationSpecifier = true; parameters = parseParameterList(options); } else parameters = createEmptyParameterList(); ASTPointer<OverrideSpecifier> overrides; bool isVirtual = false; while (true) { if (m_scanner->currentToken() == Token::Override) { if (overrides) parserError(9102_error, "Override already specified."); overrides = parseOverrideSpecifier(); } else if (m_scanner->currentToken() == Token::Virtual) { if (isVirtual) parserError(2662_error, "Virtual already specified."); isVirtual = true; advance(); } else break; } ASTPointer<Block> block; nodeFactory.markEndPosition(); if (m_scanner->currentToken() != Token::Semicolon) { block = parseBlock(); nodeFactory.setEndPositionFromNode(block); } else advance(); // just consume the ';' return nodeFactory.createNode<ModifierDefinition>(name, nameLocation, documentation, parameters, isVirtual, overrides, block); } std::pair<ASTPointer<ASTString>, SourceLocation> Parser::expectIdentifierWithLocation() { SourceLocation nameLocation = currentLocation(); ASTPointer<ASTString> name = expectIdentifierToken(); return {std::move(name), std::move(nameLocation)}; } ASTPointer<EventDefinition> Parser::parseEventDefinition() { RecursionGuard recursionGuard(*this); ASTNodeFactory nodeFactory(*this); ASTPointer<StructuredDocumentation> documentation = parseStructuredDocumentation(); expectToken(Token::Event); auto [name, nameLocation] = expectIdentifierWithLocation(); VarDeclParserOptions options; options.allowIndexed = true; ASTPointer<ParameterList> parameters = parseParameterList(options); bool anonymous = false; if (m_scanner->currentToken() == Token::Anonymous) { anonymous = true; advance(); } nodeFactory.markEndPosition(); expectToken(Token::Semicolon); return nodeFactory.createNode<EventDefinition>(name, nameLocation, documentation, parameters, anonymous); } ASTPointer<ErrorDefinition> Parser::parseErrorDefinition() { RecursionGuard recursionGuard(*this); ASTNodeFactory nodeFactory(*this); ASTPointer<StructuredDocumentation> documentation = parseStructuredDocumentation(); solAssert(*expectIdentifierToken() == "error", ""); auto&& [name, nameLocation] = expectIdentifierWithLocation(); ASTPointer<ParameterList> parameters = parseParameterList({}); nodeFactory.markEndPosition(); expectToken(Token::Semicolon); return nodeFactory.createNode<ErrorDefinition>(name, std::move(nameLocation), documentation, parameters); } ASTPointer<UsingForDirective> Parser::parseUsingDirective() { RecursionGuard recursionGuard(*this); ASTNodeFactory nodeFactory(*this); expectToken(Token::Using); std::vector<ASTPointer<IdentifierPath>> functions; std::vector<std::optional<Token>> operators; bool const usesBraces = m_scanner->currentToken() == Token::LBrace; if (usesBraces) { do { advance(); functions.emplace_back(parseIdentifierPath()); if (m_scanner->currentToken() == Token::As) { advance(); Token operator_ = m_scanner->currentToken(); if (!util::contains(userDefinableOperators, operator_)) { std::string operatorName; if (!m_scanner->currentLiteral().empty()) operatorName = m_scanner->currentLiteral(); else if (char const* tokenString = TokenTraits::toString(operator_)) operatorName = std::string(tokenString); parserError( 4403_error, fmt::format( "Not a user-definable operator: {}. Only the following operators can be user-defined: {}", operatorName, util::joinHumanReadable(userDefinableOperators | ranges::views::transform([](Token _t) { return std::string{TokenTraits::toString(_t)}; })) ) ); } operators.emplace_back(operator_); advance(); } else operators.emplace_back(std::nullopt); } while (m_scanner->currentToken() == Token::Comma); expectToken(Token::RBrace); } else { functions.emplace_back(parseIdentifierPath()); operators.emplace_back(std::nullopt); } ASTPointer<TypeName> typeName; expectToken(Token::For); if (m_scanner->currentToken() == Token::Mul) advance(); else typeName = parseTypeName(); bool global = false; if (m_scanner->currentToken() == Token::Identifier && currentLiteral() == "global") { global = true; advance(); } nodeFactory.markEndPosition(); expectToken(Token::Semicolon); return nodeFactory.createNode<UsingForDirective>(std::move(functions), std::move(operators), usesBraces, typeName, global); } ASTPointer<ModifierInvocation> Parser::parseModifierInvocation() { RecursionGuard recursionGuard(*this); ASTNodeFactory nodeFactory(*this); ASTPointer<IdentifierPath> name(parseIdentifierPath()); std::unique_ptr<std::vector<ASTPointer<Expression>>> arguments; if (m_scanner->currentToken() == Token::LParen) { advance(); arguments = std::make_unique<std::vector<ASTPointer<Expression>>>(parseFunctionCallListArguments()); nodeFactory.markEndPosition(); expectToken(Token::RParen); } else nodeFactory.setEndPositionFromNode(name); return nodeFactory.createNode<ModifierInvocation>(name, std::move(arguments)); } ASTPointer<Identifier> Parser::parseIdentifier() { RecursionGuard recursionGuard(*this); ASTNodeFactory nodeFactory(*this); nodeFactory.markEndPosition(); return nodeFactory.createNode<Identifier>(expectIdentifierToken()); } ASTPointer<Identifier> Parser::parseIdentifierOrAddress() { RecursionGuard recursionGuard(*this); ASTNodeFactory nodeFactory(*this); nodeFactory.markEndPosition(); return nodeFactory.createNode<Identifier>(expectIdentifierTokenOrAddress()); } ASTPointer<UserDefinedTypeName> Parser::parseUserDefinedTypeName() { ASTNodeFactory nodeFactory(*this); ASTPointer<IdentifierPath> identifierPath = parseIdentifierPath(); nodeFactory.setEndPositionFromNode(identifierPath); return nodeFactory.createNode<UserDefinedTypeName>(identifierPath); } ASTPointer<UserDefinedValueTypeDefinition> Parser::parseUserDefinedValueTypeDefinition() { ASTNodeFactory nodeFactory(*this); expectToken(Token::Type); auto&& [name, nameLocation] = expectIdentifierWithLocation(); expectToken(Token::Is); ASTPointer<TypeName> typeName = parseTypeName(); nodeFactory.markEndPosition(); expectToken(Token::Semicolon); return nodeFactory.createNode<UserDefinedValueTypeDefinition>( name, std::move(nameLocation), typeName ); } ASTPointer<IdentifierPath> Parser::parseIdentifierPath() { RecursionGuard recursionGuard(*this); ASTNodeFactory nodeFactory(*this); nodeFactory.markEndPosition(); auto [name, nameLocation] = expectIdentifierWithLocation(); std::vector<ASTString> identifierPath{*name}; std::vector<SourceLocation> identifierPathLocations{nameLocation}; while (m_scanner->currentToken() == Token::Period) { advance(); nodeFactory.markEndPosition(); tie(name, nameLocation) = expectIdentifierWithLocation(); identifierPath.push_back(*name); identifierPathLocations.push_back(nameLocation); } return nodeFactory.createNode<IdentifierPath>(identifierPath, identifierPathLocations); } ASTPointer<TypeName> Parser::parseTypeNameSuffix(ASTPointer<TypeName> type, ASTNodeFactory& nodeFactory) { RecursionGuard recursionGuard(*this); while (m_scanner->currentToken() == Token::LBrack) { advance(); ASTPointer<Expression> length; if (m_scanner->currentToken() != Token::RBrack) length = parseExpression(); nodeFactory.markEndPosition(); expectToken(Token::RBrack); type = nodeFactory.createNode<ArrayTypeName>(type, length); } return type; } ASTPointer<TypeName> Parser::parseTypeName() { RecursionGuard recursionGuard(*this); ASTNodeFactory nodeFactory(*this); ASTPointer<TypeName> type; Token token = m_scanner->currentToken(); if (TokenTraits::isElementaryTypeName(token)) { unsigned firstSize; unsigned secondSize; std::tie(firstSize, secondSize) = m_scanner->currentTokenInfo(); ElementaryTypeNameToken elemTypeName(token, firstSize, secondSize); ASTNodeFactory nodeFactory(*this); nodeFactory.markEndPosition(); advance(); auto stateMutability = elemTypeName.token() == Token::Address ? std::optional<StateMutability>{StateMutability::NonPayable} : std::nullopt; if (TokenTraits::isStateMutabilitySpecifier(m_scanner->currentToken())) { if (elemTypeName.token() == Token::Address) { nodeFactory.markEndPosition(); stateMutability = parseStateMutability(); } else { parserError(9106_error, "State mutability can only be specified for address types."); advance(); } } type = nodeFactory.createNode<ElementaryTypeName>(elemTypeName, stateMutability); } else if (token == Token::Function) type = parseFunctionType(); else if (token == Token::Mapping) type = parseMapping(); else if (token == Token::Identifier) type = parseUserDefinedTypeName(); else fatalParserError(3546_error, "Expected type name"); solAssert(type, ""); // Parse "[...]" postfixes for arrays. type = parseTypeNameSuffix(type, nodeFactory); return type; } ASTPointer<FunctionTypeName> Parser::parseFunctionType() { solAssert(!m_experimentalSolidityEnabledInCurrentSourceUnit); RecursionGuard recursionGuard(*this); ASTNodeFactory nodeFactory(*this); expectToken(Token::Function); FunctionHeaderParserResult header = parseFunctionHeader(true); solAssert(!header.experimentalReturnExpression); return nodeFactory.createNode<FunctionTypeName>( header.parameters, header.returnParameters, header.visibility, header.stateMutability ); } ASTPointer<Mapping> Parser::parseMapping() { RecursionGuard recursionGuard(*this); ASTNodeFactory nodeFactory(*this); expectToken(Token::Mapping); expectToken(Token::LParen); ASTPointer<TypeName> keyType; Token token = m_scanner->currentToken(); unsigned firstSize; unsigned secondSize; std::tie(firstSize, secondSize) = m_scanner->currentTokenInfo(); if (token == Token::Identifier) keyType = parseUserDefinedTypeName(); else if (TokenTraits::isElementaryTypeName(token)) { keyType = ASTNodeFactory(*this).createNode<ElementaryTypeName>( ElementaryTypeNameToken{token, firstSize, secondSize} ); advance(); } else fatalParserError(1005_error, "Expected elementary type name or identifier for mapping key type"); ASTPointer<ASTString> keyName = std::make_shared<ASTString>(""); SourceLocation keyNameLocation{}; if (m_scanner->currentToken() == Token::Identifier) tie(keyName, keyNameLocation) = expectIdentifierWithLocation(); expectToken(Token::DoubleArrow); ASTPointer<TypeName> valueType = parseTypeName(); ASTPointer<ASTString> valueName = std::make_shared<ASTString>(""); SourceLocation valueNameLocation{}; if (m_scanner->currentToken() == Token::Identifier) tie(valueName, valueNameLocation) = expectIdentifierWithLocation(); nodeFactory.markEndPosition(); expectToken(Token::RParen); return nodeFactory.createNode<Mapping>(keyType, keyName, keyNameLocation, valueType, valueName, valueNameLocation); } ASTPointer<ParameterList> Parser::parseParameterList( VarDeclParserOptions const& _options, bool _allowEmpty ) { RecursionGuard recursionGuard(*this); ASTNodeFactory nodeFactory(*this); std::vector<ASTPointer<VariableDeclaration>> parameters; VarDeclParserOptions options(_options); options.allowEmptyName = true; if (m_experimentalSolidityEnabledInCurrentSourceUnit && m_scanner->currentToken() == Token::Identifier) { // Parses unary parameter lists without parentheses. TODO: is this a good idea in all cases? Including arguments? parameters = {parsePostfixVariableDeclaration()}; nodeFactory.setEndPositionFromNode(parameters.front()); return nodeFactory.createNode<ParameterList>(parameters); } expectToken(Token::LParen); auto parseSingleVariableDeclaration = [&]() { if (m_experimentalSolidityEnabledInCurrentSourceUnit) return parsePostfixVariableDeclaration(); else return parseVariableDeclaration(options); }; if (!_allowEmpty || m_scanner->currentToken() != Token::RParen) { parameters.push_back(parseSingleVariableDeclaration()); while (m_scanner->currentToken() != Token::RParen) { if (m_scanner->currentToken() == Token::Comma && m_scanner->peekNextToken() == Token::RParen) fatalParserError(7591_error, "Unexpected trailing comma in parameter list."); expectToken(Token::Comma); parameters.push_back(parseSingleVariableDeclaration()); } } nodeFactory.markEndPosition(); advance(); return nodeFactory.createNode<ParameterList>(parameters); } ASTPointer<Block> Parser::parseBlock(bool _allowUnchecked, ASTPointer<ASTString> const& _docString) { RecursionGuard recursionGuard(*this); ASTNodeFactory nodeFactory(*this); bool const unchecked = m_scanner->currentToken() == Token::Unchecked; if (unchecked) { if (!_allowUnchecked) parserError(5296_error, "\"unchecked\" blocks can only be used inside regular blocks."); advance(); } expectToken(Token::LBrace); std::vector<ASTPointer<Statement>> statements; while (m_scanner->currentToken() != Token::RBrace) statements.push_back(parseStatement(true)); nodeFactory.markEndPosition(); expectToken(Token::RBrace); return nodeFactory.createNode<Block>(_docString, unchecked, statements); } ASTPointer<Statement> Parser::parseStatement(bool _allowUnchecked) { RecursionGuard recursionGuard(*this); ASTPointer<ASTString> docString; ASTPointer<Statement> statement; if (m_scanner->currentCommentLiteral() != "") docString = std::make_shared<ASTString>(m_scanner->currentCommentLiteral()); switch (m_scanner->currentToken()) { case Token::If: return parseIfStatement(docString); case Token::While: return parseWhileStatement(docString); case Token::Do: return parseDoWhileStatement(docString); case Token::For: return parseForStatement(docString); case Token::Unchecked: case Token::LBrace: return parseBlock(_allowUnchecked, docString); case Token::Continue: statement = ASTNodeFactory(*this).createNode<Continue>(docString); advance(); break; case Token::Break: statement = ASTNodeFactory(*this).createNode<Break>(docString); advance(); break; case Token::Return: { ASTNodeFactory nodeFactory(*this); ASTPointer<Expression> expression; if (advance() != Token::Semicolon) { expression = parseExpression(); nodeFactory.setEndPositionFromNode(expression); } statement = nodeFactory.createNode<Return>(docString, expression); break; } case Token::Throw: { statement = ASTNodeFactory(*this).createNode<Throw>(docString); advance(); break; } case Token::Try: return parseTryStatement(docString); case Token::Assembly: return parseInlineAssembly(docString); case Token::Emit: statement = parseEmitStatement(docString); break; case Token::Identifier: if (m_scanner->currentLiteral() == "revert" && m_scanner->peekNextToken() == Token::Identifier) statement = parseRevertStatement(docString); else if (m_insideModifier && m_scanner->currentLiteral() == "_") { statement = ASTNodeFactory(*this).createNode<PlaceholderStatement>(docString); advance(); } else statement = parseSimpleStatement(docString); break; default: statement = parseSimpleStatement(docString); break; } expectToken(Token::Semicolon); return statement; } ASTPointer<InlineAssembly> Parser::parseInlineAssembly(ASTPointer<ASTString> const& _docString) { RecursionGuard recursionGuard(*this); SourceLocation location = currentLocation(); expectToken(Token::Assembly); yul::Dialect const& dialect = yul::EVMDialect::strictAssemblyForEVM(m_evmVersion, m_eofVersion); if (m_scanner->currentToken() == Token::StringLiteral) { if (m_scanner->currentLiteral() != "evmasm") fatalParserError(4531_error, "Only \"evmasm\" supported."); // This can be used in the future to set the dialect. advance(); } ASTPointer<std::vector<ASTPointer<ASTString>>> flags; if (m_scanner->currentToken() == Token::LParen) { flags = std::make_shared<std::vector<ASTPointer<ASTString>>>(); do { advance(); expectToken(Token::StringLiteral, false); flags->emplace_back(std::make_shared<ASTString>(m_scanner->currentLiteral())); advance(); } while (m_scanner->currentToken() == Token::Comma); expectToken(Token::RParen); } yul::Parser asmParser(m_errorReporter, dialect); std::shared_ptr<yul::AST> ast = asmParser.parseInline(m_scanner); if (ast == nullptr) BOOST_THROW_EXCEPTION(FatalError()); location.end = nativeLocationOf(ast->root()).end; return std::make_shared<InlineAssembly>(nextID(), location, _docString, dialect, std::move(flags), ast); } 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) { advance(); falseBody = parseStatement(); nodeFactory.setEndPositionFromNode(falseBody); } else nodeFactory.setEndPositionFromNode(trueBody); return nodeFactory.createNode<IfStatement>(_docString, condition, trueBody, falseBody); } ASTPointer<TryStatement> Parser::parseTryStatement(ASTPointer<ASTString> const& _docString) { RecursionGuard recursionGuard(*this); ASTNodeFactory nodeFactory(*this); expectToken(Token::Try); ASTPointer<Expression> externalCall = parseExpression(); std::vector<ASTPointer<TryCatchClause>> clauses; ASTNodeFactory successClauseFactory(*this); ASTPointer<ParameterList> returnsParameters; if (m_scanner->currentToken() == Token::Returns) { advance(); VarDeclParserOptions options; options.allowEmptyName = true; options.allowLocationSpecifier = true; returnsParameters = parseParameterList(options, false); } ASTPointer<Block> successBlock = parseBlock(); successClauseFactory.setEndPositionFromNode(successBlock); clauses.emplace_back(successClauseFactory.createNode<TryCatchClause>( std::make_shared<ASTString>(), returnsParameters, successBlock )); do { clauses.emplace_back(parseCatchClause()); } while (m_scanner->currentToken() == Token::Catch); nodeFactory.setEndPositionFromNode(clauses.back()); return nodeFactory.createNode<TryStatement>( _docString, externalCall, clauses ); } ASTPointer<TryCatchClause> Parser::parseCatchClause() { RecursionGuard recursionGuard(*this); ASTNodeFactory nodeFactory(*this); expectToken(Token::Catch); ASTPointer<ASTString> errorName = std::make_shared<std::string>(); ASTPointer<ParameterList> errorParameters; if (m_scanner->currentToken() != Token::LBrace) { if (m_scanner->currentToken() == Token::Identifier) errorName = expectIdentifierToken(); VarDeclParserOptions options; options.allowEmptyName = true; options.allowLocationSpecifier = true; errorParameters = parseParameterList(options, !errorName->empty()); } ASTPointer<Block> block = parseBlock(); nodeFactory.setEndPositionFromNode(block); return nodeFactory.createNode<TryCatchClause>(errorName, errorParameters, block); } ASTPointer<WhileStatement> Parser::parseWhileStatement(ASTPointer<ASTString> const& _docString) { RecursionGuard recursionGuard(*this); ASTNodeFactory nodeFactory(*this); expectToken(Token::While); expectToken(Token::LParen); ASTPointer<Expression> condition = parseExpression(); expectToken(Token::RParen); ASTPointer<Statement> body = parseStatement(); nodeFactory.setEndPositionFromNode(body); return nodeFactory.createNode<WhileStatement>(_docString, condition, body, false); } ASTPointer<WhileStatement> Parser::parseDoWhileStatement(ASTPointer<ASTString> const& _docString) { RecursionGuard recursionGuard(*this); ASTNodeFactory nodeFactory(*this); expectToken(Token::Do); ASTPointer<Statement> body = parseStatement(); expectToken(Token::While); expectToken(Token::LParen); ASTPointer<Expression> condition = parseExpression(); expectToken(Token::RParen); nodeFactory.markEndPosition(); expectToken(Token::Semicolon); return nodeFactory.createNode<WhileStatement>(_docString, condition, body, true); } ASTPointer<ForStatement> Parser::parseForStatement(ASTPointer<ASTString> const& _docString) { RecursionGuard recursionGuard(*this); ASTNodeFactory nodeFactory(*this); ASTPointer<Statement> initExpression; ASTPointer<Expression> conditionExpression; ASTPointer<ExpressionStatement> loopExpression; expectToken(Token::For); expectToken(Token::LParen); // TODO: Maybe here have some predicate like peekExpression() instead of checking for semicolon and RParen? if (m_scanner->currentToken() != Token::Semicolon) initExpression = parseSimpleStatement(ASTPointer<ASTString>()); expectToken(Token::Semicolon); if (m_scanner->currentToken() != Token::Semicolon) conditionExpression = parseExpression(); expectToken(Token::Semicolon); if (m_scanner->currentToken() != Token::RParen) loopExpression = parseExpressionStatement(ASTPointer<ASTString>()); expectToken(Token::RParen); ASTPointer<Statement> body = parseStatement(); nodeFactory.setEndPositionFromNode(body); return nodeFactory.createNode<ForStatement>( _docString, initExpression, conditionExpression, loopExpression, body ); } ASTPointer<EmitStatement> Parser::parseEmitStatement(ASTPointer<ASTString> const& _docString) { expectToken(Token::Emit, false); ASTNodeFactory nodeFactory(*this); advance(); ASTNodeFactory eventCallNodeFactory(*this); if (m_scanner->currentToken() != Token::Identifier) fatalParserError(5620_error, "Expected event name or path."); IndexAccessedPath iap; while (true) { iap.path.push_back(parseIdentifier()); if (m_scanner->currentToken() != Token::Period) break; advance(); } auto eventName = expressionFromIndexAccessStructure(iap); expectToken(Token::LParen); auto functionCallArguments = parseFunctionCallArguments(); eventCallNodeFactory.markEndPosition(); nodeFactory.markEndPosition(); expectToken(Token::RParen); auto eventCall = eventCallNodeFactory.createNode<FunctionCall>( eventName, functionCallArguments.arguments, functionCallArguments.parameterNames, functionCallArguments.parameterNameLocations ); return nodeFactory.createNode<EmitStatement>(_docString, eventCall); } ASTPointer<RevertStatement> Parser::parseRevertStatement(ASTPointer<ASTString> const& _docString) { ASTNodeFactory nodeFactory(*this); solAssert(*expectIdentifierToken() == "revert", ""); ASTNodeFactory errorCallNodeFactory(*this); solAssert(m_scanner->currentToken() == Token::Identifier, ""); IndexAccessedPath iap; while (true) { iap.path.push_back(parseIdentifier()); if (m_scanner->currentToken() != Token::Period) break; advance(); } auto errorName = expressionFromIndexAccessStructure(iap); expectToken(Token::LParen); auto functionCallArguments = parseFunctionCallArguments(); errorCallNodeFactory.markEndPosition(); nodeFactory.markEndPosition(); expectToken(Token::RParen); auto errorCall = errorCallNodeFactory.createNode<FunctionCall>( errorName, functionCallArguments.arguments, functionCallArguments.parameterNames, functionCallArguments.parameterNameLocations ); return nodeFactory.createNode<RevertStatement>(_docString, errorCall); } ASTPointer<VariableDeclarationStatement> Parser::parsePostfixVariableDeclarationStatement( ASTPointer<ASTString> const& _docString ) { RecursionGuard recursionGuard(*this); ASTNodeFactory nodeFactory(*this); expectToken(Token::Let); std::vector<ASTPointer<VariableDeclaration>> variables; variables.emplace_back(parsePostfixVariableDeclaration()); nodeFactory.setEndPositionFromNode(variables.back()); ASTPointer<Expression> value; if (m_scanner->currentToken() == Token::Assign) { advance(); value = parseExpression(); nodeFactory.setEndPositionFromNode(value); } return nodeFactory.createNode<VariableDeclarationStatement>(_docString, variables, value); } ASTPointer<VariableDeclaration> Parser::parsePostfixVariableDeclaration() { RecursionGuard recursionGuard(*this); ASTNodeFactory nodeFactory(*this); ASTPointer<StructuredDocumentation> const documentation = parseStructuredDocumentation(); nodeFactory.markEndPosition(); auto [identifier, nameLocation] = expectIdentifierWithLocation(); ASTPointer<Expression> type; if (m_scanner->currentToken() == Token::Colon) { advance(); type = parseBinaryExpression(); nodeFactory.setEndPositionFromNode(type); } return nodeFactory.createNode<VariableDeclaration>( nullptr, identifier, nameLocation, nullptr, Visibility::Default, documentation, false, VariableDeclaration::Mutability::Mutable, nullptr, VariableDeclaration::Location::Unspecified, type ); } ASTPointer<TypeClassDefinition> Parser::parseTypeClassDefinition() { solAssert(m_experimentalSolidityEnabledInCurrentSourceUnit); RecursionGuard recursionGuard(*this); ASTNodeFactory nodeFactory(*this); std::vector<ASTPointer<ASTNode>> subNodes; ASTPointer<StructuredDocumentation> const documentation = parseStructuredDocumentation(); expectToken(Token::Class); // TODO: parseTypeVariable()? parseTypeVariableDeclaration()? ASTPointer<VariableDeclaration> typeVariable; { ASTNodeFactory nodeFactory(*this); nodeFactory.markEndPosition(); auto [identifier, nameLocation] = expectIdentifierWithLocation(); typeVariable = nodeFactory.createNode<VariableDeclaration>( nullptr, identifier, nameLocation, nullptr, Visibility::Default, nullptr ); } expectToken(Token::Colon); auto [name, nameLocation] = expectIdentifierWithLocation(); expectToken(Token::LBrace); while (true) { Token currentTokenValue = m_scanner->currentToken(); if (currentTokenValue == Token::RBrace) break; expectToken(Token::Function, false); subNodes.push_back(parseFunctionDefinition(false, false)); } nodeFactory.markEndPosition(); expectToken(Token::RBrace); return nodeFactory.createNode<TypeClassDefinition>( typeVariable, name, nameLocation, documentation, subNodes ); } ASTPointer<TypeClassName> Parser::parseTypeClassName() { RecursionGuard recursionGuard(*this); ASTNodeFactory nodeFactory(*this); std::variant<Token, ASTPointer<IdentifierPath>> name; if (TokenTraits::isBuiltinTypeClassName(m_scanner->currentToken())) { nodeFactory.markEndPosition(); name = m_scanner->currentToken(); advance(); } else { auto identifierPath = parseIdentifierPath(); name = identifierPath; nodeFactory.setEndPositionFromNode(identifierPath); } return nodeFactory.createNode<TypeClassName>(name); } ASTPointer<TypeClassInstantiation> Parser::parseTypeClassInstantiation() { solAssert(m_experimentalSolidityEnabledInCurrentSourceUnit); RecursionGuard recursionGuard(*this); ASTNodeFactory nodeFactory(*this); std::vector<ASTPointer<ASTNode>> subNodes; expectToken(Token::Instantiation); // TODO: parseTypeConstructor() ASTPointer<TypeName> typeConstructor = parseTypeName(); ASTPointer<ParameterList> argumentSorts; if (m_scanner->currentToken() == Token::LParen) { argumentSorts = parseParameterList(); } expectToken(Token::Colon); ASTPointer<TypeClassName> typeClassName = parseTypeClassName(); expectToken(Token::LBrace); while (true) { Token currentTokenValue = m_scanner->currentToken(); if (currentTokenValue == Token::RBrace) break; expectToken(Token::Function, false); // TODO: require body already during parsing? subNodes.push_back(parseFunctionDefinition(false, true)); } nodeFactory.markEndPosition(); expectToken(Token::RBrace); return nodeFactory.createNode<TypeClassInstantiation>( typeConstructor, argumentSorts, typeClassName, subNodes ); } ASTPointer<TypeDefinition> Parser::parseTypeDefinition() { solAssert(m_experimentalSolidityEnabledInCurrentSourceUnit); ASTNodeFactory nodeFactory(*this); expectToken(Token::Type); auto&& [name, nameLocation] = expectIdentifierWithLocation(); ASTPointer<ParameterList> arguments; if (m_scanner->currentToken() == Token::LParen) arguments = parseParameterList(); ASTPointer<Expression> expression; if (m_scanner->currentToken() == Token::Assign) { expectToken(Token::Assign); if (m_scanner->currentToken() != Token::Builtin) expression = parseExpression(); else { expectToken(Token::Builtin); expectToken(Token::LParen); expression = nodeFactory.createNode<Builtin>( std::make_shared<std::string>(m_scanner->currentLiteral()), m_scanner->currentLocation() ); expectToken(Token::StringLiteral); expectToken(Token::RParen); } } nodeFactory.markEndPosition(); expectToken(Token::Semicolon); return nodeFactory.createNode<TypeDefinition>( std::move(name), std::move(nameLocation), std::move(arguments), std::move(expression) ); } ASTPointer<Statement> Parser::parseSimpleStatement(ASTPointer<ASTString> const& _docString) { RecursionGuard recursionGuard(*this); LookAheadInfo statementType; IndexAccessedPath iap; if (m_experimentalSolidityEnabledInCurrentSourceUnit && m_scanner->currentToken() == Token::Let) return parsePostfixVariableDeclarationStatement(_docString); if (m_scanner->currentToken() == Token::LParen) { ASTNodeFactory nodeFactory(*this); size_t emptyComponents = 0; // First consume all empty components. expectToken(Token::LParen); while (m_scanner->currentToken() == Token::Comma) { advance(); emptyComponents++; } // Now see whether we have a variable declaration or an expression. std::tie(statementType, iap) = tryParseIndexAccessedPath(); switch (statementType) { case LookAheadInfo::VariableDeclaration: { std::vector<ASTPointer<VariableDeclaration>> variables; ASTPointer<Expression> value; // We have already parsed something like `(,,,,a.b.c[2][3]` VarDeclParserOptions options; options.allowLocationSpecifier = true; variables = std::vector<ASTPointer<VariableDeclaration>>(emptyComponents, nullptr); variables.push_back(parseVariableDeclaration(options, typeNameFromIndexAccessStructure(iap))); while (m_scanner->currentToken() != Token::RParen) { expectToken(Token::Comma); if (m_scanner->currentToken() == Token::Comma || m_scanner->currentToken() == Token::RParen) variables.push_back(nullptr); else variables.push_back(parseVariableDeclaration(options)); } expectToken(Token::RParen); expectToken(Token::Assign); value = parseExpression(); nodeFactory.setEndPositionFromNode(value); return nodeFactory.createNode<VariableDeclarationStatement>(_docString, variables, value); } case LookAheadInfo::Expression: { // Complete parsing the expression in the current component. std::vector<ASTPointer<Expression>> components(emptyComponents, nullptr); components.push_back(parseExpression(expressionFromIndexAccessStructure(iap))); while (m_scanner->currentToken() != Token::RParen) { expectToken(Token::Comma); if (m_scanner->currentToken() == Token::Comma || m_scanner->currentToken() == Token::RParen) components.push_back(ASTPointer<Expression>()); else components.push_back(parseExpression()); } nodeFactory.markEndPosition(); expectToken(Token::RParen); return parseExpressionStatement(_docString, nodeFactory.createNode<TupleExpression>(components, false)); } default: solAssert(false); } } else { std::tie(statementType, iap) = tryParseIndexAccessedPath(); switch (statementType) { case LookAheadInfo::VariableDeclaration: return parseVariableDeclarationStatement(_docString, typeNameFromIndexAccessStructure(iap)); case LookAheadInfo::Expression: return parseExpressionStatement(_docString, expressionFromIndexAccessStructure(iap)); default: solAssert(false); } } // FIXME: Workaround for spurious GCC 12.1 warning (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=105794) util::unreachable(); } bool Parser::IndexAccessedPath::empty() const { if (!indices.empty()) solAssert(!path.empty()); return path.empty() && indices.empty(); } std::pair<Parser::LookAheadInfo, Parser::IndexAccessedPath> Parser::tryParseIndexAccessedPath() { // These two cases are very hard to distinguish: // x[7 * 20 + 3] a; and x[7 * 20 + 3] = 9; // In the first case, x is a type name, in the second it is the name of a variable. // As an extension, we can even have: // `x.y.z[1][2] a;` and `x.y.z[1][2] = 10;` // Where in the first, x.y.z leads to a type name where in the second, it accesses structs. auto statementType = peekStatementType(); switch (statementType) { case LookAheadInfo::VariableDeclaration: case LookAheadInfo::Expression: return std::make_pair( m_experimentalSolidityEnabledInCurrentSourceUnit ? LookAheadInfo::Expression : statementType, IndexAccessedPath() ); default: break; } // At this point, we have 'Identifier "["' or 'Identifier "." Identifier' or 'ElementoryTypeName "["'. // We parse '(Identifier ("." Identifier)* |ElementaryTypeName) ( "[" Expression "]" )*' // until we can decide whether to hand this over to ExpressionStatement or create a // VariableDeclarationStatement out of it. IndexAccessedPath iap = parseIndexAccessedPath(); if (m_experimentalSolidityEnabledInCurrentSourceUnit) return std::make_pair(LookAheadInfo::Expression, std::move(iap)); if (m_scanner->currentToken() == Token::Identifier || TokenTraits::isLocationSpecifier(m_scanner->currentToken())) return std::make_pair(LookAheadInfo::VariableDeclaration, std::move(iap)); else return std::make_pair(LookAheadInfo::Expression, std::move(iap)); } ASTPointer<VariableDeclarationStatement> Parser::parseVariableDeclarationStatement( ASTPointer<ASTString> const& _docString, ASTPointer<TypeName> const& _lookAheadArrayType ) { // This does not parse multi variable declaration statements starting directly with // `(`, they are parsed in parseSimpleStatement, because they are hard to distinguish // from tuple expressions. RecursionGuard recursionGuard(*this); ASTNodeFactory nodeFactory(*this); if (_lookAheadArrayType) nodeFactory.setLocation(_lookAheadArrayType->location()); VarDeclParserOptions options; options.allowLocationSpecifier = true; std::vector<ASTPointer<VariableDeclaration>> variables; variables.emplace_back(parseVariableDeclaration(options, _lookAheadArrayType)); nodeFactory.setEndPositionFromNode(variables.back()); ASTPointer<Expression> value; if (m_scanner->currentToken() == Token::Assign) { advance(); value = parseExpression(); nodeFactory.setEndPositionFromNode(value); } return nodeFactory.createNode<VariableDeclarationStatement>(_docString, variables, value); } ASTPointer<ExpressionStatement> Parser::parseExpressionStatement( ASTPointer<ASTString> const& _docString, ASTPointer<Expression> const& _partialParserResult ) { RecursionGuard recursionGuard(*this); ASTPointer<Expression> expression = parseExpression(_partialParserResult); return ASTNodeFactory(*this, expression).createNode<ExpressionStatement>(_docString, expression); } ASTPointer<Expression> Parser::parseExpression( ASTPointer<Expression> const& _partiallyParsedExpression ) { RecursionGuard recursionGuard(*this); ASTPointer<Expression> expression = parseBinaryExpression(4, _partiallyParsedExpression); if (TokenTraits::isAssignmentOp(m_scanner->currentToken())) { Token assignmentOperator = m_scanner->currentToken(); advance(); ASTPointer<Expression> rightHandSide = parseExpression(); ASTNodeFactory nodeFactory(*this, expression); nodeFactory.setEndPositionFromNode(rightHandSide); return nodeFactory.createNode<Assignment>(expression, assignmentOperator, rightHandSide); } else if (m_scanner->currentToken() == Token::Conditional) { advance(); ASTPointer<Expression> trueExpression = parseExpression(); expectToken(Token::Colon); ASTPointer<Expression> falseExpression = parseExpression(); ASTNodeFactory nodeFactory(*this, expression); nodeFactory.setEndPositionFromNode(falseExpression); return nodeFactory.createNode<Conditional>(expression, trueExpression, falseExpression); } else return expression; } ASTPointer<Expression> Parser::parseBinaryExpression( int _minPrecedence, ASTPointer<Expression> const& _partiallyParsedExpression ) { RecursionGuard recursionGuard(*this); ASTPointer<Expression> expression = parseUnaryExpression(_partiallyParsedExpression); ASTNodeFactory nodeFactory(*this, expression); int precedence = tokenPrecedence(m_scanner->currentToken()); for (; precedence >= _minPrecedence; --precedence) while (tokenPrecedence(m_scanner->currentToken()) == precedence) { Token op = m_scanner->currentToken(); advance(); static_assert(TokenTraits::hasExpHighestPrecedence(), "Exp does not have the highest precedence"); // Parse a**b**c as a**(b**c) ASTPointer<Expression> right = (op == Token::Exp) ? parseBinaryExpression(precedence) : parseBinaryExpression(precedence + 1); nodeFactory.setEndPositionFromNode(right); expression = nodeFactory.createNode<BinaryOperation>(expression, op, right); } return expression; } int Parser::tokenPrecedence(Token _token) const { if (m_experimentalSolidityEnabledInCurrentSourceUnit) { switch (_token) { case Token::Colon: return 1000; case Token::RightArrow: return 999; default: break; } } return TokenTraits::precedence(m_scanner->currentToken()); } ASTPointer<Expression> Parser::parseUnaryExpression( ASTPointer<Expression> const& _partiallyParsedExpression ) { RecursionGuard recursionGuard(*this); ASTNodeFactory nodeFactory = _partiallyParsedExpression ? ASTNodeFactory(*this, _partiallyParsedExpression) : ASTNodeFactory(*this); Token token = m_scanner->currentToken(); if (!_partiallyParsedExpression && token == Token::Add) fatalParserError(9636_error, "Use of unary + is disallowed."); if (!_partiallyParsedExpression && (TokenTraits::isUnaryOp(token) || TokenTraits::isCountOp(token))) { // prefix expression advance(); ASTPointer<Expression> subExpression = parseUnaryExpression(); nodeFactory.setEndPositionFromNode(subExpression); return nodeFactory.createNode<UnaryOperation>(token, subExpression, true); } else { // potential postfix expression ASTPointer<Expression> subExpression = parseLeftHandSideExpression(_partiallyParsedExpression); token = m_scanner->currentToken(); if (!TokenTraits::isCountOp(token)) return subExpression; nodeFactory.markEndPosition(); advance(); return nodeFactory.createNode<UnaryOperation>(token, subExpression, false); } } ASTPointer<Expression> Parser::parseLeftHandSideExpression( ASTPointer<Expression> const& _partiallyParsedExpression ) { RecursionGuard recursionGuard(*this); ASTNodeFactory nodeFactory = _partiallyParsedExpression ? ASTNodeFactory(*this, _partiallyParsedExpression) : ASTNodeFactory(*this); ASTPointer<Expression> expression; if (_partiallyParsedExpression) expression = _partiallyParsedExpression; else if (m_scanner->currentToken() == Token::New) { expectToken(Token::New); ASTPointer<TypeName> typeName(parseTypeName()); nodeFactory.setEndPositionFromNode(typeName); expression = nodeFactory.createNode<NewExpression>(typeName); } else if (m_scanner->currentToken() == Token::Payable) { expectToken(Token::Payable); nodeFactory.markEndPosition(); auto expressionType = nodeFactory.createNode<ElementaryTypeName>( ElementaryTypeNameToken(Token::Address, 0, 0), std::make_optional(StateMutability::Payable) ); expression = nodeFactory.createNode<ElementaryTypeNameExpression>(expressionType); expectToken(Token::LParen, false); } else expression = parsePrimaryExpression(); while (true) { switch (m_scanner->currentToken()) { case Token::LBrack: { advance(); ASTPointer<Expression> index; ASTPointer<Expression> endIndex; if (m_scanner->currentToken() != Token::RBrack && m_scanner->currentToken() != Token::Colon) index = parseExpression(); if (m_scanner->currentToken() == Token::Colon) { expectToken(Token::Colon); if (m_scanner->currentToken() != Token::RBrack) endIndex = parseExpression(); nodeFactory.markEndPosition(); expectToken(Token::RBrack); expression = nodeFactory.createNode<IndexRangeAccess>(expression, index, endIndex); } else { nodeFactory.markEndPosition(); expectToken(Token::RBrack); expression = nodeFactory.createNode<IndexAccess>(expression, index); } break; } case Token::Period: { advance(); nodeFactory.markEndPosition(); SourceLocation memberLocation = currentLocation(); ASTPointer<ASTString> memberName = expectIdentifierTokenOrAddress(); expression = nodeFactory.createNode<MemberAccess>(expression, std::move(memberName), std::move(memberLocation)); break; } case Token::LParen: { advance(); auto functionCallArguments = parseFunctionCallArguments(); nodeFactory.markEndPosition(); expectToken(Token::RParen); expression = nodeFactory.createNode<FunctionCall>( expression, functionCallArguments.arguments, functionCallArguments.parameterNames, functionCallArguments.parameterNameLocations); break; } case Token::LBrace: { // See if this is followed by <identifier>, followed by ":". If not, it is not // a function call options but a Block (from a try statement). if ( m_scanner->peekNextToken() != Token::Identifier || m_scanner->peekNextNextToken() != Token::Colon ) return expression; expectToken(Token::LBrace); auto optionList = parseNamedArguments(); nodeFactory.markEndPosition(); expectToken(Token::RBrace); expression = nodeFactory.createNode<FunctionCallOptions>(expression, optionList.arguments, optionList.parameterNames); break; } default: return expression; } } } ASTPointer<Expression> Parser::parseLiteral() { RecursionGuard recursionGuard(*this); ASTNodeFactory nodeFactory(*this); Token initialToken = m_scanner->currentToken(); ASTPointer<ASTString> value = std::make_shared<std::string>(m_scanner->currentLiteral()); switch (initialToken) { case Token::TrueLiteral: case Token::FalseLiteral: case Token::Number: { nodeFactory.markEndPosition(); advance(); break; } case Token::StringLiteral: case Token::UnicodeStringLiteral: case Token::HexStringLiteral: { while (m_scanner->peekNextToken() == initialToken) { advance(); *value += m_scanner->currentLiteral(); } nodeFactory.markEndPosition(); advance(); if (m_scanner->currentToken() == Token::Illegal) fatalParserError(5428_error, to_string(m_scanner->currentError())); break; } default: solAssert(false); } if (initialToken == Token::Number && ( TokenTraits::isEtherSubdenomination(m_scanner->currentToken()) || TokenTraits::isTimeSubdenomination(m_scanner->currentToken()) )) { nodeFactory.markEndPosition(); Literal::SubDenomination subDenomination = static_cast<Literal::SubDenomination>(m_scanner->currentToken()); advance(); return nodeFactory.createNode<Literal>(initialToken, std::move(value), subDenomination); } return nodeFactory.createNode<Literal>(initialToken, std::move(value), Literal::SubDenomination::None); } ASTPointer<Expression> Parser::parsePrimaryExpression() { RecursionGuard recursionGuard(*this); ASTNodeFactory nodeFactory(*this); Token token = m_scanner->currentToken(); ASTPointer<Expression> expression; switch (token) { case Token::TrueLiteral: case Token::FalseLiteral: case Token::Number: case Token::StringLiteral: case Token::UnicodeStringLiteral: case Token::HexStringLiteral: expression = parseLiteral(); break; case Token::Identifier: nodeFactory.markEndPosition(); expression = nodeFactory.createNode<Identifier>(getLiteralAndAdvance()); break; case Token::Type: // Inside expressions "type" is the name of a special, globally-available function. nodeFactory.markEndPosition(); advance(); expression = nodeFactory.createNode<Identifier>(std::make_shared<ASTString>("type")); break; case Token::LParen: case Token::LBrack: { // Tuple/parenthesized expression or inline array/bracketed expression. // Special cases: ()/[] is empty tuple/array type, (x) is not a real tuple, // (x,) is one-dimensional tuple, elements in arrays cannot be left out, only in tuples. advance(); std::vector<ASTPointer<Expression>> components; Token oppositeToken = (token == Token::LParen ? Token::RParen : Token::RBrack); bool isArray = (token == Token::LBrack); if (m_scanner->currentToken() != oppositeToken) while (true) { if (m_scanner->currentToken() != Token::Comma && m_scanner->currentToken() != oppositeToken) components.push_back(parseExpression()); else if (isArray) parserError(4799_error, "Expected expression (inline array elements cannot be omitted)."); else components.push_back(ASTPointer<Expression>()); if (m_scanner->currentToken() == oppositeToken) break; expectToken(Token::Comma); } nodeFactory.markEndPosition(); expectToken(oppositeToken); expression = nodeFactory.createNode<TupleExpression>(components, isArray); break; } case Token::Illegal: fatalParserError(8936_error, to_string(m_scanner->currentError())); break; default: if (TokenTraits::isElementaryTypeName(token)) { //used for casts unsigned firstSize; unsigned secondSize; std::tie(firstSize, secondSize) = m_scanner->currentTokenInfo(); auto expressionType = nodeFactory.createNode<ElementaryTypeName>( ElementaryTypeNameToken(m_scanner->currentToken(), firstSize, secondSize) ); expression = nodeFactory.createNode<ElementaryTypeNameExpression>(expressionType); advance(); } else fatalParserError(6933_error, "Expected primary expression."); break; } return expression; } std::vector<ASTPointer<Expression>> Parser::parseFunctionCallListArguments() { RecursionGuard recursionGuard(*this); std::vector<ASTPointer<Expression>> arguments; if (m_scanner->currentToken() != Token::RParen) { arguments.push_back(parseExpression()); while (m_scanner->currentToken() != Token::RParen) { expectToken(Token::Comma); arguments.push_back(parseExpression()); } } return arguments; } Parser::FunctionCallArguments Parser::parseFunctionCallArguments() { RecursionGuard recursionGuard(*this); FunctionCallArguments ret; Token token = m_scanner->currentToken(); if (token == Token::LBrace) { // call({arg1 : 1, arg2 : 2 }) expectToken(Token::LBrace); ret = parseNamedArguments(); expectToken(Token::RBrace); } else ret.arguments = parseFunctionCallListArguments(); return ret; } Parser::FunctionCallArguments Parser::parseNamedArguments() { FunctionCallArguments ret; bool first = true; while (m_scanner->currentToken() != Token::RBrace) { if (!first) expectToken(Token::Comma); auto identifierWithLocation = expectIdentifierWithLocation(); // Add name ret.parameterNames.emplace_back(std::move(identifierWithLocation.first)); // Add location ret.parameterNameLocations.emplace_back(std::move(identifierWithLocation.second)); expectToken(Token::Colon); ret.arguments.emplace_back(parseExpression()); if ( m_scanner->currentToken() == Token::Comma && m_scanner->peekNextToken() == Token::RBrace ) { parserError(2074_error, "Unexpected trailing comma."); advance(); } first = false; } return ret; } bool Parser::variableDeclarationStart() { Token currentToken = m_scanner->currentToken(); return currentToken == Token::Identifier || currentToken == Token::Mapping || TokenTraits::isElementaryTypeName(currentToken) || (currentToken == Token::Function && m_scanner->peekNextToken() == Token::LParen); } std::optional<std::string> Parser::findLicenseString(std::vector<ASTPointer<ASTNode>> const& _nodes) { // We circumvent the scanner here, because it skips non-docstring comments. static std::regex const licenseNameRegex("([a-zA-Z0-9 ()+.-]+)"); static std::regex const licenseDeclarationRegex("SPDX-License-Identifier:\\s*(.+?)([\n\r]|(\\*/))"); // Search inside all parts of the source not covered by parsed nodes. // This will leave e.g. "global comments". using iter = std::string::const_iterator; std::vector<std::pair<iter, iter>> sequencesToSearch; std::string const& source = m_scanner->charStream().source(); sequencesToSearch.emplace_back(source.begin(), source.end()); for (ASTPointer<ASTNode> const& node: _nodes) if (node->location().hasText()) { sequencesToSearch.back().second = source.begin() + node->location().start; sequencesToSearch.emplace_back(source.begin() + node->location().end, source.end()); } std::vector<std::string> licenseNames; for (auto const& [start, end]: sequencesToSearch) { auto declarationsBegin = std::sregex_iterator(start, end, licenseDeclarationRegex); auto declarationsEnd = std::sregex_iterator(); for (std::sregex_iterator declIt = declarationsBegin; declIt != declarationsEnd; ++declIt) if (!declIt->empty()) { std::string license = boost::trim_copy(std::string((*declIt)[1])); licenseNames.emplace_back(std::move(license)); } } if (licenseNames.size() == 1) { std::string const& license = licenseNames.front(); if (regex_match(license, licenseNameRegex)) return license; else parserError( 1114_error, {-1, -1, m_scanner->currentLocation().sourceName}, "Invalid SPDX license identifier." ); } else if (licenseNames.empty()) parserWarning( 1878_error, {-1, -1, m_scanner->currentLocation().sourceName}, "SPDX license identifier not provided in source file. " "Before publishing, consider adding a comment containing " "\"SPDX-License-Identifier: <SPDX-License>\" to each source file. " "Use \"SPDX-License-Identifier: UNLICENSED\" for non-open-source code. " "Please see https://spdx.org for more information." ); else parserError( 3716_error, {-1, -1, m_scanner->currentLocation().sourceName}, "Multiple SPDX license identifiers found in source file. " "Use \"AND\" or \"OR\" to combine multiple licenses. " "Please see https://spdx.org for more information." ); return {}; } Parser::LookAheadInfo Parser::peekStatementType() const { // Distinguish between variable declaration (and potentially assignment) and expression statement // (which include assignments to other expressions and pre-declared variables). // We have a variable declaration if we get a keyword that specifies a type name. // If it is an identifier or an elementary type name followed by an identifier // or a mutability specifier, we also have a variable declaration. // If we get an identifier followed by a "[" or ".", it can be both ("lib.type[9] a;" or "variable.el[9] = 7;"). // In all other cases, we have an expression statement. Token token(m_scanner->currentToken()); bool mightBeTypeName = (TokenTraits::isElementaryTypeName(token) || token == Token::Identifier); if (token == Token::Mapping || token == Token::Function) return LookAheadInfo::VariableDeclaration; if (mightBeTypeName) { Token next = m_scanner->peekNextToken(); // So far we only allow ``address payable`` in variable declaration statements and in no other // kind of statement. This means, for example, that we do not allow type expressions of the form // ``address payable;``. // If we want to change this in the future, we need to consider another scanner token here. if (TokenTraits::isElementaryTypeName(token) && TokenTraits::isStateMutabilitySpecifier(next)) return LookAheadInfo::VariableDeclaration; if (next == Token::Identifier || TokenTraits::isLocationSpecifier(next)) return LookAheadInfo::VariableDeclaration; if (next == Token::LBrack || next == Token::Period) return LookAheadInfo::IndexAccessStructure; } return LookAheadInfo::Expression; } Parser::IndexAccessedPath Parser::parseIndexAccessedPath() { IndexAccessedPath iap; if (m_scanner->currentToken() == Token::Identifier) { iap.path.push_back(parseIdentifier()); while (m_scanner->currentToken() == Token::Period) { advance(); if (m_experimentalSolidityEnabledInCurrentSourceUnit && m_scanner->currentToken() == Token::Number) { ASTNodeFactory nodeFactory(*this); nodeFactory.markEndPosition(); iap.path.push_back(nodeFactory.createNode<Identifier>(getLiteralAndAdvance())); } else iap.path.push_back(parseIdentifierOrAddress()); } } else { unsigned firstNum; unsigned secondNum; std::tie(firstNum, secondNum) = m_scanner->currentTokenInfo(); auto expressionType = ASTNodeFactory(*this).createNode<ElementaryTypeName>( ElementaryTypeNameToken(m_scanner->currentToken(), firstNum, secondNum) ); iap.path.push_back(ASTNodeFactory(*this).createNode<ElementaryTypeNameExpression>(expressionType)); advance(); } while (m_scanner->currentToken() == Token::LBrack) { expectToken(Token::LBrack); ASTPointer<Expression> index; if (m_scanner->currentToken() != Token::RBrack && m_scanner->currentToken() != Token::Colon) index = parseExpression(); SourceLocation indexLocation = iap.path.front()->location(); if (m_scanner->currentToken() == Token::Colon) { expectToken(Token::Colon); ASTPointer<Expression> endIndex; if (m_scanner->currentToken() != Token::RBrack) endIndex = parseExpression(); indexLocation.end = currentLocation().end; iap.indices.emplace_back(IndexAccessedPath::Index{index, {endIndex}, indexLocation}); expectToken(Token::RBrack); } else { indexLocation.end = currentLocation().end; iap.indices.emplace_back(IndexAccessedPath::Index{index, {}, indexLocation}); expectToken(Token::RBrack); } } return iap; } ASTPointer<TypeName> Parser::typeNameFromIndexAccessStructure(Parser::IndexAccessedPath const& _iap) { if (_iap.empty()) return {}; RecursionGuard recursionGuard(*this); ASTNodeFactory nodeFactory(*this); SourceLocation location = _iap.path.front()->location(); location.end = _iap.path.back()->location().end; nodeFactory.setLocation(location); ASTPointer<TypeName> type; if (auto typeName = dynamic_cast<ElementaryTypeNameExpression const*>(_iap.path.front().get())) { solAssert(_iap.path.size() == 1, ""); type = nodeFactory.createNode<ElementaryTypeName>(typeName->type().typeName()); } else { std::vector<ASTString> path; std::vector<SourceLocation> pathLocations; for (auto const& el: _iap.path) { auto& identifier = dynamic_cast<Identifier const&>(*el); path.push_back(identifier.name()); pathLocations.push_back(identifier.location()); } type = nodeFactory.createNode<UserDefinedTypeName>(nodeFactory.createNode<IdentifierPath>(path, pathLocations)); } for (auto const& lengthExpression: _iap.indices) { if (lengthExpression.end) parserError(5464_error, lengthExpression.location, "Expected array length expression."); nodeFactory.setLocation(lengthExpression.location); type = nodeFactory.createNode<ArrayTypeName>(type, lengthExpression.start); } return type; } ASTPointer<Expression> Parser::expressionFromIndexAccessStructure( Parser::IndexAccessedPath const& _iap ) { if (_iap.empty()) return {}; RecursionGuard recursionGuard(*this); ASTNodeFactory nodeFactory(*this, _iap.path.front()); ASTPointer<Expression> expression(_iap.path.front()); for (size_t i = 1; i < _iap.path.size(); ++i) { SourceLocation location(_iap.path.front()->location()); location.end = _iap.path[i]->location().end; nodeFactory.setLocation(location); Identifier const& identifier = dynamic_cast<Identifier const&>(*_iap.path[i]); expression = nodeFactory.createNode<MemberAccess>( expression, std::make_shared<ASTString>(identifier.name()), identifier.location() ); } for (auto const& index: _iap.indices) { nodeFactory.setLocation(index.location); if (index.end) expression = nodeFactory.createNode<IndexRangeAccess>(expression, index.start, *index.end); else expression = nodeFactory.createNode<IndexAccess>(expression, index.start); } return expression; } ASTPointer<ParameterList> Parser::createEmptyParameterList() { RecursionGuard recursionGuard(*this); ASTNodeFactory nodeFactory(*this); nodeFactory.setLocationEmpty(); return nodeFactory.createNode<ParameterList>(std::vector<ASTPointer<VariableDeclaration>>()); } ASTPointer<ASTString> Parser::expectIdentifierToken() { expectToken(Token::Identifier, false /* do not advance */); return getLiteralAndAdvance(); } ASTPointer<ASTString> Parser::expectIdentifierTokenOrAddress() { ASTPointer<ASTString> result; if (m_scanner->currentToken() == Token::Address) { result = std::make_shared<ASTString>("address"); advance(); } else { expectToken(Token::Identifier, false /* do not advance */); result = getLiteralAndAdvance(); } return result; } ASTPointer<ASTString> Parser::getLiteralAndAdvance() { ASTPointer<ASTString> identifier = std::make_shared<ASTString>(m_scanner->currentLiteral()); advance(); return identifier; } bool Parser::isQuotedPath() const { return m_scanner->currentToken() == Token::StringLiteral; } bool Parser::isStdlibPath() const { return m_experimentalSolidityEnabledInCurrentSourceUnit && m_scanner->currentToken() == Token::Identifier && m_scanner->currentLiteral() == "std"; } ASTPointer<ASTString> Parser::getStdlibImportPathAndAdvance() { ASTPointer<ASTString> std = expectIdentifierToken(); if (m_scanner->currentToken() == Token::Period) advance(); ASTPointer<ASTString> library = expectIdentifierToken(); return std::make_shared<ASTString>(*std + "." + *library); } }
87,006
C++
.cpp
2,542
31.375295
149
0.7638
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
3,157
PredicateSort.cpp
ethereum_solidity/libsolidity/formal/PredicateSort.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libsolidity/formal/PredicateSort.h> #include <libsolidity/formal/SMTEncoder.h> #include <libsolidity/formal/SymbolicTypes.h> using namespace solidity::util; using namespace solidity::smtutil; namespace solidity::frontend::smt { SortPointer interfaceSort(ContractDefinition const& _contract, SymbolicState& _state) { return std::make_shared<FunctionSort>( std::vector<SortPointer>{_state.thisAddressSort()} + getBuiltInFunctionsSorts(_state) + std::vector<SortPointer>{_state.stateSort()} + stateSorts(_contract), SortProvider::boolSort ); } SortPointer nondetInterfaceSort(ContractDefinition const& _contract, SymbolicState& _state) { auto varSorts = stateSorts(_contract); std::vector<SortPointer> stateSort{_state.stateSort()}; return std::make_shared<FunctionSort>( std::vector<SortPointer>{_state.errorFlagSort(), _state.thisAddressSort()} + getBuiltInFunctionsSorts(_state) + stateSort + varSorts + stateSort + varSorts, SortProvider::boolSort ); } SortPointer constructorSort(ContractDefinition const& _contract, SymbolicState& _state) { if (auto const* constructor = _contract.constructor()) return functionSort(*constructor, &_contract, _state); auto varSorts = stateSorts(_contract); std::vector<SortPointer> stateSort{_state.stateSort()}; return std::make_shared<FunctionSort>( std::vector<SortPointer>{_state.errorFlagSort(), _state.thisAddressSort()} + getBuiltInFunctionsSorts(_state) + std::vector<SortPointer>{_state.txSort(), _state.stateSort(), _state.stateSort()} + varSorts + varSorts, SortProvider::boolSort ); } SortPointer functionSort(FunctionDefinition const& _function, ContractDefinition const* _contract, SymbolicState& _state) { auto smtSort = [](auto _var) { return smt::smtSortAbstractFunction(*_var->type()); }; auto varSorts = _contract ? stateSorts(*_contract) : std::vector<SortPointer>{}; auto inputSorts = applyMap(_function.parameters(), smtSort); auto outputSorts = applyMap(_function.returnParameters(), smtSort); return std::make_shared<FunctionSort>( std::vector<SortPointer>{_state.errorFlagSort(), _state.thisAddressSort()} + getBuiltInFunctionsSorts(_state) + std::vector<SortPointer>{_state.txSort(), _state.stateSort()} + varSorts + inputSorts + std::vector<SortPointer>{_state.stateSort()} + varSorts + inputSorts + outputSorts, SortProvider::boolSort ); } SortPointer functionBodySort(FunctionDefinition const& _function, ContractDefinition const* _contract, SymbolicState& _state) { auto fSort = std::dynamic_pointer_cast<FunctionSort>(functionSort(_function, _contract, _state)); solAssert(fSort, ""); auto smtSort = [](auto _var) { return smt::smtSortAbstractFunction(*_var->type()); }; return std::make_shared<FunctionSort>( fSort->domain + applyMap(SMTEncoder::localVariablesIncludingModifiers(_function, _contract), smtSort), SortProvider::boolSort ); } SortPointer arity0FunctionSort() { return std::make_shared<FunctionSort>( std::vector<SortPointer>(), SortProvider::boolSort ); } /// Helpers std::vector<SortPointer> stateSorts(ContractDefinition const& _contract) { return applyMap( SMTEncoder::stateVariablesIncludingInheritedAndPrivate(_contract), [](auto _var) { return smt::smtSortAbstractFunction(*_var->type()); } ); } std::vector<SortPointer> getBuiltInFunctionsSorts(SymbolicState& _state) { if (_state.hasBytesConcatFunction()) return {_state.abiSort(), _state.bytesConcatSort(), _state.cryptoSort()}; return {_state.abiSort(), _state.cryptoSort()}; } }
4,249
C++
.cpp
110
36.3
125
0.769231
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
3,158
ModelChecker.cpp
ethereum_solidity/libsolidity/formal/ModelChecker.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libsolidity/formal/ModelChecker.h> #include <boost/process.hpp> #include <range/v3/algorithm/any_of.hpp> #include <range/v3/view.hpp> using namespace solidity; using namespace solidity::util; using namespace solidity::langutil; using namespace solidity::frontend; using namespace solidity::smtutil; ModelChecker::ModelChecker( ErrorReporter& _errorReporter, langutil::CharStreamProvider const& _charStreamProvider, std::map<h256, std::string> const& _smtlib2Responses, ModelCheckerSettings _settings, ReadCallback::Callback const& _smtCallback ): m_errorReporter(_errorReporter), m_provedSafeReporter(m_provedSafeLogs), m_settings(std::move(_settings)), m_context(), m_bmc(m_context, m_uniqueErrorReporter, m_unsupportedErrorReporter, m_provedSafeReporter, _smtlib2Responses, _smtCallback, m_settings, _charStreamProvider), m_chc(m_context, m_uniqueErrorReporter, m_unsupportedErrorReporter, m_provedSafeReporter, _smtlib2Responses, _smtCallback, m_settings, _charStreamProvider) { } // TODO This should be removed for 0.9.0. bool ModelChecker::isPragmaPresent(std::vector<std::shared_ptr<SourceUnit>> const& _sources) { return ranges::any_of(_sources, [](auto _source) { return _source && _source->annotation().experimentalFeatures.count(ExperimentalFeature::SMTChecker); }); } void ModelChecker::checkRequestedSourcesAndContracts(std::vector<std::shared_ptr<SourceUnit>> const& _sources) { std::map<std::string, std::set<std::string>> exist; for (auto const& source: _sources) for (auto node: source->nodes()) if (auto contract = std::dynamic_pointer_cast<ContractDefinition>(node)) exist[contract->sourceUnitName()].insert(contract->name()); // Requested sources for (auto const& sourceName: m_settings.contracts.contracts | ranges::views::keys) { if (!exist.count(sourceName)) { m_uniqueErrorReporter.warning( 9134_error, SourceLocation(), "Requested source \"" + sourceName + "\" does not exist." ); continue; } auto const& source = exist.at(sourceName); // Requested contracts in source `s`. for (auto const& contract: m_settings.contracts.contracts.at(sourceName)) if (!source.count(contract)) m_uniqueErrorReporter.warning( 7400_error, SourceLocation(), "Requested contract \"" + contract + "\" does not exist in source \"" + sourceName + "\"." ); } } void ModelChecker::analyze(SourceUnit const& _source) { // TODO This should be removed for 0.9.0. if (_source.annotation().experimentalFeatures.count(ExperimentalFeature::SMTChecker)) { PragmaDirective const* smtPragma = nullptr; for (auto node: _source.nodes()) if (auto pragma = std::dynamic_pointer_cast<PragmaDirective>(node)) if ( pragma->literals().size() >= 2 && pragma->literals().at(1) == "SMTChecker" ) { smtPragma = pragma.get(); break; } solAssert(smtPragma, ""); m_uniqueErrorReporter.warning( 5523_error, smtPragma->location(), "The SMTChecker pragma has been deprecated and will be removed in the future. " "Please use the \"model checker engine\" compiler setting to activate the SMTChecker instead. " "If the pragma is enabled, all engines will be used." ); } if (m_settings.engine.none()) return; if (m_settings.engine.chc) m_chc.analyze(_source); std::map<ASTNode const*, std::set<VerificationTargetType>, smt::EncodingContext::IdCompare> solvedTargets; for (auto const& [node, targets]: m_chc.safeTargets()) for (auto const& target: targets) solvedTargets[node].insert(target.type); for (auto const& [node, targets]: m_chc.unsafeTargets()) solvedTargets[node] += targets | ranges::views::keys; if (m_settings.engine.bmc) m_bmc.analyze(_source, solvedTargets); if (m_settings.showUnsupported) { m_errorReporter.append(m_unsupportedErrorReporter.errors()); m_unsupportedErrorReporter.clear(); } else if (!m_unsupportedErrorReporter.errors().empty()) m_errorReporter.warning( 5724_error, {}, "SMTChecker: " + std::to_string(m_unsupportedErrorReporter.errors().size()) + " unsupported language feature(s)." " Enable the model checker option \"show unsupported\" to see all of them." ); m_errorReporter.append(m_uniqueErrorReporter.errors()); m_uniqueErrorReporter.clear(); if (m_settings.showProvedSafe) { m_errorReporter.append(m_provedSafeReporter.errors()); m_provedSafeReporter.clear(); } } std::vector<std::string> ModelChecker::unhandledQueries() { return m_bmc.unhandledQueries() + m_chc.unhandledQueries(); } SMTSolverChoice ModelChecker::availableSolvers() { smtutil::SMTSolverChoice available = smtutil::SMTSolverChoice::SMTLIB2(); available.eld = !boost::process::search_path("eld").empty(); available.cvc5 = !boost::process::search_path("cvc5").empty(); #ifdef EMSCRIPTEN_BUILD available.z3 = true; #else available.z3 = !boost::process::search_path("z3").empty(); #endif return available; } SMTSolverChoice ModelChecker::checkRequestedSolvers(SMTSolverChoice _enabled, ErrorReporter& _errorReporter) { SMTSolverChoice availableSolvers{ModelChecker::availableSolvers()}; if (_enabled.cvc5 && !availableSolvers.cvc5) { _enabled.cvc5 = false; _errorReporter.warning( 4902_error, SourceLocation(), "Solver cvc5 was selected for SMTChecker but it is not available." ); } if (_enabled.eld && !availableSolvers.eld) { _enabled.eld = false; _errorReporter.warning( 4458_error, SourceLocation(), #if defined(__linux) || defined(__APPLE__) "Solver Eldarica was selected for SMTChecker but it was not found in the system." #else "Solver Eldarica was selected for SMTChecker but it is only supported on Linux and MacOS." #endif ); } if (_enabled.z3 && !availableSolvers.z3) { _enabled.z3 = false; _errorReporter.warning( 8158_error, SourceLocation(), "Solver z3 was selected for SMTChecker but it is not available." ); } return _enabled; }
6,617
C++
.cpp
186
32.854839
157
0.748399
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,159
EldaricaCHCSmtLib2Interface.cpp
ethereum_solidity/libsolidity/formal/EldaricaCHCSmtLib2Interface.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libsolidity/formal/EldaricaCHCSmtLib2Interface.h> #include <libsolidity/interface/UniversalCallback.h> using namespace solidity::frontend::smt; EldaricaCHCSmtLib2Interface::EldaricaCHCSmtLib2Interface( frontend::ReadCallback::Callback _smtCallback, std::optional<unsigned int> _queryTimeout, bool computeInvariants ): CHCSmtLib2Interface({}, std::move(_smtCallback), _queryTimeout), m_computeInvariants(computeInvariants) { } std::string EldaricaCHCSmtLib2Interface::querySolver(std::string const& _input) { if (auto* universalCallback = m_smtCallback.target<frontend::UniversalCallback>()) universalCallback->smtCommand().setEldarica(m_queryTimeout, m_computeInvariants); return CHCSmtLib2Interface::querySolver(_input); }
1,432
C++
.cpp
30
45.833333
106
0.811917
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,160
PredicateInstance.cpp
ethereum_solidity/libsolidity/formal/PredicateInstance.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libsolidity/formal/PredicateInstance.h> #include <libsolidity/formal/EncodingContext.h> #include <libsolidity/formal/SMTEncoder.h> using namespace solidity::util; using namespace solidity::smtutil; namespace solidity::frontend::smt { smtutil::Expression interfacePre(Predicate const& _pred, ContractDefinition const& _contract, EncodingContext& _context) { auto& state = _context.state(); std::vector<smtutil::Expression> stateExprs = getStateExpressionsForInterfacePre(state); return _pred(stateExprs + initialStateVariables(_contract, _context)); } smtutil::Expression interface(Predicate const& _pred, ContractDefinition const& _contract, EncodingContext& _context) { auto const& state = _context.state(); std::vector<smtutil::Expression> stateExprs = getStateExpressionsForInterface(state); return _pred(stateExprs + currentStateVariables(_contract, _context)); } smtutil::Expression nondetInterface( Predicate const& _pred, ContractDefinition const& _contract, EncodingContext& _context, unsigned _preIdx, unsigned _postIdx) { auto const& state = _context.state(); std::vector<smtutil::Expression> stateExprs = getStateExpressionsForNondetInterface(state); return _pred( stateExprs + std::vector<smtutil::Expression>{_context.state().state(_preIdx)} + stateVariablesAtIndex(_preIdx, _contract, _context) + std::vector<smtutil::Expression>{_context.state().state(_postIdx)} + stateVariablesAtIndex(_postIdx, _contract, _context) ); } smtutil::Expression constructor(Predicate const& _pred, EncodingContext& _context) { auto const& contract = dynamic_cast<ContractDefinition const&>(*_pred.programNode()); if (auto const* constructor = contract.constructor()) return _pred(currentFunctionVariablesForDefinition(*constructor, &contract, _context)); auto& state = _context.state(); std::vector<smtutil::Expression> stateExprs = getStateExpressionsForConstructor(state); return _pred(stateExprs + initialStateVariables(contract, _context) + currentStateVariables(contract, _context)); } smtutil::Expression constructorCall(Predicate const& _pred, EncodingContext& _context, bool _internal) { auto const& contract = dynamic_cast<ContractDefinition const&>(*_pred.programNode()); if (auto const* constructor = contract.constructor()) return _pred(currentFunctionVariablesForCall(*constructor, &contract, _context, _internal)); auto& state = _context.state(); std::vector<smtutil::Expression> stateExprs = getStateExpressionsForCall(state, _internal); state.newState(); stateExprs += std::vector<smtutil::Expression>{state.state()}; stateExprs += currentStateVariables(contract, _context); stateExprs += newStateVariables(contract, _context); return _pred(stateExprs); } smtutil::Expression function( Predicate const& _pred, ContractDefinition const* _contract, EncodingContext& _context ) { auto const& function = dynamic_cast<FunctionDefinition const&>(*_pred.programNode()); return _pred(currentFunctionVariablesForDefinition(function, _contract, _context)); } smtutil::Expression functionCall( Predicate const& _pred, ContractDefinition const* _contract, EncodingContext& _context ) { auto const& function = dynamic_cast<FunctionDefinition const&>(*_pred.programNode()); return _pred(currentFunctionVariablesForCall(function, _contract, _context)); } smtutil::Expression functionBlock( Predicate const& _pred, FunctionDefinition const& _function, ContractDefinition const* _contract, EncodingContext& _context ) { return _pred(currentBlockVariables(_function, _contract, _context)); } /// Helpers std::vector<smtutil::Expression> initialStateVariables(ContractDefinition const& _contract, EncodingContext& _context) { return stateVariablesAtIndex(0, _contract, _context); } std::vector<smtutil::Expression> stateVariablesAtIndex(unsigned _index, ContractDefinition const& _contract, EncodingContext& _context) { return applyMap( SMTEncoder::stateVariablesIncludingInheritedAndPrivate(_contract), [&](auto _var) { return _context.variable(*_var)->valueAtIndex(_index); } ); } std::vector<smtutil::Expression> currentStateVariables(ContractDefinition const& _contract, EncodingContext& _context) { return applyMap( SMTEncoder::stateVariablesIncludingInheritedAndPrivate(_contract), [&](auto _var) { return _context.variable(*_var)->currentValue(); } ); } std::vector<smtutil::Expression> newStateVariables(ContractDefinition const& _contract, EncodingContext& _context) { return applyMap( SMTEncoder::stateVariablesIncludingInheritedAndPrivate(_contract), [&](auto _var) { return _context.variable(*_var)->increaseIndex(); } ); } std::vector<smtutil::Expression> currentFunctionVariablesForDefinition( FunctionDefinition const& _function, ContractDefinition const* _contract, EncodingContext& _context ) { auto& state = _context.state(); std::vector<smtutil::Expression> exprs = getStateExpressionsForDefinition(state); exprs += _contract ? initialStateVariables(*_contract, _context) : std::vector<smtutil::Expression>{}; exprs += applyMap(_function.parameters(), [&](auto _var) { return _context.variable(*_var)->valueAtIndex(0); }); exprs += std::vector<smtutil::Expression>{state.state()}; exprs += _contract ? currentStateVariables(*_contract, _context) : std::vector<smtutil::Expression>{}; exprs += applyMap(_function.parameters(), [&](auto _var) { return _context.variable(*_var)->currentValue(); }); exprs += applyMap(_function.returnParameters(), [&](auto _var) { return _context.variable(*_var)->currentValue(); }); return exprs; } std::vector<smtutil::Expression> currentFunctionVariablesForCall( FunctionDefinition const& _function, ContractDefinition const* _contract, EncodingContext& _context, bool _internal ) { auto& state = _context.state(); std::vector<smtutil::Expression> exprs = getStateExpressionsForCall(state, _internal); exprs += _contract ? currentStateVariables(*_contract, _context) : std::vector<smtutil::Expression>{}; exprs += applyMap(_function.parameters(), [&](auto _var) { return _context.variable(*_var)->currentValue(); }); state.newState(); exprs += std::vector<smtutil::Expression>{state.state()}; exprs += _contract ? newStateVariables(*_contract, _context) : std::vector<smtutil::Expression>{}; exprs += applyMap(_function.parameters(), [&](auto _var) { return _context.variable(*_var)->increaseIndex(); }); exprs += applyMap(_function.returnParameters(), [&](auto _var) { return _context.variable(*_var)->currentValue(); }); return exprs; } std::vector<smtutil::Expression> currentBlockVariables(FunctionDefinition const& _function, ContractDefinition const* _contract, EncodingContext& _context) { return currentFunctionVariablesForDefinition(_function, _contract, _context) + applyMap( SMTEncoder::localVariablesIncludingModifiers(_function, _contract), [&](auto _var) { return _context.variable(*_var)->currentValue(); } ); } std::vector<smtutil::Expression> getStateExpressionsForInterfacePre(SymbolicState const& _state) { if (_state.hasBytesConcatFunction()) return {_state.thisAddress(0), _state.abi(0), _state.bytesConcat(0), _state.crypto(0), _state.state(0)}; return {_state.thisAddress(0), _state.abi(0), _state.crypto(0), _state.state(0)}; } std::vector<smtutil::Expression> getStateExpressionsForInterface(SymbolicState const& _state) { if (_state.hasBytesConcatFunction()) return {_state.thisAddress(0), _state.abi(0), _state.bytesConcat(0), _state.crypto(0), _state.state()}; return {_state.thisAddress(0), _state.abi(0), _state.crypto(0), _state.state()}; } std::vector<smtutil::Expression> getStateExpressionsForNondetInterface(SymbolicState const& _state) { if (_state.hasBytesConcatFunction()) return {_state.errorFlag().currentValue(), _state.thisAddress(), _state.abi(), _state.bytesConcat(), _state.crypto()}; return {_state.errorFlag().currentValue(), _state.thisAddress(), _state.abi(), _state.crypto()}; } std::vector<smtutil::Expression> getStateExpressionsForConstructor(SymbolicState const& _state) { if (_state.hasBytesConcatFunction()) return {_state.errorFlag().currentValue(), _state.thisAddress(0), _state.abi(0), _state.bytesConcat(0), _state.crypto(0), _state.tx(0), _state.state(0), _state.state()}; return {_state.errorFlag().currentValue(), _state.thisAddress(0), _state.abi(0), _state.crypto(0), _state.tx(0), _state.state(0), _state.state()}; } std::vector<smtutil::Expression> getStateExpressionsForCall(SymbolicState const& _state, bool _internal) { if (_state.hasBytesConcatFunction()) return {_state.errorFlag().currentValue(), _internal ? _state.thisAddress(0) : _state.thisAddress(), _state.abi(0), _state.bytesConcat(0), _state.crypto(0), _internal ? _state.tx(0) : _state.tx(), _state.state()}; return {_state.errorFlag().currentValue(), _internal ? _state.thisAddress(0) : _state.thisAddress(), _state.abi(0), _state.crypto(0), _internal ? _state.tx(0) : _state.tx(), _state.state()}; } std::vector<smtutil::Expression> getStateExpressionsForDefinition(SymbolicState const& _state) { if (_state.hasBytesConcatFunction()) return {_state.errorFlag().currentValue(), _state.thisAddress(0), _state.abi(0), _state.bytesConcat(0), _state.crypto(0), _state.tx(0), _state.state(0)}; return {_state.errorFlag().currentValue(), _state.thisAddress(0), _state.abi(0), _state.crypto(0), _state.tx(0), _state.state(0)}; } }
10,083
C++
.cpp
211
45.843602
155
0.763313
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
3,161
Invariants.cpp
ethereum_solidity/libsolidity/formal/Invariants.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libsolidity/formal/Invariants.h> #include <libsolidity/formal/ExpressionFormatter.h> #include <libsolidity/formal/SMTEncoder.h> #include <libsolutil/Algorithms.h> #include <boost/algorithm/string.hpp> using boost::algorithm::starts_with; using namespace solidity; using namespace solidity::smtutil; using namespace solidity::frontend::smt; namespace solidity::frontend::smt { std::map<Predicate const*, std::set<std::string>> collectInvariants( smtutil::Expression const& _proof, std::set<Predicate const*> const& _predicates, ModelCheckerInvariants const& _invariantsSetting ) { std::set<std::string> targets; if (_invariantsSetting.has(InvariantType::Contract)) targets.insert("interface_"); if (_invariantsSetting.has(InvariantType::Reentrancy)) targets.insert("nondet_interface_"); std::map<std::string, std::pair<smtutil::Expression, smtutil::Expression>> equalities; // Collect equalities where one of the sides is a predicate we're interested in. util::BreadthFirstSearch<smtutil::Expression const*>{{&_proof}}.run([&](auto&& _expr, auto&& _addChild) { if (_expr->name == "=") for (auto const& t: targets) { auto arg0 = _expr->arguments.at(0); auto arg1 = _expr->arguments.at(1); if (starts_with(arg0.name, t)) equalities.insert({arg0.name, {arg0, std::move(arg1)}}); else if (starts_with(arg1.name, t)) equalities.insert({arg1.name, {arg1, std::move(arg0)}}); } for (auto const& arg: _expr->arguments) _addChild(&arg); }); std::map<Predicate const*, std::set<std::string>> invariants; for (auto pred: _predicates) { auto predName = pred->functor().name; if (!equalities.count(predName)) continue; solAssert(pred->contextContract(), ""); auto const& [predExpr, invExpr] = equalities.at(predName); static std::set<std::string> const ignore{"true", "false"}; auto r = substitute(invExpr, pred->expressionSubstitution(predExpr)); // No point in reporting true/false as invariants. if (!ignore.count(r.name)) invariants[pred].insert(toSolidityStr(r)); } return invariants; } }
2,771
C++
.cpp
69
37.565217
106
0.745346
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
3,163
Cvc5SMTLib2Interface.cpp
ethereum_solidity/libsolidity/formal/Cvc5SMTLib2Interface.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libsolidity/formal/Cvc5SMTLib2Interface.h> #include <libsolidity/interface/UniversalCallback.h> using namespace solidity::frontend::smt; Cvc5SMTLib2Interface::Cvc5SMTLib2Interface( frontend::ReadCallback::Callback _smtCallback, std::optional<unsigned int> _queryTimeout ): SMTLib2Interface({}, std::move(_smtCallback), _queryTimeout) { } void Cvc5SMTLib2Interface::setupSmtCallback() { if (auto* universalCallback = m_smtCallback.target<frontend::UniversalCallback>()) universalCallback->smtCommand().setCvc5(m_queryTimeout); }
1,233
C++
.cpp
27
43.777778
83
0.803005
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,164
Predicate.cpp
ethereum_solidity/libsolidity/formal/Predicate.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libsolidity/formal/Predicate.h> #include <libsolidity/formal/ExpressionFormatter.h> #include <libsolidity/formal/SMTEncoder.h> #include <liblangutil/CharStreamProvider.h> #include <liblangutil/CharStream.h> #include <libsolidity/ast/AST.h> #include <libsolidity/ast/TypeProvider.h> #include <boost/algorithm/string/join.hpp> #include <boost/algorithm/string.hpp> #include <range/v3/view.hpp> #include <utility> using boost::algorithm::starts_with; using namespace solidity; using namespace solidity::smtutil; using namespace solidity::frontend; using namespace solidity::frontend::smt; std::map<std::string, Predicate> Predicate::m_predicates; Predicate const* Predicate::create( SortPointer _sort, std::string _name, PredicateType _type, EncodingContext& _context, ASTNode const* _node, ContractDefinition const* _contractContext, std::vector<ScopeOpener const*> _scopeStack ) { solAssert(!m_predicates.count(_name), ""); return &m_predicates.emplace( std::piecewise_construct, std::forward_as_tuple(_name), std::forward_as_tuple(_name, std::move(_sort), _type, _context.state().hasBytesConcatFunction(), _node, _contractContext, std::move(_scopeStack)) ).first->second; } Predicate::Predicate( std::string _name, SortPointer _sort, PredicateType _type, bool _bytesConcatFunctionInContext, ASTNode const* _node, ContractDefinition const* _contractContext, std::vector<ScopeOpener const*> _scopeStack ): m_functor(std::move(_name), {}, std::move(_sort)), m_type(_type), m_node(_node), m_contractContext(_contractContext), m_scopeStack(_scopeStack), m_bytesConcatFunctionInContext(_bytesConcatFunctionInContext) { } Predicate const* Predicate::predicate(std::string const& _name) { return &m_predicates.at(_name); } void Predicate::reset() { m_predicates.clear(); } smtutil::Expression Predicate::operator()(std::vector<smtutil::Expression> const& _args) const { return smtutil::Expression(m_functor.name, _args, SortProvider::boolSort); } smtutil::Expression const& Predicate::functor() const { return m_functor; } ASTNode const* Predicate::programNode() const { return m_node; } ContractDefinition const* Predicate::contextContract() const { return m_contractContext; } ContractDefinition const* Predicate::programContract() const { if (auto const* contract = dynamic_cast<ContractDefinition const*>(m_node)) if (!contract->constructor()) return contract; return nullptr; } FunctionDefinition const* Predicate::programFunction() const { if (auto const* contract = dynamic_cast<ContractDefinition const*>(m_node)) { if (contract->constructor()) return contract->constructor(); return nullptr; } if (auto const* fun = dynamic_cast<FunctionDefinition const*>(m_node)) return fun; return nullptr; } FunctionCall const* Predicate::programFunctionCall() const { return dynamic_cast<FunctionCall const*>(m_node); } VariableDeclaration const* Predicate::programVariable() const { return dynamic_cast<VariableDeclaration const*>(m_node); } std::optional<std::vector<VariableDeclaration const*>> Predicate::stateVariables() const { if (m_contractContext) return SMTEncoder::stateVariablesIncludingInheritedAndPrivate(*m_contractContext); return std::nullopt; } bool Predicate::isSummary() const { return isFunctionSummary() || isInternalCall() || isExternalCallTrusted() || isExternalCallUntrusted() || isConstructorSummary(); } bool Predicate::isFunctionSummary() const { return m_type == PredicateType::FunctionSummary; } bool Predicate::isFunctionBlock() const { return m_type == PredicateType::FunctionBlock; } bool Predicate::isFunctionErrorBlock() const { return m_type == PredicateType::FunctionErrorBlock; } bool Predicate::isInternalCall() const { return m_type == PredicateType::InternalCall; } bool Predicate::isExternalCallTrusted() const { return m_type == PredicateType::ExternalCallTrusted; } bool Predicate::isExternalCallUntrusted() const { return m_type == PredicateType::ExternalCallUntrusted; } bool Predicate::isConstructorSummary() const { return m_type == PredicateType::ConstructorSummary; } bool Predicate::isInterface() const { return m_type == PredicateType::Interface; } bool Predicate::isNondetInterface() const { return m_type == PredicateType::NondetInterface; } std::string Predicate::formatSummaryCall( std::vector<smtutil::Expression> const& _args, langutil::CharStreamProvider const& _charStreamProvider, bool _appendTxVars ) const { solAssert(isSummary(), ""); if (programVariable()) return {}; if (auto funCall = programFunctionCall()) { if (funCall->location().hasText()) return std::string(_charStreamProvider.charStream(*funCall->location().sourceName).text(funCall->location())); else return {}; } /// The signature of a function summary predicate is: summary(error, this, abiFunctions, (optionally) bytesConcatFunctions, cryptoFunctions, txData, preBlockChainState, preStateVars, preInputVars, postBlockchainState, postStateVars, postInputVars, outputVars). /// Here we are interested in preInputVars to format the function call. std::string txModel; if (_appendTxVars) { std::set<std::string> txVars; if (isFunctionSummary()) { solAssert(programFunction(), ""); if (programFunction()->isPayable()) txVars.insert("msg.value"); } else if (isConstructorSummary()) { FunctionDefinition const* fun = programFunction(); if (fun && fun->isPayable()) txVars.insert("msg.value"); } struct TxVarsVisitor: public ASTConstVisitor { bool visit(MemberAccess const& _memberAccess) { Expression const* memberExpr = SMTEncoder::innermostTuple(_memberAccess.expression()); Type const* exprType = memberExpr->annotation().type; solAssert(exprType, ""); if (exprType->category() == Type::Category::Magic) if (auto const* identifier = dynamic_cast<Identifier const*>(memberExpr)) { ASTString const& name = identifier->name(); auto memberName = _memberAccess.memberName(); // TODO remove this for 0.9.0 if (name == "block" && memberName == "difficulty") memberName = "prevrandao"; if (name == "block" || name == "msg" || name == "tx") txVars.insert(name + "." + memberName); } return true; } std::set<std::string> txVars; } txVarsVisitor; if (auto fun = programFunction()) { fun->accept(txVarsVisitor); txVars += txVarsVisitor.txVars; } // Here we are interested in txData from the summary predicate. auto txValues = readTxVars(_args.at(txValuesIndex())); std::vector<std::string> values; for (auto const& _var: txVars) if (auto v = txValues.at(_var)) values.push_back(_var + ": " + *v); if (!values.empty()) txModel = "{ " + boost::algorithm::join(values, ", ") + " }"; } if (auto contract = programContract()) return contract->name() + ".constructor()" + txModel; auto stateVars = stateVariables(); solAssert(stateVars.has_value(), ""); auto const* fun = programFunction(); solAssert(fun, ""); auto first = _args.begin() + static_cast<int>(firstArgIndex()) + static_cast<int>(stateVars->size()); auto last = first + static_cast<int>(fun->parameters().size()); solAssert(first >= _args.begin() && first <= _args.end(), ""); solAssert(last >= _args.begin() && last <= _args.end(), ""); auto inTypes = SMTEncoder::replaceUserTypes(FunctionType(*fun).parameterTypes()); std::vector<std::optional<std::string>> functionArgsCex = formatExpressions(std::vector<smtutil::Expression>(first, last), inTypes); std::vector<std::string> functionArgs; auto const& params = fun->parameters(); solAssert(params.size() == functionArgsCex.size(), ""); bool paramNameInsteadOfValue = false; for (unsigned i = 0; i < params.size(); ++i) if (params.at(i) && functionArgsCex.at(i)) functionArgs.emplace_back(*functionArgsCex.at(i)); else { paramNameInsteadOfValue = true; functionArgs.emplace_back(params[i]->name()); } std::string fName = fun->isConstructor() ? "constructor" : fun->isFallback() ? "fallback" : fun->isReceive() ? "receive" : fun->name(); std::string prefix; if (fun->isFree()) prefix = !fun->sourceUnitName().empty() ? (fun->sourceUnitName() + ":") : ""; else { solAssert(fun->annotation().contract, ""); prefix = fun->annotation().contract->name() + "."; } std::string summary = prefix + fName + "(" + boost::algorithm::join(functionArgs, ", ") + ")" + txModel; if (paramNameInsteadOfValue) summary += " -- counterexample incomplete; parameter name used instead of value"; return summary; } std::vector<std::optional<std::string>> Predicate::summaryStateValues(std::vector<smtutil::Expression> const& _args) const { /// The signature of a function summary predicate is: summary(error, this, abiFunctions, (optionally) bytesConcatFunctions, cryptoFunctions, txData, preBlockchainState, preStateVars, preInputVars, postBlockchainState, postStateVars, postInputVars, outputVars). /// The signature of the summary predicate of a contract without constructor is: summary(error, this, abiFunctions, (optionally) bytesConcatFunctions, cryptoFunctions, txData, preBlockchainState, postBlockchainState, preStateVars, postStateVars). /// Here we are interested in postStateVars. auto stateVars = stateVariables(); solAssert(stateVars.has_value(), ""); std::vector<smtutil::Expression>::const_iterator stateFirst; std::vector<smtutil::Expression>::const_iterator stateLast; if (auto const* function = programFunction()) { stateFirst = _args.begin() + static_cast<int>(firstArgIndex()) + static_cast<int>(stateVars->size()) + static_cast<int>(function->parameters().size()) + 1; stateLast = stateFirst + static_cast<int>(stateVars->size()); } else if (programContract()) { stateFirst = _args.begin() + static_cast<int>(firstStateVarIndex()) + static_cast<int>(stateVars->size()); stateLast = stateFirst + static_cast<int>(stateVars->size()); } else if (programVariable()) return {}; else solAssert(false, ""); solAssert(stateFirst >= _args.begin() && stateFirst <= _args.end(), ""); solAssert(stateLast >= _args.begin() && stateLast <= _args.end(), ""); std::vector<smtutil::Expression> stateArgs(stateFirst, stateLast); solAssert(stateArgs.size() == stateVars->size(), ""); auto stateTypes = util::applyMap(*stateVars, [&](auto const& _var) { return _var->type(); }); return formatExpressions(stateArgs, stateTypes); } std::vector<std::optional<std::string>> Predicate::summaryPostInputValues(std::vector<smtutil::Expression> const& _args) const { /// The signature of a function summary predicate is: summary(error, this, abiFunctions, (optionally) bytesConcatFunctions, cryptoFunctions, txData, preBlockchainState, preStateVars, preInputVars, postBlockchainState, postStateVars, postInputVars, outputVars). /// Here we are interested in postInputVars. auto const* function = programFunction(); solAssert(function, ""); auto stateVars = stateVariables(); solAssert(stateVars.has_value(), ""); auto const& inParams = function->parameters(); auto first = _args.begin() + static_cast<int>(firstArgIndex()) + static_cast<int>(stateVars->size()) * 2 + static_cast<int>(inParams.size()) + 1; auto last = first + static_cast<int>(inParams.size()); solAssert(first >= _args.begin() && first <= _args.end(), ""); solAssert(last >= _args.begin() && last <= _args.end(), ""); std::vector<smtutil::Expression> inValues(first, last); solAssert(inValues.size() == inParams.size(), ""); auto inTypes = SMTEncoder::replaceUserTypes(FunctionType(*function).parameterTypes()); return formatExpressions(inValues, inTypes); } std::vector<std::optional<std::string>> Predicate::summaryPostOutputValues(std::vector<smtutil::Expression> const& _args) const { /// The signature of a function summary predicate is: summary(error, this, abiFunctions, (optionally) bytesConcatFunctions, cryptoFunctions, txData, preBlockchainState, preStateVars, preInputVars, postBlockchainState, postStateVars, postInputVars, outputVars). /// Here we are interested in outputVars. auto const* function = programFunction(); solAssert(function, ""); auto stateVars = stateVariables(); solAssert(stateVars.has_value(), ""); auto const& inParams = function->parameters(); auto first = _args.begin() + static_cast<int>(firstArgIndex()) + static_cast<int>(stateVars->size()) * 2 + static_cast<int>(inParams.size()) * 2 + 1; solAssert(first >= _args.begin() && first <= _args.end(), ""); std::vector<smtutil::Expression> outValues(first, _args.end()); solAssert(outValues.size() == function->returnParameters().size(), ""); auto outTypes = SMTEncoder::replaceUserTypes(FunctionType(*function).returnParameterTypes()); return formatExpressions(outValues, outTypes); } std::pair<std::vector<std::optional<std::string>>, std::vector<VariableDeclaration const*>> Predicate::localVariableValues(std::vector<smtutil::Expression> const& _args) const { /// The signature of a local block predicate is: /// block(error, this, abiFunctions, (optionally) bytesConcatFunctions, cryptoFunctions, txData, preBlockchainState, preStateVars, preInputVars, postBlockchainState, postStateVars, postInputVars, outputVars, localVars). /// Here we are interested in localVars. auto const* function = programFunction(); solAssert(function, ""); auto const& localVars = SMTEncoder::localVariablesIncludingModifiers(*function, m_contractContext); auto first = _args.end() - static_cast<int>(localVars.size()); std::vector<smtutil::Expression> outValues(first, _args.end()); auto mask = util::applyMap( localVars, [this](auto _var) { auto varScope = dynamic_cast<ScopeOpener const*>(_var->scope()); return find(begin(m_scopeStack), end(m_scopeStack), varScope) != end(m_scopeStack); } ); auto localVarsInScope = util::filter(localVars, mask); auto outValuesInScope = util::filter(outValues, mask); auto outTypes = util::applyMap(localVarsInScope, [](auto _var) { return _var->type(); }); return {formatExpressions(outValuesInScope, outTypes), localVarsInScope}; } std::map<std::string, std::string> Predicate::expressionSubstitution(smtutil::Expression const& _predExpr) const { std::map<std::string, std::string> subst; std::string predName = functor().name; solAssert(contextContract(), ""); auto const& stateVars = SMTEncoder::stateVariablesIncludingInheritedAndPrivate(*contextContract()); auto nArgs = _predExpr.arguments.size(); // The signature of an interface predicate is // interface(this, abiFunctions, (optionally) bytesConcatFunctions, cryptoFunctions, blockchainState, stateVariables). // An invariant for an interface predicate is a contract // invariant over its state, for example `x <= 0`. if (isInterface()) { size_t shift = txValuesIndex(); solAssert(starts_with(predName, "interface"), ""); subst[_predExpr.arguments.at(0).name] = "address(this)"; solAssert(nArgs == stateVars.size() + shift, ""); for (size_t i = nArgs - stateVars.size(); i < nArgs; ++i) subst[_predExpr.arguments.at(i).name] = stateVars.at(i - shift)->name(); } // The signature of a nondet interface predicate is // nondet_interface(error, this, abiFunctions, (optionally) bytesConcatFunctions, cryptoFunctions, blockchainState, stateVariables, blockchainState', stateVariables'). // An invariant for a nondet interface predicate is a reentrancy property // over the pre and post state variables of a contract, where pre state vars // are represented by the variable's name and post state vars are represented // by the primed variable's name, for example // `(x <= 0) => (x' <= 100)`. else if (isNondetInterface()) { solAssert(starts_with(predName, "nondet_interface"), ""); subst[_predExpr.arguments.at(0).name] = "<errorCode>"; subst[_predExpr.arguments.at(1).name] = "address(this)"; solAssert(nArgs == stateVars.size() * 2 + firstArgIndex(), ""); for (size_t i = nArgs - stateVars.size(), s = 0; i < nArgs; ++i, ++s) subst[_predExpr.arguments.at(i).name] = stateVars.at(s)->name() + "'"; for (size_t i = nArgs - (stateVars.size() * 2 + 1), s = 0; i < nArgs - (stateVars.size() + 1); ++i, ++s) subst[_predExpr.arguments.at(i).name] = stateVars.at(s)->name(); } return subst; } std::map<std::string, std::optional<std::string>> Predicate::readTxVars(smtutil::Expression const& _tx) const { std::map<std::string, Type const*> const txVars{ {"block.basefee", TypeProvider::uint256()}, {"block.chainid", TypeProvider::uint256()}, {"block.coinbase", TypeProvider::address()}, {"block.prevrandao", TypeProvider::uint256()}, {"block.gaslimit", TypeProvider::uint256()}, {"block.number", TypeProvider::uint256()}, {"block.timestamp", TypeProvider::uint256()}, {"blockhash", TypeProvider::array(DataLocation::Memory, TypeProvider::uint256())}, {"msg.data", TypeProvider::array(DataLocation::CallData)}, {"msg.sender", TypeProvider::address()}, {"msg.sig", TypeProvider::fixedBytes(4)}, {"msg.value", TypeProvider::uint256()}, {"tx.gasprice", TypeProvider::uint256()}, {"tx.origin", TypeProvider::address()} }; std::map<std::string, std::optional<std::string>> vars; for (auto&& [i, v]: txVars | ranges::views::enumerate) vars.emplace(v.first, expressionToString(_tx.arguments.at(i), v.second)); return vars; }
18,005
C++
.cpp
426
39.85446
261
0.737324
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,165
ArraySlicePredicate.cpp
ethereum_solidity/libsolidity/formal/ArraySlicePredicate.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libsolidity/formal/ArraySlicePredicate.h> #include <liblangutil/Exceptions.h> using namespace solidity; using namespace solidity::smtutil; using namespace solidity::frontend; using namespace solidity::frontend::smt; std::map<std::string, ArraySlicePredicate::SliceData> ArraySlicePredicate::m_slicePredicates; std::pair<bool, ArraySlicePredicate::SliceData const&> ArraySlicePredicate::create(SortPointer _sort, EncodingContext& _context) { solAssert(_sort->kind == Kind::Tuple, ""); auto tupleSort = std::dynamic_pointer_cast<TupleSort>(_sort); solAssert(tupleSort, ""); auto tupleName = tupleSort->name; if (m_slicePredicates.count(tupleName)) return {true, m_slicePredicates.at(tupleName)}; auto sort = tupleSort->components.at(0); solAssert(sort->kind == Kind::Array, ""); smt::SymbolicArrayVariable aVar{sort, "a_" + tupleName, _context }; smt::SymbolicArrayVariable bVar{sort, "b_" + tupleName, _context}; smt::SymbolicIntVariable startVar{TypeProvider::uint256(), TypeProvider::uint256(), "start_" + tupleName, _context}; smt::SymbolicIntVariable endVar{TypeProvider::uint256(), TypeProvider::uint256(), "end_" + tupleName, _context }; smt::SymbolicIntVariable iVar{TypeProvider::uint256(), TypeProvider::uint256(), "i_" + tupleName, _context}; std::vector<SortPointer> domain{sort, sort, startVar.sort(), endVar.sort()}; auto sliceSort = std::make_shared<FunctionSort>(domain, SortProvider::boolSort); Predicate const& slice = *Predicate::create(sliceSort, "array_slice_" + tupleName, PredicateType::Custom, _context); domain.emplace_back(iVar.sort()); auto predSort = std::make_shared<FunctionSort>(domain, SortProvider::boolSort); Predicate const& header = *Predicate::create(predSort, "array_slice_header_" + tupleName, PredicateType::Custom, _context); Predicate const& loop = *Predicate::create(predSort, "array_slice_loop_" + tupleName, PredicateType::Custom, _context); auto a = aVar.elements(); auto b = bVar.elements(); auto start = startVar.currentValue(); auto end = endVar.currentValue(); auto i = iVar.currentValue(); auto rule1 = smtutil::Expression::implies( end > start, header({a, b, start, end, 0}) ); auto rule2 = smtutil::Expression::implies( header({a, b, start, end, i}) && i >= (end - start), slice({a, b, start, end}) ); auto rule3 = smtutil::Expression::implies( header({a, b, start, end, i}) && i >= 0 && i < (end - start), loop({a, b, start, end, i}) ); auto b_i = smtutil::Expression::select(b, i); auto a_start_i = smtutil::Expression::select(a, start + i); auto rule4 = smtutil::Expression::implies( loop({a, b, start, end, i}) && b_i == a_start_i, header({a, b, start, end, i + 1}) ); return {false, m_slicePredicates[tupleName] = { {&slice, &header, &loop}, {std::move(rule1), std::move(rule2), std::move(rule3), std::move(rule4)} }}; }
3,546
C++
.cpp
71
47.704225
128
0.733796
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
3,166
SMTEncoder.cpp
ethereum_solidity/libsolidity/formal/SMTEncoder.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libsolidity/formal/SMTEncoder.h> #include <libsolidity/ast/TypeProvider.h> #include <libsolidity/formal/SymbolicState.h> #include <libsolidity/formal/SymbolicTypes.h> #include <libsolidity/analysis/ConstantEvaluator.h> #include <libyul/AST.h> #include <libyul/optimiser/Semantics.h> #include <libsmtutil/SMTPortfolio.h> #include <libsmtutil/Helpers.h> #include <liblangutil/CharStreamProvider.h> #include <libsolutil/Algorithms.h> #include <libsolutil/FunctionSelector.h> #include <range/v3/view.hpp> #include <limits> #include <deque> using namespace solidity; using namespace solidity::util; using namespace solidity::langutil; using namespace solidity::frontend; using namespace std::string_literals; SMTEncoder::SMTEncoder( smt::EncodingContext& _context, ModelCheckerSettings _settings, UniqueErrorReporter& _errorReporter, UniqueErrorReporter& _unsupportedErrorReporter, ErrorReporter& _provedSafeReporter, langutil::CharStreamProvider const& _charStreamProvider ): m_errorReporter(_errorReporter), m_unsupportedErrors(_unsupportedErrorReporter), m_provedSafeReporter(_provedSafeReporter), m_context(_context), m_settings(std::move(_settings)), m_charStreamProvider(_charStreamProvider) { } void SMTEncoder::resetSourceAnalysis() { m_freeFunctions.clear(); } bool SMTEncoder::visit(ContractDefinition const& _contract) { solAssert(m_currentContract, ""); for (auto const& node: _contract.subNodes()) if ( !std::dynamic_pointer_cast<FunctionDefinition>(node) && !std::dynamic_pointer_cast<VariableDeclaration>(node) ) node->accept(*this); for (auto const& base: _contract.annotation().linearizedBaseContracts) { // Look for all the constructor invocations bottom up. if (auto const& constructor = base->constructor()) for (auto const& invocation: constructor->modifiers()) { auto refDecl = invocation->name().annotation().referencedDeclaration; if (auto const& baseContract = dynamic_cast<ContractDefinition const*>(refDecl)) { solAssert(!m_baseConstructorCalls.count(baseContract), ""); m_baseConstructorCalls[baseContract] = invocation.get(); } } } // Functions are visited first since they might be used // for state variable initialization which is part of // the constructor. // Constructors are visited as part of the constructor // hierarchy inlining. for (auto const* function: contractFunctionsWithoutVirtual(_contract) + allFreeFunctions()) if (!function->isConstructor()) function->accept(*this); // Constructors need to be handled by the engines separately. return false; } void SMTEncoder::endVisit(ContractDefinition const& _contract) { m_context.resetAllVariables(); m_baseConstructorCalls.clear(); solAssert(m_currentContract == &_contract, ""); m_currentContract = nullptr; if (m_callStack.empty()) m_context.popSolver(); } bool SMTEncoder::visit(ImportDirective const&) { // do not visit because the identifier therein will confuse us. return false; } void SMTEncoder::endVisit(VariableDeclaration const& _varDecl) { // State variables are handled by the constructor. if (_varDecl.isLocalVariable() &&_varDecl.value()) assignment(_varDecl, *_varDecl.value()); } bool SMTEncoder::visit(ModifierDefinition const&) { return false; } bool SMTEncoder::visit(FunctionDefinition const& _function) { solAssert(m_currentContract, ""); m_modifierDepthStack.push_back(-1); initializeLocalVariables(_function); _function.parameterList().accept(*this); if (_function.returnParameterList()) _function.returnParameterList()->accept(*this); visitFunctionOrModifier(); return false; } void SMTEncoder::visitFunctionOrModifier() { solAssert(!m_callStack.empty(), ""); solAssert(!m_modifierDepthStack.empty(), ""); ++m_modifierDepthStack.back(); FunctionDefinition const& function = dynamic_cast<FunctionDefinition const&>(*m_callStack.back().first); if (m_modifierDepthStack.back() == static_cast<int>(function.modifiers().size())) { if (function.isImplemented()) { pushInlineFrame(function); function.body().accept(*this); popInlineFrame(function); } } else { solAssert(m_modifierDepthStack.back() < static_cast<int>(function.modifiers().size()), ""); ASTPointer<ModifierInvocation> const& modifierInvocation = function.modifiers()[static_cast<size_t>(m_modifierDepthStack.back())]; solAssert(modifierInvocation, ""); auto refDecl = modifierInvocation->name().annotation().referencedDeclaration; if (dynamic_cast<ContractDefinition const*>(refDecl)) visitFunctionOrModifier(); else if (auto modifier = resolveModifierInvocation(*modifierInvocation, m_currentContract)) { m_scopes.push_back(modifier); inlineModifierInvocation(modifierInvocation.get(), modifier); solAssert(m_scopes.back() == modifier, ""); m_scopes.pop_back(); } else solAssert(false, ""); } --m_modifierDepthStack.back(); } void SMTEncoder::inlineModifierInvocation(ModifierInvocation const* _invocation, CallableDeclaration const* _definition) { solAssert(_invocation, ""); _invocation->accept(*this); std::vector<smtutil::Expression> args; if (auto const* arguments = _invocation->arguments()) { auto const& modifierParams = _definition->parameters(); solAssert(modifierParams.size() == arguments->size(), ""); for (unsigned i = 0; i < arguments->size(); ++i) args.push_back(expr(*arguments->at(i), modifierParams.at(i)->type())); } initializeFunctionCallParameters(*_definition, args); pushCallStack({_definition, _invocation}); pushInlineFrame(*_definition); if (auto modifier = dynamic_cast<ModifierDefinition const*>(_definition)) { if (modifier->isImplemented()) modifier->body().accept(*this); popCallStack(); } else if (auto function = dynamic_cast<FunctionDefinition const*>(_definition)) { if (function->isImplemented()) function->accept(*this); // Functions are popped from the callstack in endVisit(FunctionDefinition) } popInlineFrame(*_definition); } void SMTEncoder::inlineConstructorHierarchy(ContractDefinition const& _contract) { auto const& hierarchy = m_currentContract->annotation().linearizedBaseContracts; auto it = find(begin(hierarchy), end(hierarchy), &_contract); solAssert(it != end(hierarchy), ""); auto nextBase = it + 1; // Initialize the base contracts here as long as their constructors are implicit, // stop when the first explicit constructor is found. while (nextBase != end(hierarchy)) { if (auto baseConstructor = (*nextBase)->constructor()) { createLocalVariables(*baseConstructor); // If any subcontract explicitly called baseConstructor, use those arguments. if (m_baseConstructorCalls.count(*nextBase)) inlineModifierInvocation(m_baseConstructorCalls.at(*nextBase), baseConstructor); else if (baseConstructor->isImplemented()) { // The first constructor found is handled like a function // and its pushed into the callstack there. // This if avoids duplication in the callstack. if (!m_callStack.empty()) pushCallStack({baseConstructor, nullptr}); baseConstructor->accept(*this); // popped by endVisit(FunctionDefinition) } break; } else { initializeStateVariables(**nextBase); ++nextBase; } } initializeStateVariables(_contract); } bool SMTEncoder::visit(PlaceholderStatement const&) { solAssert(!m_callStack.empty(), ""); auto lastCall = popCallStack(); visitFunctionOrModifier(); pushCallStack(lastCall); return true; } void SMTEncoder::endVisit(FunctionDefinition const&) { solAssert(m_currentContract, ""); popCallStack(); solAssert(m_modifierDepthStack.back() == -1, ""); m_modifierDepthStack.pop_back(); if (m_callStack.empty()) m_context.popSolver(); } bool SMTEncoder::visit(Block const& _block) { if (_block.unchecked()) { solAssert(m_checked, ""); m_checked = false; } return true; } void SMTEncoder::endVisit(Block const& _block) { if (_block.unchecked()) { solAssert(!m_checked, ""); m_checked = true; } } bool SMTEncoder::visit(InlineAssembly const& _inlineAsm) { /// This is very similar to `yul::Assignments`, except I need to collect `Identifier`s and not just names as `YulString`s. struct AssignedExternalsCollector: public yul::ASTWalker { AssignedExternalsCollector(InlineAssembly const& _inlineAsm): externalReferences(_inlineAsm.annotation().externalReferences) { this->operator()(_inlineAsm.operations().root()); } std::map<yul::Identifier const*, InlineAssemblyAnnotation::ExternalIdentifierInfo> const& externalReferences; std::set<VariableDeclaration const*> assignedVars; using yul::ASTWalker::operator(); void operator()(yul::Assignment const& _assignment) { auto const& vars = _assignment.variableNames; for (auto const& identifier: vars) if (auto externalInfo = util::valueOrNullptr(externalReferences, &identifier)) if (auto varDecl = dynamic_cast<VariableDeclaration const*>(externalInfo->declaration)) assignedVars.insert(varDecl); } }; yul::SideEffectsCollector sideEffectsCollector(_inlineAsm.dialect(), _inlineAsm.operations().root()); if (sideEffectsCollector.invalidatesMemory()) resetMemoryVariables(); if (sideEffectsCollector.invalidatesStorage()) resetStorageVariables(); auto assignedVars = AssignedExternalsCollector(_inlineAsm).assignedVars; for (auto const* var: assignedVars) { solAssert(var, ""); solAssert(var->isLocalVariable(), "Non-local variable assigned in inlined assembly"); m_context.resetVariable(*var); } m_unsupportedErrors.warning( 7737_error, _inlineAsm.location(), "Inline assembly may cause SMTChecker to produce spurious warnings (false positives)." ); return false; } void SMTEncoder::pushInlineFrame(CallableDeclaration const&) { pushPathCondition(currentPathConditions()); } void SMTEncoder::popInlineFrame(CallableDeclaration const&) { popPathCondition(); } void SMTEncoder::endVisit(VariableDeclarationStatement const& _varDecl) { if (auto init = _varDecl.initialValue()) expressionToTupleAssignment(_varDecl.declarations(), *init); } bool SMTEncoder::visit(Assignment const& _assignment) { // RHS must be visited before LHS; as opposed to what Assignment::accept does _assignment.rightHandSide().accept(*this); _assignment.leftHandSide().accept(*this); return false; } void SMTEncoder::endVisit(Assignment const& _assignment) { createExpr(_assignment); Token op = _assignment.assignmentOperator(); solAssert(TokenTraits::isAssignmentOp(op), ""); if (!isSupportedType(*_assignment.annotation().type)) { // Give it a new index anyway to keep the SSA scheme sound. Expression const* base = &_assignment.leftHandSide(); if (auto const* indexAccess = dynamic_cast<IndexAccess const*>(base)) base = leftmostBase(*indexAccess); if (auto varDecl = identifierToVariable(*base)) m_context.newValue(*varDecl); } else { if (dynamic_cast<TupleType const*>(_assignment.rightHandSide().annotation().type)) tupleAssignment(_assignment.leftHandSide(), _assignment.rightHandSide()); else { auto const& type = _assignment.annotation().type; auto rightHandSide = op == Token::Assign ? expr(_assignment.rightHandSide(), type) : compoundAssignment(_assignment); defineExpr(_assignment, rightHandSide); assignment( _assignment.leftHandSide(), expr(_assignment, type), type ); } } } void SMTEncoder::endVisit(TupleExpression const& _tuple) { if (_tuple.annotation().type->category() == Type::Category::Function) return; if (_tuple.annotation().type->category() == Type::Category::TypeType) return; createExpr(_tuple); if (_tuple.isInlineArray()) { // Add constraints for the length and values as it is known. auto symbArray = std::dynamic_pointer_cast<smt::SymbolicArrayVariable>(m_context.expression(_tuple)); solAssert(symbArray, ""); addArrayLiteralAssertions(*symbArray, applyMap(_tuple.components(), [&](auto const& c) { return expr(*c); })); } else { auto values = applyMap(_tuple.components(), [this](auto const& component) -> std::optional<smtutil::Expression> { if (component) { if (!m_context.knownExpression(*component)) createExpr(*component); return expr(*component); } return {}; }); defineExpr(_tuple, values); } } void SMTEncoder::endVisit(UnaryOperation const& _op) { /// We need to shortcut here due to potentially unknown /// rational number sizes. if (_op.annotation().type->category() == Type::Category::RationalNumber) return; if (TokenTraits::isBitOp(_op.getOperator()) && !*_op.annotation().userDefinedFunction) return bitwiseNotOperation(_op); createExpr(_op); // User-defined operators are essentially function calls. if (*_op.annotation().userDefinedFunction) return; auto const* subExpr = innermostTuple(_op.subExpression()); auto type = _op.annotation().type; switch (_op.getOperator()) { case Token::Not: // ! { solAssert(smt::isBool(*type), ""); defineExpr(_op, !expr(*subExpr)); break; } case Token::Inc: // ++ (pre- or postfix) case Token::Dec: // -- (pre- or postfix) { solAssert(smt::isInteger(*type) || smt::isFixedPoint(*type), ""); solAssert(subExpr->annotation().willBeWrittenTo, ""); auto innerValue = expr(*subExpr); auto newValue = arithmeticOperation( _op.getOperator() == Token::Inc ? Token::Add : Token::Sub, innerValue, smtutil::Expression(size_t(1)), _op.annotation().type, _op ).first; defineExpr(_op, _op.isPrefixOperation() ? newValue : innerValue); assignment(*subExpr, newValue); break; } case Token::Sub: // - { defineExpr(_op, 0 - expr(*subExpr)); break; } case Token::Delete: { if (auto decl = identifierToVariable(*subExpr)) { m_context.newValue(*decl); m_context.setZeroValue(*decl); } else { solAssert(m_context.knownExpression(*subExpr), ""); auto const& symbVar = m_context.expression(*subExpr); symbVar->increaseIndex(); m_context.setZeroValue(*symbVar); if ( dynamic_cast<IndexAccess const*>(subExpr) || dynamic_cast<MemberAccess const*>(subExpr) ) indexOrMemberAssignment(*subExpr, symbVar->currentValue()); // Empty push added a zero value anyway, so no need to delete extra. else if (!isEmptyPush(*subExpr)) solAssert(false, ""); } break; } default: solAssert(false, ""); } } bool SMTEncoder::visit(UnaryOperation const& _op) { return !shortcutRationalNumber(_op); } bool SMTEncoder::visit(BinaryOperation const& _op) { if (shortcutRationalNumber(_op)) return false; if (TokenTraits::isBooleanOp(_op.getOperator()) && !*_op.annotation().userDefinedFunction) { booleanOperation(_op); return false; } return true; } void SMTEncoder::endVisit(BinaryOperation const& _op) { /// If _op is const evaluated the RationalNumber shortcut was taken. if (isConstant(_op)) return; if (TokenTraits::isBooleanOp(_op.getOperator()) && !*_op.annotation().userDefinedFunction) return; createExpr(_op); // User-defined operators are essentially function calls. if (*_op.annotation().userDefinedFunction) return; if (TokenTraits::isArithmeticOp(_op.getOperator())) arithmeticOperation(_op); else if (TokenTraits::isCompareOp(_op.getOperator())) compareOperation(_op); else if (TokenTraits::isBitOp(_op.getOperator()) || TokenTraits::isShiftOp(_op.getOperator())) bitwiseOperation(_op); else solAssert(false, ""); } bool SMTEncoder::visit(Conditional const& _op) { _op.condition().accept(*this); auto indicesEndTrue = visitBranch(&_op.trueExpression(), expr(_op.condition())).first; auto indicesEndFalse = visitBranch(&_op.falseExpression(), !expr(_op.condition())).first; mergeVariables(expr(_op.condition()), indicesEndTrue, indicesEndFalse); defineExpr(_op, smtutil::Expression::ite( expr(_op.condition()), expr(_op.trueExpression(), _op.annotation().type), expr(_op.falseExpression(), _op.annotation().type) )); return false; } bool SMTEncoder::visit(FunctionCall const& _funCall) { auto functionCallKind = *_funCall.annotation().kind; if (functionCallKind != FunctionCallKind::FunctionCall) return true; FunctionType const& funType = dynamic_cast<FunctionType const&>(*_funCall.expression().annotation().type); // We do not want to visit the TypeTypes in the second argument of `abi.decode`. // Those types are checked/used in SymbolicState::buildABIFunctions. if (funType.kind() == FunctionType::Kind::ABIDecode) { if (auto arg = _funCall.arguments().front()) arg->accept(*this); return false; } // We do not really need to visit the expression in a wrap/unwrap no-op call, // so we just ignore the function call expression to avoid "unsupported" warnings. else if ( funType.kind() == FunctionType::Kind::Wrap || funType.kind() == FunctionType::Kind::Unwrap ) { if (auto arg = _funCall.arguments().front()) arg->accept(*this); return false; } return true; } void SMTEncoder::endVisit(FunctionCall const& _funCall) { auto functionCallKind = *_funCall.annotation().kind; createExpr(_funCall); if (functionCallKind == FunctionCallKind::StructConstructorCall) { visitStructConstructorCall(_funCall); return; } if (functionCallKind == FunctionCallKind::TypeConversion) { visitTypeConversion(_funCall); return; } FunctionType const& funType = dynamic_cast<FunctionType const&>(*_funCall.expression().annotation().type); std::vector<ASTPointer<Expression const>> const args = _funCall.arguments(); switch (funType.kind()) { case FunctionType::Kind::Assert: visitAssert(_funCall); break; case FunctionType::Kind::Require: visitRequire(_funCall); break; case FunctionType::Kind::Revert: // Revert is a special case of require and equals to `require(false)` addPathImpliedExpression(smtutil::Expression(false)); break; case FunctionType::Kind::GasLeft: visitGasLeft(_funCall); break; case FunctionType::Kind::External: if (publicGetter(_funCall.expression())) visitPublicGetter(_funCall); break; case FunctionType::Kind::BytesConcat: visitBytesConcat(_funCall); break; case FunctionType::Kind::ABIDecode: case FunctionType::Kind::ABIEncode: case FunctionType::Kind::ABIEncodePacked: case FunctionType::Kind::ABIEncodeWithSelector: case FunctionType::Kind::ABIEncodeCall: case FunctionType::Kind::ABIEncodeWithSignature: visitABIFunction(_funCall); break; case FunctionType::Kind::Internal: case FunctionType::Kind::BareStaticCall: case FunctionType::Kind::BareCall: break; case FunctionType::Kind::KECCAK256: case FunctionType::Kind::ECRecover: case FunctionType::Kind::SHA256: case FunctionType::Kind::RIPEMD160: visitCryptoFunction(_funCall); break; case FunctionType::Kind::BlockHash: defineExpr(_funCall, state().blockhash(expr(*_funCall.arguments().at(0)))); break; case FunctionType::Kind::AddMod: case FunctionType::Kind::MulMod: visitAddMulMod(_funCall); break; case FunctionType::Kind::Unwrap: case FunctionType::Kind::Wrap: visitWrapUnwrap(_funCall); break; case FunctionType::Kind::Send: case FunctionType::Kind::Transfer: { auto const& memberAccess = dynamic_cast<MemberAccess const&>(_funCall.expression()); auto const& address = memberAccess.expression(); auto const& value = args.front(); solAssert(value, ""); smtutil::Expression thisBalance = state().balance(); setSymbolicUnknownValue(thisBalance, TypeProvider::uint256(), m_context); state().transfer(state().thisAddress(), expr(address), expr(*value)); break; } case FunctionType::Kind::ArrayPush: arrayPush(_funCall); break; case FunctionType::Kind::ArrayPop: arrayPop(_funCall); break; case FunctionType::Kind::Event: case FunctionType::Kind::Error: // This can be safely ignored. break; case FunctionType::Kind::ObjectCreation: visitObjectCreation(_funCall); return; case FunctionType::Kind::Creation: if (!m_settings.engine.chc || !m_settings.externalCalls.isTrusted()) m_unsupportedErrors.warning( 8729_error, _funCall.location(), "Contract deployment is only supported in the trusted mode for external calls" " with the CHC engine." ); break; case FunctionType::Kind::DelegateCall: case FunctionType::Kind::BareCallCode: case FunctionType::Kind::BareDelegateCall: default: m_unsupportedErrors.warning( 4588_error, _funCall.location(), "Assertion checker does not yet implement this type of function call." ); } } bool SMTEncoder::visit(ModifierInvocation const& _node) { if (auto const* args = _node.arguments()) for (auto const& arg: *args) if (arg) arg->accept(*this); return false; } void SMTEncoder::initContract(ContractDefinition const& _contract) { solAssert(m_currentContract == nullptr, ""); m_currentContract = &_contract; m_context.reset(); m_context.pushSolver(); createStateVariables(_contract); clearIndices(m_currentContract, nullptr); m_variableUsage.setCurrentContract(_contract); m_checked = true; } void SMTEncoder::initFunction(FunctionDefinition const& _function) { solAssert(m_callStack.empty(), ""); solAssert(m_currentContract, ""); m_context.pushSolver(); m_pathConditions.clear(); pushCallStack({&_function, nullptr}); m_uninterpretedTerms.clear(); createStateVariables(*m_currentContract); createLocalVariables(_function); m_arrayAssignmentHappened = false; clearIndices(m_currentContract, &_function); m_checked = true; } void SMTEncoder::visitAssert(FunctionCall const& _funCall) { auto const& args = _funCall.arguments(); solAssert(args.size() == 1, ""); solAssert(args.front()->annotation().type->category() == Type::Category::Bool, ""); } void SMTEncoder::visitRequire(FunctionCall const& _funCall) { auto const& args = _funCall.arguments(); solAssert(args.size() >= 1, ""); solAssert(args.front()->annotation().type->category() == Type::Category::Bool, ""); addPathImpliedExpression(expr(*args.front())); } void SMTEncoder::visitBytesConcat(FunctionCall const& _funCall) { auto const& args = _funCall.sortedArguments(); // bytes.concat call with no arguments returns an empty array if (args.size() == 0) { defineExpr(_funCall, smt::zeroValue(TypeProvider::bytesMemory())); return; } // bytes.concat with single argument of type bytes memory if (args.size() == 1 && args.front()->annotation().type->category() == frontend::Type::Category::Array) { defineExpr(_funCall, expr(*args.front(), TypeProvider::bytesMemory())); return; } auto const& [name, inTypes, outType] = state().bytesConcatFunctionTypes(&_funCall); solAssert(inTypes.size() == args.size(), ""); auto symbFunction = state().bytesConcatFunction(&_funCall); auto out = createSelectExpressionForFunction(symbFunction, args, inTypes, args.size()); defineExpr(_funCall, out); } void SMTEncoder::visitABIFunction(FunctionCall const& _funCall) { auto symbFunction = state().abiFunction(&_funCall); auto const& [name, inTypes, outTypes] = state().abiFunctionTypes(&_funCall); auto const& funType = dynamic_cast<FunctionType const&>(*_funCall.expression().annotation().type); auto kind = funType.kind(); auto const& args = _funCall.sortedArguments(); auto argsActualLength = kind == FunctionType::Kind::ABIDecode ? 1 : args.size(); solAssert(inTypes.size() == argsActualLength, ""); if (argsActualLength == 0) { defineExpr(_funCall, smt::zeroValue(TypeProvider::bytesMemory())); return; } auto out = createSelectExpressionForFunction(symbFunction, args, inTypes, argsActualLength); if (outTypes.size() == 1) defineExpr(_funCall, out); else { auto symbTuple = std::dynamic_pointer_cast<smt::SymbolicTupleVariable>(m_context.expression(_funCall)); solAssert(symbTuple, ""); solAssert(symbTuple->components().size() == outTypes.size(), ""); solAssert(out.sort->kind == smtutil::Kind::Tuple, ""); symbTuple->increaseIndex(); for (unsigned i = 0; i < symbTuple->components().size(); ++i) m_context.addAssertion(symbTuple->component(i) == smtutil::Expression::tuple_get(out, i)); } } void SMTEncoder::visitCryptoFunction(FunctionCall const& _funCall) { auto const& funType = dynamic_cast<FunctionType const&>(*_funCall.expression().annotation().type); auto kind = funType.kind(); auto arg0 = expr(*_funCall.arguments().at(0)); std::optional<smtutil::Expression> result; if (kind == FunctionType::Kind::KECCAK256) result = smtutil::Expression::select(state().cryptoFunction("keccak256"), arg0); else if (kind == FunctionType::Kind::SHA256) result = smtutil::Expression::select(state().cryptoFunction("sha256"), arg0); else if (kind == FunctionType::Kind::RIPEMD160) result = smtutil::Expression::select(state().cryptoFunction("ripemd160"), arg0); else if (kind == FunctionType::Kind::ECRecover) { auto e = state().cryptoFunction("ecrecover"); auto arg0 = expr(*_funCall.arguments().at(0)); auto arg1 = expr(*_funCall.arguments().at(1)); auto arg2 = expr(*_funCall.arguments().at(2)); auto arg3 = expr(*_funCall.arguments().at(3)); auto inputSort = dynamic_cast<smtutil::ArraySort&>(*e.sort).domain; auto ecrecoverInput = smtutil::Expression::tuple_constructor( smtutil::Expression(std::make_shared<smtutil::SortSort>(inputSort), ""), {arg0, arg1, arg2, arg3} ); result = smtutil::Expression::select(e, ecrecoverInput); } else solAssert(false, ""); defineExpr(_funCall, *result); } void SMTEncoder::visitGasLeft(FunctionCall const& _funCall) { std::string gasLeft = "gasleft"; // We increase the variable index since gasleft changes // inside a tx. defineGlobalVariable(gasLeft, _funCall, true); auto const& symbolicVar = m_context.globalSymbol(gasLeft); unsigned index = symbolicVar->index(); // We set the current value to unknown anyway to add type constraints. m_context.setUnknownValue(*symbolicVar); if (index > 0) m_context.addAssertion(symbolicVar->currentValue() <= symbolicVar->valueAtIndex(index - 1)); } void SMTEncoder::visitAddMulMod(FunctionCall const& _funCall) { auto const& funType = dynamic_cast<FunctionType const&>(*_funCall.expression().annotation().type); auto kind = funType.kind(); solAssert(kind == FunctionType::Kind::AddMod || kind == FunctionType::Kind::MulMod, ""); auto const& args = _funCall.arguments(); solAssert(args.at(0) && args.at(1) && args.at(2), ""); auto x = expr(*args.at(0)); auto y = expr(*args.at(1)); auto k = expr(*args.at(2)); auto const& intType = dynamic_cast<IntegerType const&>(*_funCall.annotation().type); if (kind == FunctionType::Kind::AddMod) defineExpr(_funCall, divModWithSlacks(x + y, k, intType).second); else defineExpr(_funCall, divModWithSlacks(x * y, k, intType).second); } void SMTEncoder::visitWrapUnwrap(FunctionCall const& _funCall) { auto const& args = _funCall.arguments(); solAssert(args.size() == 1, ""); defineExpr(_funCall, expr(*args.front())); } void SMTEncoder::visitObjectCreation(FunctionCall const& _funCall) { auto const& args = _funCall.arguments(); solAssert(args.size() >= 1, ""); auto argType = args.front()->annotation().type->category(); solAssert(argType == Type::Category::Integer || argType == Type::Category::RationalNumber, ""); smtutil::Expression arraySize = expr(*args.front()); setSymbolicUnknownValue(arraySize, TypeProvider::uint256(), m_context); auto symbArray = std::dynamic_pointer_cast<smt::SymbolicArrayVariable>(m_context.expression(_funCall)); solAssert(symbArray, ""); smt::setSymbolicZeroValue(*symbArray, m_context); auto zeroElements = symbArray->elements(); symbArray->increaseIndex(); m_context.addAssertion(symbArray->length() == arraySize); m_context.addAssertion(symbArray->elements() == zeroElements); } void SMTEncoder::endVisit(Identifier const& _identifier) { if (auto decl = identifierToVariable(_identifier)) { if (decl->isConstant()) defineExpr(_identifier, constantExpr(_identifier, *decl)); else defineExpr(_identifier, currentValue(*decl)); } else if (_identifier.annotation().type->category() == Type::Category::Function) visitFunctionIdentifier(_identifier); else if (_identifier.name() == "now") defineGlobalVariable(_identifier.name(), _identifier); else if (_identifier.name() == "this") { defineExpr(_identifier, state().thisAddress()); m_uninterpretedTerms.insert(&_identifier); } // Ignore type identifiers else if (dynamic_cast<TypeType const*>(_identifier.annotation().type)) return; // Ignore module identifiers else if (dynamic_cast<ModuleType const*>(_identifier.annotation().type)) return; // Ignore user defined value type identifiers else if (dynamic_cast<UserDefinedValueType const*>(_identifier.annotation().type)) return; // Ignore the builtin abi, it is handled in FunctionCall. // TODO: ignore MagicType in general (abi, block, msg, tx, type) else if (auto magicType = dynamic_cast<MagicType const*>(_identifier.annotation().type); magicType && magicType->kind() == MagicType::Kind::ABI) { solAssert(_identifier.name() == "abi", ""); return; } else createExpr(_identifier); } void SMTEncoder::endVisit(ElementaryTypeNameExpression const& _typeName) { auto const& typeType = dynamic_cast<TypeType const&>(*_typeName.annotation().type); auto result = smt::newSymbolicVariable( *TypeProvider::uint256(), typeType.actualType()->toString(false), m_context ); solAssert(!result.first && result.second, ""); m_context.createExpression(_typeName, result.second); } namespace // helpers for SMTEncoder::visitPublicGetter { bool isReturnedFromStructGetter(Type const* _type) { // So far it seems that only Mappings and ordinary Arrays are not returned. auto category = _type->category(); if (category == Type::Category::Mapping) return false; if (category == Type::Category::Array) return dynamic_cast<ArrayType const&>(*_type).isByteArrayOrString(); // default return true; } std::vector<std::string> structGetterReturnedMembers(StructType const& _structType) { std::vector<std::string> returnedMembers; for (auto const& member: _structType.nativeMembers(nullptr)) if (isReturnedFromStructGetter(member.type)) returnedMembers.push_back(member.name); return returnedMembers; } } void SMTEncoder::visitPublicGetter(FunctionCall const& _funCall) { auto var = publicGetter(_funCall.expression()); solAssert(var && var->isStateVariable(), ""); solAssert(m_context.knownExpression(_funCall), ""); auto paramExpectedTypes = replaceUserTypes(FunctionType(*var).parameterTypes()); auto actualArguments = _funCall.arguments(); solAssert(actualArguments.size() == paramExpectedTypes.size(), ""); std::deque<smtutil::Expression> symbArguments; for (unsigned i = 0; i < paramExpectedTypes.size(); ++i) symbArguments.push_back(expr(*actualArguments[i], paramExpectedTypes[i])); // See FunctionType::FunctionType(VariableDeclaration const& _varDecl) // to understand the return types of public getters. Type const* type = var->type(); smtutil::Expression currentExpr = currentValue(*var); while (true) { if ( type->isValueType() || (type->category() == Type::Category::Array && dynamic_cast<ArrayType const&>(*type).isByteArrayOrString()) ) { solAssert(symbArguments.empty(), ""); defineExpr(_funCall, currentExpr); return; } switch (type->category()) { case Type::Category::Array: case Type::Category::Mapping: { solAssert(!symbArguments.empty(), ""); // For nested arrays/mappings, each argument in the call is an index to the next layer. // We mirror this with `select` after unpacking the SMT-LIB array expression. currentExpr = smtutil::Expression::select(smtutil::Expression::tuple_get(currentExpr, 0), symbArguments.front()); symbArguments.pop_front(); if (auto arrayType = dynamic_cast<ArrayType const*>(type)) type = arrayType->baseType(); else if (auto mappingType = dynamic_cast<MappingType const*>(type)) type = mappingType->valueType(); else solAssert(false, ""); break; } case Type::Category::Struct: { solAssert(symbArguments.empty(), ""); smt::SymbolicStructVariable structVar(dynamic_cast<StructType const*>(type), "struct_temp_" + std::to_string(_funCall.id()), m_context); m_context.addAssertion(structVar.currentValue() == currentExpr); auto returnedMembers = structGetterReturnedMembers(dynamic_cast<StructType const&>(*structVar.type())); solAssert(!returnedMembers.empty(), ""); auto returnedValues = applyMap(returnedMembers, [&](std::string const& memberName) -> std::optional<smtutil::Expression> { return structVar.member(memberName); }); defineExpr(_funCall, returnedValues); return; } default: { // Unsupported cases, do nothing and the getter will be abstracted. return; } } } } bool SMTEncoder::shouldAnalyze(SourceUnit const& _source) const { return m_settings.contracts.isDefault() || m_settings.contracts.has(*_source.annotation().path); } bool SMTEncoder::shouldAnalyze(ContractDefinition const& _contract) const { if (!_contract.canBeDeployed()) return false; return m_settings.contracts.isDefault() || m_settings.contracts.has(_contract.sourceUnitName()); } void SMTEncoder::visitTypeConversion(FunctionCall const& _funCall) { solAssert(*_funCall.annotation().kind == FunctionCallKind::TypeConversion, ""); solAssert(_funCall.arguments().size() == 1, ""); auto argument = _funCall.arguments().front(); auto const argType = argument->annotation().type; auto const funCallType = _funCall.annotation().type; auto symbArg = expr(*argument, funCallType); if (smt::isStringLiteral(*argType) && smt::isFixedBytes(*funCallType)) { defineExpr(_funCall, symbArg); return; } ArrayType const* arrayType = dynamic_cast<ArrayType const*>(argType); if (auto sliceType = dynamic_cast<ArraySliceType const*>(argType)) arrayType = &sliceType->arrayType(); if (arrayType && arrayType->isByteArrayOrString() && smt::isFixedBytes(*funCallType)) { auto array = std::dynamic_pointer_cast<smt::SymbolicArrayVariable>(m_context.expression(*argument)); bytesToFixedBytesAssertions(*array, _funCall); return; } // TODO Simplify this whole thing for 0.8.0 where weird casts are disallowed. unsigned argSize = argType->storageBytes(); unsigned castSize = funCallType->storageBytes(); bool castIsSigned = smt::isNumber(*funCallType) && smt::isSigned(funCallType); bool argIsSigned = smt::isNumber(*argType) && smt::isSigned(argType); std::optional<smtutil::Expression> symbMin; std::optional<smtutil::Expression> symbMax; if (smt::isNumber(*funCallType)) { symbMin = smt::minValue(funCallType); symbMax = smt::maxValue(funCallType); } if (argSize == castSize) { // If sizes are the same, it's possible that the signs are different. if (smt::isNumber(*funCallType) && smt::isNumber(*argType)) { // castIsSigned && !argIsSigned => might overflow if arg > castType.max // !castIsSigned && argIsSigned => might underflow if arg < castType.min // !castIsSigned && !argIsSigned => ok // castIsSigned && argIsSigned => ok if (castIsSigned && !argIsSigned) { auto wrap = smtutil::Expression::ite( symbArg > *symbMax, symbArg - (*symbMax - *symbMin + 1), symbArg ); defineExpr(_funCall, wrap); } else if (!castIsSigned && argIsSigned) { auto wrap = smtutil::Expression::ite( symbArg < *symbMin, symbArg + (*symbMax + 1), symbArg ); defineExpr(_funCall, wrap); } else defineExpr(_funCall, symbArg); } else defineExpr(_funCall, symbArg); } else if (castSize > argSize) { solAssert(smt::isNumber(*funCallType), ""); // RationalNumbers have size 32. solAssert(argType->category() != Type::Category::RationalNumber, ""); // castIsSigned && !argIsSigned => ok // castIsSigned && argIsSigned => ok // !castIsSigned && !argIsSigned => ok except for FixedBytesType, need to adjust padding // !castIsSigned && argIsSigned => might underflow if arg < castType.min if (!castIsSigned && argIsSigned) { auto wrap = smtutil::Expression::ite( symbArg < *symbMin, symbArg + (*symbMax + 1), symbArg ); defineExpr(_funCall, wrap); } else if (!castIsSigned && !argIsSigned) { if (auto const* fixedCast = dynamic_cast<FixedBytesType const*>(funCallType)) { auto const* fixedArg = dynamic_cast<FixedBytesType const*>(argType); solAssert(fixedArg, ""); auto diff = fixedCast->numBytes() - fixedArg->numBytes(); solAssert(diff > 0, ""); auto bvSize = fixedCast->numBytes() * 8; defineExpr( _funCall, smtutil::Expression::bv2int(smtutil::Expression::int2bv(symbArg, bvSize) << smtutil::Expression::int2bv(diff * 8, bvSize)) ); } else defineExpr(_funCall, symbArg); } else defineExpr(_funCall, symbArg); } else // castSize < argSize { solAssert(smt::isNumber(*funCallType), ""); RationalNumberType const* rationalType = isConstant(*argument); if (rationalType) { // The TypeChecker guarantees that a constant fits in the cast size. defineExpr(_funCall, symbArg); return; } auto const* fixedCast = dynamic_cast<FixedBytesType const*>(funCallType); auto const* fixedArg = dynamic_cast<FixedBytesType const*>(argType); if (fixedCast && fixedArg) { createExpr(_funCall); auto diff = argSize - castSize; solAssert(fixedArg->numBytes() - fixedCast->numBytes() == diff, ""); auto argValueBV = smtutil::Expression::int2bv(symbArg, argSize * 8); auto shr = smtutil::Expression::int2bv(diff * 8, argSize * 8); solAssert(!castIsSigned, ""); defineExpr(_funCall, smtutil::Expression::bv2int(argValueBV >> shr)); } else { auto argValueBV = smtutil::Expression::int2bv(symbArg, castSize * 8); defineExpr(_funCall, smtutil::Expression::bv2int(argValueBV, castIsSigned)); } } } void SMTEncoder::visitFunctionIdentifier(Identifier const& _identifier) { auto const& fType = dynamic_cast<FunctionType const&>(*_identifier.annotation().type); if (replaceUserTypes(fType.returnParameterTypes()).size() == 1) { defineGlobalVariable(fType.identifier(), _identifier); m_context.createExpression(_identifier, m_context.globalSymbol(fType.identifier())); } } void SMTEncoder::visitStructConstructorCall(FunctionCall const& _funCall) { solAssert(*_funCall.annotation().kind == FunctionCallKind::StructConstructorCall, ""); if (smt::isNonRecursiveStruct(*_funCall.annotation().type)) { auto& structSymbolicVar = dynamic_cast<smt::SymbolicStructVariable&>(*m_context.expression(_funCall)); auto structType = dynamic_cast<StructType const*>(structSymbolicVar.type()); solAssert(structType, ""); auto const& structMembers = structType->structDefinition().members(); solAssert(structMembers.size() == _funCall.sortedArguments().size(), ""); auto args = _funCall.sortedArguments(); structSymbolicVar.assignAllMembers(applyMap( ranges::views::zip(args, structMembers), [this] (auto const& argMemberPair) { return expr(*argMemberPair.first, argMemberPair.second->type()); } )); } } void SMTEncoder::endVisit(Literal const& _literal) { solAssert(_literal.annotation().type, "Expected type for AST node"); Type const& type = *_literal.annotation().type; if (smt::isNumber(type)) defineExpr(_literal, smtutil::Expression(type.literalValue(&_literal))); else if (smt::isBool(type)) defineExpr(_literal, smtutil::Expression(_literal.token() == Token::TrueLiteral ? true : false)); else if (smt::isStringLiteral(type)) { createExpr(_literal); // Add constraints for the length and values as it is known. auto symbArray = std::dynamic_pointer_cast<smt::SymbolicArrayVariable>(m_context.expression(_literal)); solAssert(symbArray, ""); addArrayLiteralAssertions( *symbArray, applyMap(_literal.value(), [](unsigned char c) { return smtutil::Expression{size_t(c)}; }) ); } else solAssert(false, ""); } void SMTEncoder::addArrayLiteralAssertions( smt::SymbolicArrayVariable& _symArray, std::vector<smtutil::Expression> const& _elementValues ) { m_context.addAssertion(_symArray.length() == _elementValues.size()); // Assert to the solver that _elementValues are exactly the elements at the beginning of the array. // Since we create new symbolic representation for every array literal in the source file, we want to ensure that // representations of two equal literals are also equal. For this reason we always start from constant-zero array. // This ensures SMT-LIB arrays (which are infinite) are also equal beyond the length of the Solidity array literal. auto type = _symArray.type(); smtAssert(type); auto valueType = [&]() { if (auto const* arrayType = dynamic_cast<ArrayType const*>(type)) return arrayType->baseType(); if (smt::isStringLiteral(*type)) return TypeProvider::stringMemory()->baseType(); smtAssert(false); }(); auto tupleSort = std::dynamic_pointer_cast<smtutil::TupleSort>(smt::smtSort(*type)); auto sortSort = std::make_shared<smtutil::SortSort>(tupleSort->components.front()); smtutil::Expression arrayExpr = smtutil::Expression::const_array(smtutil::Expression(sortSort), smt::zeroValue(valueType)); smtAssert(arrayExpr.sort->kind == smtutil::Kind::Array); for (size_t i = 0; i < _elementValues.size(); i++) arrayExpr = smtutil::Expression::store(arrayExpr, smtutil::Expression(i), _elementValues[i]); m_context.addAssertion(_symArray.elements() == arrayExpr); } void SMTEncoder::bytesToFixedBytesAssertions( smt::SymbolicArrayVariable& _symArray, Expression const& _fixedBytes ) { auto const& fixed = dynamic_cast<FixedBytesType const&>(*_fixedBytes.annotation().type); auto intType = TypeProvider::uint256(); std::string suffix = std::to_string(_fixedBytes.id()) + "_" + std::to_string(m_context.newUniqueId()); smt::SymbolicIntVariable k(intType, intType, "k_" + suffix, m_context); m_context.addAssertion(k.currentValue() == 0); size_t n = fixed.numBytes(); for (size_t i = 0; i < n; i++) { auto kPrev = k.currentValue(); m_context.addAssertion((smtutil::Expression::select(_symArray.elements(), i) * (u256(1) << ((n - i - 1) * 8))) + kPrev == k.increaseIndex()); } m_context.addAssertion(expr(_fixedBytes) == k.currentValue()); } void SMTEncoder::endVisit(Return const& _return) { if (_return.expression() && m_context.knownExpression(*_return.expression())) { auto returnParams = m_callStack.back().first->returnParameters(); if (returnParams.size() > 1) { auto const& symbTuple = std::dynamic_pointer_cast<smt::SymbolicTupleVariable>(m_context.expression(*_return.expression())); solAssert(symbTuple, ""); solAssert(symbTuple->components().size() == returnParams.size(), ""); auto const* tupleType = dynamic_cast<TupleType const*>(_return.expression()->annotation().type); solAssert(tupleType, ""); auto const& types = tupleType->components(); solAssert(types.size() == returnParams.size(), ""); for (unsigned i = 0; i < returnParams.size(); ++i) assignment(*returnParams.at(i), symbTuple->component(i, types.at(i), returnParams.at(i)->type())); } else if (returnParams.size() == 1) assignment(*returnParams.front(), expr(*_return.expression(), returnParams.front()->type())); } } bool SMTEncoder::visit(MemberAccess const& _memberAccess) { createExpr(_memberAccess); auto const& accessType = _memberAccess.annotation().type; if (accessType->category() == Type::Category::Function) { auto const* functionType = dynamic_cast<FunctionType const*>(_memberAccess.annotation().type); if (functionType && functionType->hasDeclaration()) defineExpr( _memberAccess, util::selectorFromSignatureU32(functionType->richIdentifier()) ); return true; } Expression const* memberExpr = innermostTuple(_memberAccess.expression()); auto const& exprType = memberExpr->annotation().type; solAssert(exprType, ""); if (exprType->category() == Type::Category::Magic) { if (auto const* identifier = dynamic_cast<Identifier const*>(memberExpr)) { auto const& name = identifier->name(); solAssert(name == "block" || name == "msg" || name == "tx", ""); auto memberName = _memberAccess.memberName(); // TODO remove this for 0.9.0 if (name == "block" && memberName == "difficulty") memberName = "prevrandao"; defineExpr(_memberAccess, state().txMember(name + "." + memberName)); } else if (auto magicType = dynamic_cast<MagicType const*>(exprType)) { if (magicType->kind() == MagicType::Kind::Block) defineExpr(_memberAccess, state().txMember("block." + _memberAccess.memberName())); else if (magicType->kind() == MagicType::Kind::Message) defineExpr(_memberAccess, state().txMember("msg." + _memberAccess.memberName())); else if (magicType->kind() == MagicType::Kind::Transaction) defineExpr(_memberAccess, state().txMember("tx." + _memberAccess.memberName())); else if (magicType->kind() == MagicType::Kind::MetaType) { auto const& memberName = _memberAccess.memberName(); if (memberName == "min" || memberName == "max") { if (IntegerType const* integerType = dynamic_cast<IntegerType const*>(magicType->typeArgument())) defineExpr(_memberAccess, memberName == "min" ? integerType->minValue() : integerType->maxValue()); else if (EnumType const* enumType = dynamic_cast<EnumType const*>(magicType->typeArgument())) defineExpr(_memberAccess, memberName == "min" ? enumType->minValue() : enumType->maxValue()); } else if (memberName == "interfaceId") { ContractDefinition const& contract = dynamic_cast<ContractType const&>(*magicType->typeArgument()).contractDefinition(); defineExpr(_memberAccess, contract.interfaceId()); } else // NOTE: supporting name, creationCode, runtimeCode would be easy enough, but the bytes/string they return are not // at all usable in the SMT checker currently m_unsupportedErrors.warning( 7507_error, _memberAccess.location(), "Assertion checker does not yet support this expression." ); } } else solAssert(false, ""); return false; } else if (smt::isNonRecursiveStruct(*exprType)) { memberExpr->accept(*this); auto const& symbStruct = std::dynamic_pointer_cast<smt::SymbolicStructVariable>(m_context.expression(*memberExpr)); defineExpr(_memberAccess, symbStruct->member(_memberAccess.memberName())); return false; } else if (exprType->category() == Type::Category::TypeType) { auto const* decl = expressionToDeclaration(*memberExpr); if (dynamic_cast<EnumDefinition const*>(decl)) { auto enumType = dynamic_cast<EnumType const*>(accessType); solAssert(enumType, ""); defineExpr(_memberAccess, enumType->memberValue(_memberAccess.memberName())); return false; } else if (dynamic_cast<ContractDefinition const*>(decl)) { if (auto const* var = dynamic_cast<VariableDeclaration const*>(_memberAccess.annotation().referencedDeclaration)) { if (var->isConstant()) defineExpr(_memberAccess, constantExpr(_memberAccess, *var)); else defineExpr(_memberAccess, currentValue(*var)); return false; } } } else if (exprType->category() == Type::Category::Address) { memberExpr->accept(*this); if (_memberAccess.memberName() == "balance") { defineExpr(_memberAccess, state().balance(expr(*memberExpr))); setSymbolicUnknownValue(*m_context.expression(_memberAccess), m_context); m_uninterpretedTerms.insert(&_memberAccess); return false; } } else if (exprType->category() == Type::Category::Array) { memberExpr->accept(*this); if (_memberAccess.memberName() == "length") { auto symbArray = std::dynamic_pointer_cast<smt::SymbolicArrayVariable>(m_context.expression(*memberExpr)); solAssert(symbArray, ""); defineExpr(_memberAccess, symbArray->length()); m_uninterpretedTerms.insert(&_memberAccess); setSymbolicUnknownValue( expr(_memberAccess), _memberAccess.annotation().type, m_context ); } return false; } else if ( auto const* functionType = dynamic_cast<FunctionType const*>(exprType); functionType && _memberAccess.memberName() == "selector" && functionType->hasDeclaration() ) { defineExpr(_memberAccess, functionType->externalIdentifier()); return false; } else if (exprType->category() == Type::Category::Module) { if (auto const* var = dynamic_cast<VariableDeclaration const*>(_memberAccess.annotation().referencedDeclaration)) { solAssert(var->isConstant(), ""); defineExpr(_memberAccess, constantExpr(_memberAccess, *var)); return false; } } m_unsupportedErrors.warning( 7650_error, _memberAccess.location(), "Assertion checker does not yet support this expression." ); return true; } void SMTEncoder::endVisit(IndexAccess const& _indexAccess) { createExpr(_indexAccess); if (_indexAccess.annotation().type->category() == Type::Category::TypeType) return; makeOutOfBoundsVerificationTarget(_indexAccess); if (auto const* type = dynamic_cast<FixedBytesType const*>(_indexAccess.baseExpression().annotation().type)) { smtutil::Expression base = expr(_indexAccess.baseExpression()); if (type->numBytes() == 1) defineExpr(_indexAccess, base); else { auto [bvSize, isSigned] = smt::typeBvSizeAndSignedness(_indexAccess.baseExpression().annotation().type); solAssert(!isSigned, ""); solAssert(bvSize >= 16, ""); solAssert(bvSize % 8 == 0, ""); smtutil::Expression idx = expr(*_indexAccess.indexExpression()); auto bvBase = smtutil::Expression::int2bv(base, bvSize); auto bvShl = smtutil::Expression::int2bv(idx * 8, bvSize); auto bvShr = smtutil::Expression::int2bv(bvSize - 8, bvSize); auto result = (bvBase << bvShl) >> bvShr; auto anyValue = expr(_indexAccess); m_context.expression(_indexAccess)->increaseIndex(); unsigned numBytes = bvSize / 8; auto withBound = smtutil::Expression::ite( idx < numBytes, smtutil::Expression::bv2int(result, false), anyValue ); defineExpr(_indexAccess, withBound); } return; } std::shared_ptr<smt::SymbolicVariable> array; if (auto const* id = dynamic_cast<Identifier const*>(&_indexAccess.baseExpression())) { auto varDecl = identifierToVariable(*id); solAssert(varDecl, ""); array = m_context.variable(*varDecl); if (varDecl && varDecl->isConstant()) m_context.addAssertion(currentValue(*varDecl) == expr(*id)); } else { solAssert(m_context.knownExpression(_indexAccess.baseExpression()), ""); array = m_context.expression(_indexAccess.baseExpression()); } auto arrayVar = std::dynamic_pointer_cast<smt::SymbolicArrayVariable>(array); solAssert(arrayVar, ""); Type const* baseType = _indexAccess.baseExpression().annotation().type; defineExpr(_indexAccess, smtutil::Expression::select( arrayVar->elements(), expr(*_indexAccess.indexExpression(), keyType(baseType)) )); setSymbolicUnknownValue( expr(_indexAccess), _indexAccess.annotation().type, m_context ); m_uninterpretedTerms.insert(&_indexAccess); } void SMTEncoder::endVisit(IndexRangeAccess const& _indexRangeAccess) { createExpr(_indexRangeAccess); /// The actual slice is created by CHC which also assigns the length. } void SMTEncoder::arrayAssignment() { m_arrayAssignmentHappened = true; } void SMTEncoder::indexOrMemberAssignment(Expression const& _expr, smtutil::Expression const& _rightHandSide) { auto toStore = _rightHandSide; auto const* lastExpr = &_expr; while (true) { if (auto const* indexAccess = dynamic_cast<IndexAccess const*>(lastExpr)) { auto const& base = indexAccess->baseExpression(); if (dynamic_cast<Identifier const*>(&base)) base.accept(*this); Type const* baseType = base.annotation().type; auto indexExpr = expr(*indexAccess->indexExpression(), keyType(baseType)); auto symbArray = std::dynamic_pointer_cast<smt::SymbolicArrayVariable>(m_context.expression(base)); solAssert(symbArray, ""); toStore = smtutil::Expression::tuple_constructor( smtutil::Expression(std::make_shared<smtutil::SortSort>(smt::smtSort(*baseType)), baseType->toString(true)), {smtutil::Expression::store(symbArray->elements(), indexExpr, toStore), symbArray->length()} ); defineExpr(*indexAccess, smtutil::Expression::select( symbArray->elements(), indexExpr )); lastExpr = &indexAccess->baseExpression(); } else if (auto const* memberAccess = dynamic_cast<MemberAccess const*>(lastExpr)) { auto const& base = memberAccess->expression(); if (dynamic_cast<Identifier const*>(&base)) base.accept(*this); if ( auto const* structType = dynamic_cast<StructType const*>(base.annotation().type); structType && structType->recursive() ) { m_unsupportedErrors.warning( 4375_error, memberAccess->location(), "Assertion checker does not support recursive structs." ); return; } if (auto varDecl = identifierToVariable(*memberAccess)) { if (varDecl->hasReferenceOrMappingType()) resetReferences(*varDecl); assignment(*varDecl, toStore); break; } auto symbStruct = std::dynamic_pointer_cast<smt::SymbolicStructVariable>(m_context.expression(base)); solAssert(symbStruct, ""); symbStruct->assignMember(memberAccess->memberName(), toStore); toStore = symbStruct->currentValue(); defineExpr(*memberAccess, symbStruct->member(memberAccess->memberName())); lastExpr = &memberAccess->expression(); } else if (auto const& id = dynamic_cast<Identifier const*>(lastExpr)) { auto varDecl = identifierToVariable(*id); solAssert(varDecl, ""); if (varDecl->hasReferenceOrMappingType()) resetReferences(*varDecl); assignment(*varDecl, toStore); defineExpr(*id, currentValue(*varDecl)); break; } else { auto type = lastExpr->annotation().type; if ( dynamic_cast<ReferenceType const*>(type) || dynamic_cast<MappingType const*>(type) ) resetReferences(type); assignment(*m_context.expression(*lastExpr), toStore); break; } } } void SMTEncoder::arrayPush(FunctionCall const& _funCall) { auto memberAccess = dynamic_cast<MemberAccess const*>(&_funCall.expression()); solAssert(memberAccess, ""); auto symbArray = std::dynamic_pointer_cast<smt::SymbolicArrayVariable>(m_context.expression(memberAccess->expression())); solAssert(symbArray, ""); auto oldLength = symbArray->length(); m_context.addAssertion(oldLength >= 0); // Real world assumption: the array length is assumed to not overflow. // This assertion guarantees that both the current and updated lengths have the above property. m_context.addAssertion(oldLength + 1 < (smt::maxValue(*TypeProvider::uint256()) - 1)); auto const& arguments = _funCall.arguments(); auto arrayType = dynamic_cast<ArrayType const*>(symbArray->type()); solAssert(arrayType, ""); auto elementType = arrayType->baseType(); smtutil::Expression element = arguments.empty() ? smt::zeroValue(elementType) : expr(*arguments.front(), elementType); smtutil::Expression store = smtutil::Expression::store( symbArray->elements(), oldLength, element ); symbArray->increaseIndex(); m_context.addAssertion(symbArray->elements() == store); m_context.addAssertion(symbArray->length() == oldLength + 1); if (arguments.empty()) defineExpr(_funCall, element); assignment(memberAccess->expression(), symbArray->currentValue()); } void SMTEncoder::arrayPop(FunctionCall const& _funCall) { auto memberAccess = dynamic_cast<MemberAccess const*>(cleanExpression(_funCall.expression())); solAssert(memberAccess, ""); auto symbArray = std::dynamic_pointer_cast<smt::SymbolicArrayVariable>(m_context.expression(memberAccess->expression())); solAssert(symbArray, ""); makeArrayPopVerificationTarget(_funCall); auto oldElements = symbArray->elements(); auto oldLength = symbArray->length(); symbArray->increaseIndex(); m_context.addAssertion(symbArray->elements() == oldElements); auto newLength = smtutil::Expression::ite( oldLength > 0, oldLength - 1, 0 ); m_context.addAssertion(symbArray->length() == newLength); assignment(memberAccess->expression(), symbArray->currentValue()); } void SMTEncoder::defineGlobalVariable(std::string const& _name, Expression const& _expr, bool _increaseIndex) { if (!m_context.knownGlobalSymbol(_name)) { bool abstract = m_context.createGlobalSymbol(_name, _expr); if (abstract) m_unsupportedErrors.warning( 1695_error, _expr.location(), "Assertion checker does not yet support this global variable." ); } else if (_increaseIndex) m_context.globalSymbol(_name)->increaseIndex(); // The default behavior is not to increase the index since // most of the global values stay the same throughout a tx. if (isSupportedType(*_expr.annotation().type)) defineExpr(_expr, m_context.globalSymbol(_name)->currentValue()); } bool SMTEncoder::shortcutRationalNumber(Expression const& _expr) { RationalNumberType const* rationalType = isConstant(_expr); if (!rationalType) return false; if (rationalType->isNegative()) defineExpr(_expr, smtutil::Expression(u2s(rationalType->literalValue(nullptr)))); else defineExpr(_expr, smtutil::Expression(rationalType->literalValue(nullptr))); return true; } void SMTEncoder::arithmeticOperation(BinaryOperation const& _op) { auto type = _op.annotation().commonType; solAssert(type, ""); solAssert(type->category() == Type::Category::Integer || type->category() == Type::Category::FixedPoint, ""); switch (_op.getOperator()) { case Token::Add: case Token::Sub: case Token::Mul: case Token::Div: case Token::Mod: { auto values = arithmeticOperation( _op.getOperator(), expr(_op.leftExpression()), expr(_op.rightExpression()), _op.annotation().commonType, _op ); defineExpr(_op, values.first); break; } default: m_unsupportedErrors.warning( 5188_error, _op.location(), "Assertion checker does not yet implement this operator." ); } } std::pair<smtutil::Expression, smtutil::Expression> SMTEncoder::arithmeticOperation( Token _op, smtutil::Expression const& _left, smtutil::Expression const& _right, Type const* _commonType, Expression const& _operation ) { static std::set<Token> validOperators{ Token::Add, Token::Sub, Token::Mul, Token::Div, Token::Mod }; solAssert(validOperators.count(_op), ""); solAssert(_commonType, ""); solAssert( _commonType->category() == Type::Category::Integer || _commonType->category() == Type::Category::FixedPoint, "" ); IntegerType const* intType = nullptr; if (auto type = dynamic_cast<IntegerType const*>(_commonType)) intType = type; else intType = TypeProvider::uint256(); auto valueUnbounded = [&]() -> smtutil::Expression { switch (_op) { case Token::Add: return _left + _right; case Token::Sub: return _left - _right; case Token::Mul: return _left * _right; case Token::Div: return divModWithSlacks(_left, _right, *intType).first; case Token::Mod: return divModWithSlacks(_left, _right, *intType).second; default: solAssert(false, ""); } }(); if (m_checked) return {valueUnbounded, valueUnbounded}; if (_op == Token::Div || _op == Token::Mod) { // mod and unsigned division never underflow/overflow if (_op == Token::Mod || !intType->isSigned()) return {valueUnbounded, valueUnbounded}; // The only case where division overflows is // - type is signed // - LHS is type.min // - RHS is -1 // the result is then -(type.min), which wraps back to type.min smtutil::Expression maxLeft = _left == smt::minValue(*intType); smtutil::Expression minusOneRight = _right == std::numeric_limits<size_t >::max(); smtutil::Expression wrap = smtutil::Expression::ite(maxLeft && minusOneRight, smt::minValue(*intType), valueUnbounded); return {wrap, valueUnbounded}; } auto symbMin = smt::minValue(*intType); auto symbMax = smt::maxValue(*intType); smtutil::Expression intValueRange = (0 - symbMin) + symbMax + 1; std::string suffix = std::to_string(_operation.id()) + "_" + std::to_string(m_context.newUniqueId()); smt::SymbolicIntVariable k(intType, intType, "k_" + suffix, m_context); smt::SymbolicIntVariable m(intType, intType, "m_" + suffix, m_context); // To wrap around valueUnbounded in case of overflow or underflow, we replace it with a k, given: // 1. k + m * intValueRange = valueUnbounded // 2. k is in range of the desired integer type auto wrap = k.currentValue(); m_context.addAssertion(valueUnbounded == (k.currentValue() + intValueRange * m.currentValue())); m_context.addAssertion(k.currentValue() >= symbMin); m_context.addAssertion(k.currentValue() <= symbMax); // TODO this could be refined: // for unsigned types it's enough to check only the upper bound. auto value = smtutil::Expression::ite( valueUnbounded > symbMax, wrap, smtutil::Expression::ite( valueUnbounded < symbMin, wrap, valueUnbounded ) ); return {value, valueUnbounded}; } smtutil::Expression SMTEncoder::bitwiseOperation( Token _op, smtutil::Expression const& _left, smtutil::Expression const& _right, Type const* _commonType ) { static std::set<Token> validOperators{ Token::BitAnd, Token::BitOr, Token::BitXor, Token::SHL, Token::SHR, Token::SAR }; solAssert(validOperators.count(_op), ""); solAssert(_commonType, ""); auto [bvSize, isSigned] = smt::typeBvSizeAndSignedness(_commonType); auto bvLeft = smtutil::Expression::int2bv(_left, bvSize); auto bvRight = smtutil::Expression::int2bv(_right, bvSize); std::optional<smtutil::Expression> result; switch (_op) { case Token::BitAnd: result = bvLeft & bvRight; break; case Token::BitOr: result = bvLeft | bvRight; break; case Token::BitXor: result = bvLeft ^ bvRight; break; case Token::SHL: result = bvLeft << bvRight; break; case Token::SHR: result = bvLeft >> bvRight; break; case Token::SAR: result = isSigned ? smtutil::Expression::ashr(bvLeft, bvRight) : bvLeft >> bvRight; break; default: solAssert(false, ""); } solAssert(result.has_value(), ""); return smtutil::Expression::bv2int(*result, isSigned); } void SMTEncoder::compareOperation(BinaryOperation const& _op) { auto commonType = _op.annotation().commonType; solAssert(commonType, ""); if (isSupportedType(*commonType)) { smtutil::Expression left(expr(_op.leftExpression(), commonType)); smtutil::Expression right(expr(_op.rightExpression(), commonType)); Token op = _op.getOperator(); std::shared_ptr<smtutil::Expression> value; if (smt::isNumber(*commonType)) { value = std::make_shared<smtutil::Expression>( op == Token::Equal ? (left == right) : op == Token::NotEqual ? (left != right) : op == Token::LessThan ? (left < right) : op == Token::LessThanOrEqual ? (left <= right) : op == Token::GreaterThan ? (left > right) : /*op == Token::GreaterThanOrEqual*/ (left >= right) ); } else // Bool { solUnimplementedAssert(smt::isBool(*commonType), "Operation not yet supported"); value = std::make_shared<smtutil::Expression>( op == Token::Equal ? (left == right) : /*op == Token::NotEqual*/ (left != right) ); } // TODO: check that other values for op are not possible. defineExpr(_op, *value); } else m_unsupportedErrors.warning( 7229_error, _op.location(), "Assertion checker does not yet implement the type " + _op.annotation().commonType->toString() + " for comparisons" ); } void SMTEncoder::booleanOperation(BinaryOperation const& _op) { solAssert(_op.getOperator() == Token::And || _op.getOperator() == Token::Or, ""); solAssert(_op.annotation().commonType, ""); solAssert(_op.annotation().commonType->category() == Type::Category::Bool, ""); // @TODO check that both of them are not constant _op.leftExpression().accept(*this); if (_op.getOperator() == Token::And) { auto indicesAfterSecond = visitBranch(&_op.rightExpression(), expr(_op.leftExpression())).first; mergeVariables(!expr(_op.leftExpression()), copyVariableIndices(), indicesAfterSecond); defineExpr(_op, expr(_op.leftExpression()) && expr(_op.rightExpression())); } else { auto indicesAfterSecond = visitBranch(&_op.rightExpression(), !expr(_op.leftExpression())).first; mergeVariables(expr(_op.leftExpression()), copyVariableIndices(), indicesAfterSecond); defineExpr(_op, expr(_op.leftExpression()) || expr(_op.rightExpression())); } } void SMTEncoder::bitwiseOperation(BinaryOperation const& _op) { auto op = _op.getOperator(); solAssert(TokenTraits::isBitOp(op) || TokenTraits::isShiftOp(op), ""); auto commonType = _op.annotation().commonType; solAssert(commonType, ""); defineExpr(_op, bitwiseOperation( _op.getOperator(), expr(_op.leftExpression(), commonType), expr(_op.rightExpression(), commonType), commonType )); } void SMTEncoder::bitwiseNotOperation(UnaryOperation const& _op) { solAssert(_op.getOperator() == Token::BitNot, ""); auto [bvSize, isSigned] = smt::typeBvSizeAndSignedness(_op.annotation().type); auto bvOperand = smtutil::Expression::int2bv(expr(_op.subExpression(), _op.annotation().type), bvSize); defineExpr(_op, smtutil::Expression::bv2int(~bvOperand, isSigned)); } std::pair<smtutil::Expression, smtutil::Expression> SMTEncoder::divModWithSlacks( smtutil::Expression _left, smtutil::Expression _right, IntegerType const& _type ) { if (m_settings.divModNoSlacks) return {_left / _right, _left % _right}; IntegerType const* intType = &_type; std::string suffix = "div_mod_" + std::to_string(m_context.newUniqueId()); smt::SymbolicIntVariable dSymb(intType, intType, "d_" + suffix, m_context); smt::SymbolicIntVariable rSymb(intType, intType, "r_" + suffix, m_context); auto d = dSymb.currentValue(); auto r = rSymb.currentValue(); // x / y = d and x % y = r iff d * y + r = x and // either x >= 0 and 0 <= r < abs(y) (or just 0 <= r < y for unsigned) // or x < 0 and -abs(y) < r <= 0 m_context.addAssertion(((d * _right) + r) == _left); if (_type.isSigned()) m_context.addAssertion( (_left >= 0 && 0 <= r && (_right == 0 || r < smtutil::abs(_right))) || (_left < 0 && ((_right == 0 || 0 - smtutil::abs(_right) < r) && r <= 0)) ); else // unsigned version m_context.addAssertion(0 <= r && (_right == 0 || r < _right)); auto divResult = smtutil::Expression::ite(_right == 0, 0, d); auto modResult = smtutil::Expression::ite(_right == 0, 0, r); return {divResult, modResult}; } void SMTEncoder::assignment(Expression const& _left, smtutil::Expression const& _right) { assignment(_left, _right, _left.annotation().type); } void SMTEncoder::assignment( Expression const& _left, smtutil::Expression const& _right, Type const* _type ) { solAssert( _left.annotation().type->category() != Type::Category::Tuple, "Tuple assignments should be handled by tupleAssignment." ); Expression const* left = cleanExpression(_left); if (!isSupportedType(*_type)) { // Give it a new index anyway to keep the SSA scheme sound. if (auto varDecl = identifierToVariable(*left)) m_context.newValue(*varDecl); } else if (auto varDecl = identifierToVariable(*left)) { if (varDecl->hasReferenceOrMappingType()) resetReferences(*varDecl); assignment(*varDecl, _right); } else if ( dynamic_cast<IndexAccess const*>(left) || dynamic_cast<MemberAccess const*>(left) ) indexOrMemberAssignment(*left, _right); else if (auto const* funCall = dynamic_cast<FunctionCall const*>(left)) { if (auto funType = dynamic_cast<FunctionType const*>(funCall->expression().annotation().type)) { if (funType->kind() == FunctionType::Kind::ArrayPush) { auto memberAccess = dynamic_cast<MemberAccess const*>(&funCall->expression()); solAssert(memberAccess, ""); auto symbArray = std::dynamic_pointer_cast<smt::SymbolicArrayVariable>(m_context.expression(memberAccess->expression())); solAssert(symbArray, ""); auto oldLength = symbArray->length(); auto store = smtutil::Expression::store( symbArray->elements(), symbArray->length() - 1, _right ); symbArray->increaseIndex(); m_context.addAssertion(symbArray->elements() == store); m_context.addAssertion(symbArray->length() == oldLength); assignment(memberAccess->expression(), symbArray->currentValue()); } else if (funType->kind() == FunctionType::Kind::Internal) { for (auto type: replaceUserTypes(funType->returnParameterTypes())) if (type->category() == Type::Category::Mapping || dynamic_cast<ReferenceType const*>(type)) resetReferences(type); } } } else solAssert(false, ""); } void SMTEncoder::tupleAssignment(Expression const& _left, Expression const& _right) { auto lTuple = dynamic_cast<TupleExpression const*>(innermostTuple(_left)); solAssert(lTuple, ""); Expression const* right = innermostTuple(_right); auto const& lComponents = lTuple->components(); // If both sides are tuple expressions, we individually and potentially // recursively assign each pair of components. // This is because of potential type conversion. if (auto rTuple = dynamic_cast<TupleExpression const*>(right)) { auto const& rComponents = rTuple->components(); solAssert(lComponents.size() == rComponents.size(), ""); for (unsigned i = 0; i < lComponents.size(); ++i) { if (!lComponents.at(i) || !rComponents.at(i)) continue; auto const& lExpr = *lComponents.at(i); auto const& rExpr = *rComponents.at(i); if (lExpr.annotation().type->category() == Type::Category::Tuple) tupleAssignment(lExpr, rExpr); else { auto type = lExpr.annotation().type; assignment(lExpr, expr(rExpr, type), type); } } } else { auto rType = dynamic_cast<TupleType const*>(right->annotation().type); solAssert(rType, ""); auto const& rComponents = rType->components(); solAssert(lComponents.size() == rComponents.size(), ""); auto symbRight = expr(*right); solAssert(symbRight.sort->kind == smtutil::Kind::Tuple, ""); for (unsigned i = 0; i < lComponents.size(); ++i) if (auto component = lComponents.at(i); component && rComponents.at(i)) assignment(*component, smtutil::Expression::tuple_get(symbRight, i), component->annotation().type); } } smtutil::Expression SMTEncoder::compoundAssignment(Assignment const& _assignment) { static std::map<Token, Token> const compoundToArithmetic{ {Token::AssignAdd, Token::Add}, {Token::AssignSub, Token::Sub}, {Token::AssignMul, Token::Mul}, {Token::AssignDiv, Token::Div}, {Token::AssignMod, Token::Mod} }; static std::map<Token, Token> const compoundToBitwise{ {Token::AssignBitAnd, Token::BitAnd}, {Token::AssignBitOr, Token::BitOr}, {Token::AssignBitXor, Token::BitXor}, {Token::AssignShl, Token::SHL}, {Token::AssignShr, Token::SHR}, {Token::AssignSar, Token::SAR} }; Token op = _assignment.assignmentOperator(); solAssert(compoundToArithmetic.count(op) || compoundToBitwise.count(op), ""); auto decl = identifierToVariable(_assignment.leftHandSide()); if (compoundToBitwise.count(op)) return bitwiseOperation( compoundToBitwise.at(op), decl ? currentValue(*decl) : expr(_assignment.leftHandSide(), _assignment.annotation().type), expr(_assignment.rightHandSide(), _assignment.annotation().type), _assignment.annotation().type ); auto values = arithmeticOperation( compoundToArithmetic.at(op), decl ? currentValue(*decl) : expr(_assignment.leftHandSide(), _assignment.annotation().type), expr(_assignment.rightHandSide(), _assignment.annotation().type), _assignment.annotation().type, _assignment ); return values.first; } void SMTEncoder::expressionToTupleAssignment(std::vector<std::shared_ptr<VariableDeclaration>> const& _variables, Expression const& _rhs) { auto symbolicVar = m_context.expression(_rhs); if (_variables.size() > 1) { auto symbTuple = std::dynamic_pointer_cast<smt::SymbolicTupleVariable>(symbolicVar); solAssert(symbTuple, ""); auto const& symbComponents = symbTuple->components(); solAssert(symbComponents.size() == _variables.size(), ""); auto tupleType = dynamic_cast<TupleType const*>(_rhs.annotation().type); solAssert(tupleType, ""); auto const& typeComponents = tupleType->components(); solAssert(typeComponents.size() == symbComponents.size(), ""); for (unsigned i = 0; i < symbComponents.size(); ++i) { auto param = _variables.at(i); if (param) { solAssert(m_context.knownVariable(*param), ""); assignment(*param, symbTuple->component(i, typeComponents[i], param->type())); } } } else if (_variables.size() == 1) { auto const& var = *_variables.front(); solAssert(m_context.knownVariable(var), ""); assignment(var, _rhs); } } void SMTEncoder::assignment(VariableDeclaration const& _variable, Expression const& _value) { // In general, at this point, the SMT sorts of _variable and _value are the same, // even if there is implicit conversion. // This is a special case where the SMT sorts are different. // For now we are unaware of other cases where this happens, but if they do appear // we should extract this into an `implicitConversion` function. assignment(_variable, expr(_value, _variable.type())); } void SMTEncoder::assignment(VariableDeclaration const& _variable, smtutil::Expression const& _value) { Type const* type = _variable.type(); if (type->category() == Type::Category::Mapping) arrayAssignment(); assignment(*m_context.variable(_variable), _value); } void SMTEncoder::assignment(smt::SymbolicVariable& _symVar, smtutil::Expression const& _value) { m_context.addAssertion(_symVar.increaseIndex() == _value); } std::pair<SMTEncoder::VariableIndices, smtutil::Expression> SMTEncoder::visitBranch( ASTNode const* _statement, smtutil::Expression _condition ) { return visitBranch(_statement, &_condition); } std::pair<SMTEncoder::VariableIndices, smtutil::Expression> SMTEncoder::visitBranch( ASTNode const* _statement, smtutil::Expression const* _condition ) { auto indicesBeforeBranch = copyVariableIndices(); if (_condition) pushPathCondition(*_condition); _statement->accept(*this); auto pathConditionOnExit = currentPathConditions(); if (_condition) popPathCondition(); auto indicesAfterBranch = copyVariableIndices(); resetVariableIndices(indicesBeforeBranch); return {indicesAfterBranch, pathConditionOnExit}; } void SMTEncoder::initializeFunctionCallParameters(CallableDeclaration const& _function, std::vector<smtutil::Expression> const& _callArgs) { auto const& funParams = _function.parameters(); solAssert(funParams.size() == _callArgs.size(), ""); for (unsigned i = 0; i < funParams.size(); ++i) if (createVariable(*funParams[i])) { m_context.addAssertion(_callArgs[i] == m_context.newValue(*funParams[i])); if (funParams[i]->annotation().type->category() == Type::Category::Mapping) m_arrayAssignmentHappened = true; } std::vector<VariableDeclaration const*> localVars; if (auto const* fun = dynamic_cast<FunctionDefinition const*>(&_function)) localVars = localVariablesIncludingModifiers(*fun, m_currentContract); else localVars = _function.localVariables(); for (auto const& variable: localVars) if (createVariable(*variable)) { m_context.newValue(*variable); m_context.setZeroValue(*variable); } if (_function.returnParameterList()) for (auto const& retParam: _function.returnParameters()) if (createVariable(*retParam)) { m_context.newValue(*retParam); m_context.setZeroValue(*retParam); } } void SMTEncoder::createStateVariables(ContractDefinition const& _contract) { for (auto var: stateVariablesIncludingInheritedAndPrivate(_contract)) createVariable(*var); } void SMTEncoder::initializeStateVariables(ContractDefinition const& _contract) { for (auto var: _contract.stateVariables()) { solAssert(m_context.knownVariable(*var), ""); m_context.setZeroValue(*var); } for (auto var: _contract.stateVariables()) if (var->value()) { var->value()->accept(*this); assignment(*var, *var->value()); } } void SMTEncoder::createLocalVariables(FunctionDefinition const& _function) { for (auto const& variable: localVariablesIncludingModifiers(_function, m_currentContract)) createVariable(*variable); for (auto const& param: _function.parameters()) createVariable(*param); if (_function.returnParameterList()) for (auto const& retParam: _function.returnParameters()) createVariable(*retParam); } void SMTEncoder::initializeLocalVariables(FunctionDefinition const& _function) { for (auto const& variable: localVariablesIncludingModifiers(_function, m_currentContract)) { solAssert(m_context.knownVariable(*variable), ""); m_context.setZeroValue(*variable); } for (auto const& param: _function.parameters()) { solAssert(m_context.knownVariable(*param), ""); m_context.setUnknownValue(*param); } if (_function.returnParameterList()) for (auto const& retParam: _function.returnParameters()) { solAssert(m_context.knownVariable(*retParam), ""); m_context.setZeroValue(*retParam); } } void SMTEncoder::resetStateVariables() { m_context.resetVariables([&](VariableDeclaration const& _variable) { return _variable.isStateVariable(); }); } void SMTEncoder::resetMemoryVariables() { m_context.resetVariables([&](VariableDeclaration const& _variable) { return _variable.referenceLocation() == VariableDeclaration::Location::Memory; }); } void SMTEncoder::resetStorageVariables() { m_context.resetVariables([&](VariableDeclaration const& _variable) { return _variable.referenceLocation() == VariableDeclaration::Location::Storage || _variable.isStateVariable(); }); } void SMTEncoder::resetBalances() { state().newBalances(); } void SMTEncoder::resetReferences(VariableDeclaration const& _varDecl) { m_context.resetVariables([&](VariableDeclaration const& _var) { if (_var == _varDecl) return false; // If both are state variables no need to clear knowledge. if (_var.isStateVariable() && _varDecl.isStateVariable()) return false; return sameTypeOrSubtype(_var.type(), _varDecl.type()); }); } void SMTEncoder::resetReferences(Type const* _type) { m_context.resetVariables([&](VariableDeclaration const& _var) { return sameTypeOrSubtype(_var.type(), _type); }); } bool SMTEncoder::sameTypeOrSubtype(Type const* _a, Type const* _b) { bool foundSame = false; solidity::util::BreadthFirstSearch<Type const*> bfs{{_a}}; bfs.run([&](auto _type, auto&& _addChild) { if (*typeWithoutPointer(_b) == *typeWithoutPointer(_type)) { foundSame = true; bfs.abort(); } if (auto const* mapType = dynamic_cast<MappingType const*>(_type)) _addChild(mapType->valueType()); else if (auto const* arrayType = dynamic_cast<ArrayType const*>(_type)) _addChild(arrayType->baseType()); else if (auto const* structType = dynamic_cast<StructType const*>(_type)) for (auto const& member: structType->nativeMembers(nullptr)) _addChild(member.type); }); return foundSame; } bool SMTEncoder::isSupportedType(Type const& _type) const { return smt::isSupportedType(*underlyingType(&_type)); } Type const* SMTEncoder::typeWithoutPointer(Type const* _type) { if (auto refType = dynamic_cast<ReferenceType const*>(_type)) return TypeProvider::withLocationIfReference(refType->location(), _type); return _type; } void SMTEncoder::mergeVariables(smtutil::Expression const& _condition, VariableIndices const& _indicesEndTrue, VariableIndices const& _indicesEndFalse) { for (auto const& entry: _indicesEndTrue) { VariableDeclaration const* var = entry.first; auto trueIndex = entry.second; if (_indicesEndFalse.count(var) && _indicesEndFalse.at(var) != trueIndex) { m_context.addAssertion(m_context.newValue(*var) == smtutil::Expression::ite( _condition, valueAtIndex(*var, trueIndex), valueAtIndex(*var, _indicesEndFalse.at(var))) ); } } } smtutil::Expression SMTEncoder::currentValue(VariableDeclaration const& _decl) const { solAssert(m_context.knownVariable(_decl), ""); return m_context.variable(_decl)->currentValue(); } smtutil::Expression SMTEncoder::valueAtIndex(VariableDeclaration const& _decl, unsigned _index) const { solAssert(m_context.knownVariable(_decl), ""); return m_context.variable(_decl)->valueAtIndex(_index); } bool SMTEncoder::createVariable(VariableDeclaration const& _varDecl) { if (m_context.knownVariable(_varDecl)) return true; bool abstract = m_context.createVariable(_varDecl); if (abstract) { m_unsupportedErrors.warning( 8115_error, _varDecl.location(), "Assertion checker does not yet support the type of this variable." ); return false; } return true; } smtutil::Expression SMTEncoder::expr(Expression const& _e, Type const* _targetType) { if (!m_context.knownExpression(_e)) { m_unsupportedErrors.warning(6031_error, _e.location(), "Internal error: Expression undefined for SMT solver." ); createExpr(_e); } return m_context.expression(_e)->currentValue(underlyingType(_targetType)); } void SMTEncoder::createExpr(Expression const& _e) { bool abstract = m_context.createExpression(_e); if (abstract) m_unsupportedErrors.warning( 8364_error, _e.location(), "Assertion checker does not yet implement type " + _e.annotation().type->toString() ); } void SMTEncoder::defineExpr(Expression const& _e, smtutil::Expression _value) { auto type = _e.annotation().type; createExpr(_e); solAssert(_value.sort->kind != smtutil::Kind::Function, "Equality operator applied to type that is not fully supported"); if (!smt::isInaccessibleDynamic(*type)) m_context.addAssertion(expr(_e) == _value); if (m_checked && smt::isNumber(*type)) m_context.addAssertion(smtutil::Expression::implies( currentPathConditions(), smt::symbolicUnknownConstraints(expr(_e), type) )); } void SMTEncoder::defineExpr(Expression const& _e, std::vector<std::optional<smtutil::Expression>> const& _values) { if (_values.size() == 1 && _values.front()) { defineExpr(_e, *_values.front()); return; } auto const& symbTuple = std::dynamic_pointer_cast<smt::SymbolicTupleVariable>(m_context.expression(_e)); solAssert(symbTuple, ""); symbTuple->increaseIndex(); auto const& symbComponents = symbTuple->components(); solAssert(symbComponents.size() == _values.size(), ""); auto tupleType = dynamic_cast<TupleType const*>(_e.annotation().type); solAssert(tupleType, ""); solAssert(tupleType->components().size() == symbComponents.size(), ""); for (unsigned i = 0; i < symbComponents.size(); ++i) if (_values[i] && !smt::isInaccessibleDynamic(*tupleType->components()[i])) m_context.addAssertion(symbTuple->component(i) == *_values[i]); } void SMTEncoder::popPathCondition() { solAssert(m_pathConditions.size() > 0, "Cannot pop path condition, empty."); m_pathConditions.pop_back(); } void SMTEncoder::pushPathCondition(smtutil::Expression const& _e) { m_pathConditions.push_back(currentPathConditions() && _e); } void SMTEncoder::setPathCondition(smtutil::Expression const& _e) { if (m_pathConditions.empty()) m_pathConditions.push_back(_e); else m_pathConditions.back() = _e; } smtutil::Expression SMTEncoder::currentPathConditions() { if (m_pathConditions.empty()) return smtutil::Expression(true); return m_pathConditions.back(); } SecondarySourceLocation SMTEncoder::callStackMessage(std::vector<CallStackEntry> const& _callStack) { SecondarySourceLocation callStackLocation; solAssert(!_callStack.empty(), ""); callStackLocation.append("Callstack:", SourceLocation()); for (auto const& call: _callStack | ranges::views::reverse) if (call.second) callStackLocation.append("", call.second->location()); return callStackLocation; } std::pair<CallableDeclaration const*, ASTNode const*> SMTEncoder::popCallStack() { solAssert(!m_callStack.empty(), ""); auto lastCalled = m_callStack.back(); m_callStack.pop_back(); return lastCalled; } void SMTEncoder::pushCallStack(CallStackEntry _entry) { m_callStack.push_back(_entry); } void SMTEncoder::addPathImpliedExpression(smtutil::Expression const& _e) { m_context.addAssertion(smtutil::Expression::implies(currentPathConditions(), _e)); } bool SMTEncoder::isRootFunction() { return m_callStack.size() == 1; } bool SMTEncoder::visitedFunction(FunctionDefinition const* _funDef) { for (auto const& call: m_callStack) if (call.first == _funDef) return true; return false; } ContractDefinition const* SMTEncoder::currentScopeContract() { for (auto&& f: m_callStack | ranges::views::reverse | ranges::views::keys) if (auto fun = dynamic_cast<FunctionDefinition const*>(f)) return fun->annotation().contract; return nullptr; } SMTEncoder::VariableIndices SMTEncoder::copyVariableIndices() { VariableIndices indices; for (auto const& var: m_context.variables()) indices.emplace(var.first, var.second->index()); return indices; } void SMTEncoder::resetVariableIndices(VariableIndices const& _indices) { for (auto const& var: _indices) m_context.variable(*var.first)->setIndex(var.second); } void SMTEncoder::clearIndices(ContractDefinition const* _contract, FunctionDefinition const* _function) { solAssert(_contract, ""); for (auto var: stateVariablesIncludingInheritedAndPrivate(*_contract)) m_context.variable(*var)->resetIndex(); if (_function) { for (auto const& var: _function->parameters() + _function->returnParameters()) m_context.variable(*var)->resetIndex(); for (auto const& var: localVariablesIncludingModifiers(*_function, _contract)) m_context.variable(*var)->resetIndex(); } state().reset(); } Expression const* SMTEncoder::leftmostBase(IndexAccess const& _indexAccess) { Expression const* base = &_indexAccess.baseExpression(); while (auto access = dynamic_cast<IndexAccess const*>(base)) base = &access->baseExpression(); return base; } Type const* SMTEncoder::keyType(Type const* _type) { if (auto const* mappingType = dynamic_cast<MappingType const*>(_type)) return mappingType->keyType(); if ( dynamic_cast<ArrayType const*>(_type) || dynamic_cast<ArraySliceType const*>(_type) ) return TypeProvider::uint256(); else solAssert(false, ""); } Expression const* SMTEncoder::innermostTuple(Expression const& _expr) { auto const* tuple = dynamic_cast<TupleExpression const*>(&_expr); if (!tuple || tuple->isInlineArray()) return &_expr; Expression const* expr = tuple; while (tuple && !tuple->isInlineArray() && tuple->components().size() == 1) { expr = tuple->components().front().get(); tuple = dynamic_cast<TupleExpression const*>(expr); } solAssert(expr, ""); return expr; } Type const* SMTEncoder::underlyingType(Type const* _type) { if (auto userType = dynamic_cast<UserDefinedValueType const*>(_type)) _type = &userType->underlyingType(); return _type; } TypePointers SMTEncoder::replaceUserTypes(TypePointers const& _types) { return applyMap(_types, [](auto _type) { if (auto userType = dynamic_cast<UserDefinedValueType const*>(_type)) return &userType->underlyingType(); return _type; }); } std::pair<Expression const*, FunctionCallOptions const*> SMTEncoder::functionCallExpression(FunctionCall const& _funCall) { Expression const* callExpr = &_funCall.expression(); auto const* callOptions = dynamic_cast<FunctionCallOptions const*>(callExpr); if (callOptions) callExpr = &callOptions->expression(); return {callExpr, callOptions}; } Expression const* SMTEncoder::cleanExpression(Expression const& _expr) { auto const* expr = &_expr; if (auto const* tuple = dynamic_cast<TupleExpression const*>(expr)) return cleanExpression(*innermostTuple(*tuple)); if (auto const* functionCall = dynamic_cast<FunctionCall const*>(expr)) if (*functionCall->annotation().kind == FunctionCallKind::TypeConversion) { auto typeType = dynamic_cast<TypeType const*>(functionCall->expression().annotation().type); solAssert(typeType, ""); if (auto const* arrayType = dynamic_cast<ArrayType const*>(typeType->actualType())) if (arrayType->isByteArrayOrString()) { // this is a cast to `bytes` solAssert(functionCall->arguments().size() == 1, ""); Expression const& arg = *functionCall->arguments()[0]; if ( auto const* argArrayType = dynamic_cast<ArrayType const*>(arg.annotation().type); argArrayType && argArrayType->isByteArrayOrString() ) return cleanExpression(arg); } } solAssert(expr, ""); return expr; } std::set<VariableDeclaration const*> SMTEncoder::touchedVariables(ASTNode const& _node) { std::vector<CallableDeclaration const*> callStack; for (auto const& call: m_callStack) callStack.push_back(call.first); return m_variableUsage.touchedVariables(_node, callStack); } Declaration const* SMTEncoder::expressionToDeclaration(Expression const& _expr) const { if (auto const* identifier = dynamic_cast<Identifier const*>(&_expr)) return identifier->annotation().referencedDeclaration; if (auto const* outerMemberAccess = dynamic_cast<MemberAccess const*>(&_expr)) return outerMemberAccess->annotation().referencedDeclaration; return nullptr; } VariableDeclaration const* SMTEncoder::identifierToVariable(Expression const& _expr) const { // We do not use `expressionToDeclaration` here because we are not interested in // struct.field, for example. if (auto const* identifier = dynamic_cast<Identifier const*>(&_expr)) if (auto const* varDecl = dynamic_cast<VariableDeclaration const*>(identifier->annotation().referencedDeclaration)) { solAssert(m_context.knownVariable(*varDecl), ""); return varDecl; } // But we are interested in "contract.var", because that is the same as just "var". if (auto const* memberAccess = dynamic_cast<MemberAccess const*>(&_expr)) if (dynamic_cast<ContractDefinition const*>(expressionToDeclaration( *cleanExpression(memberAccess->expression()) ))) if (auto const* varDecl = dynamic_cast<VariableDeclaration const*>(memberAccess->annotation().referencedDeclaration)) { solAssert(m_context.knownVariable(*varDecl), ""); return varDecl; } return nullptr; } MemberAccess const* SMTEncoder::isEmptyPush(Expression const& _expr) const { if ( auto const* funCall = dynamic_cast<FunctionCall const*>(&_expr); funCall && funCall->arguments().empty() ) { auto const& funType = dynamic_cast<FunctionType const&>(*funCall->expression().annotation().type); if (funType.kind() == FunctionType::Kind::ArrayPush) return &dynamic_cast<MemberAccess const&>(funCall->expression()); } return nullptr; } smtutil::Expression SMTEncoder::contractAddressValue(FunctionCall const& _f) { FunctionType const& funType = dynamic_cast<FunctionType const&>(*_f.expression().annotation().type); if (funType.kind() == FunctionType::Kind::Internal) return state().thisAddress(); auto [funExpr, funOptions] = functionCallExpression(_f); if (MemberAccess const* callBase = dynamic_cast<MemberAccess const*>(funExpr)) return expr(callBase->expression()); solAssert(false, "Unreachable!"); } VariableDeclaration const* SMTEncoder::publicGetter(Expression const& _expr) const { if (auto memberAccess = dynamic_cast<MemberAccess const*>(&_expr)) if (auto variableDeclaration = dynamic_cast<VariableDeclaration const*>(memberAccess->annotation().referencedDeclaration)) return variableDeclaration->isStateVariable() ? variableDeclaration : nullptr; return nullptr; } bool SMTEncoder::isExternalCallToThis(Expression const* _expr) { auto memberAccess = dynamic_cast<MemberAccess const*>(_expr); if (!memberAccess) return false; auto identifier = dynamic_cast<Identifier const*>(&memberAccess->expression()); return identifier && identifier->name() == "this" && identifier->annotation().referencedDeclaration && dynamic_cast<MagicVariableDeclaration const*>(identifier->annotation().referencedDeclaration) ; } std::string SMTEncoder::extraComment() { std::string extra; if (m_arrayAssignmentHappened) extra += "\nNote that array aliasing is not supported," " therefore all mapping information is erased after" " a mapping local variable/parameter is assigned.\n" "You can re-introduce information using require()."; return extra; } FunctionDefinition const* SMTEncoder::functionCallToDefinition( FunctionCall const& _funCall, ContractDefinition const* _scopeContract, ContractDefinition const* _contextContract ) { if (*_funCall.annotation().kind != FunctionCallKind::FunctionCall) return {}; auto [calledExpr, callOptions] = functionCallExpression(_funCall); if (TupleExpression const* fun = dynamic_cast<TupleExpression const*>(calledExpr)) { solAssert(fun->components().size() == 1, ""); calledExpr = innermostTuple(*calledExpr); } auto resolveVirtual = [&](auto const* _ref) -> FunctionDefinition const* { VirtualLookup lookup = *_ref->annotation().requiredLookup; solAssert(_contextContract || lookup == VirtualLookup::Static, "No contract context provided for function lookup resolution!"); auto funDef = dynamic_cast<FunctionDefinition const*>(_ref->annotation().referencedDeclaration); if (!funDef) return funDef; switch (lookup) { case VirtualLookup::Virtual: return &(funDef->resolveVirtual(*_contextContract)); case VirtualLookup::Super: { solAssert(_scopeContract, ""); auto super = _scopeContract->superContract(*_contextContract); solAssert(super, "Super contract not available."); return &funDef->resolveVirtual(*_contextContract, super); } case VirtualLookup::Static: return funDef; } solAssert(false, ""); }; if (Identifier const* fun = dynamic_cast<Identifier const*>(calledExpr)) return resolveVirtual(fun); else if (MemberAccess const* fun = dynamic_cast<MemberAccess const*>(calledExpr)) return resolveVirtual(fun); return {}; } std::vector<VariableDeclaration const*> SMTEncoder::stateVariablesIncludingInheritedAndPrivate(ContractDefinition const& _contract) { return fold( _contract.annotation().linearizedBaseContracts, std::vector<VariableDeclaration const*>{}, [](auto&& _acc, auto _contract) { return _acc + _contract->stateVariables(); } ); } std::vector<VariableDeclaration const*> SMTEncoder::stateVariablesIncludingInheritedAndPrivate(FunctionDefinition const& _function) { if (auto contract = dynamic_cast<ContractDefinition const*>(_function.scope())) return stateVariablesIncludingInheritedAndPrivate(*contract); return {}; } std::vector<VariableDeclaration const*> SMTEncoder::localVariablesIncludingModifiers(FunctionDefinition const& _function, ContractDefinition const* _contract) { return _function.localVariables() + tryCatchVariables(_function) + modifiersVariables(_function, _contract); } std::vector<VariableDeclaration const*> SMTEncoder::tryCatchVariables(FunctionDefinition const& _function) { struct TryCatchVarsVisitor : public ASTConstVisitor { bool visit(TryCatchClause const& _catchClause) override { if (_catchClause.parameters()) { auto const& params = _catchClause.parameters()->parameters(); for (auto param: params) vars.push_back(param.get()); } return true; } std::vector<VariableDeclaration const*> vars; } tryCatchVarsVisitor; _function.accept(tryCatchVarsVisitor); return tryCatchVarsVisitor.vars; } std::vector<VariableDeclaration const*> SMTEncoder::modifiersVariables(FunctionDefinition const& _function, ContractDefinition const* _contract) { struct BlockVars: ASTConstVisitor { BlockVars(Block const& _block) { _block.accept(*this); } void endVisit(VariableDeclaration const& _var) { vars.push_back(&_var); } std::vector<VariableDeclaration const*> vars; }; std::vector<VariableDeclaration const*> vars; std::set<ModifierDefinition const*> visited; for (auto invok: _function.modifiers()) { if (!invok) continue; auto const* modifier = resolveModifierInvocation(*invok, _contract); if (!modifier || visited.count(modifier)) continue; visited.insert(modifier); if (modifier->isImplemented()) { vars += applyMap(modifier->parameters(), [](auto _var) { return _var.get(); }); vars += BlockVars(modifier->body()).vars; } } return vars; } ModifierDefinition const* SMTEncoder::resolveModifierInvocation(ModifierInvocation const& _invocation, ContractDefinition const* _contract) { auto const* modifier = dynamic_cast<ModifierDefinition const*>(_invocation.name().annotation().referencedDeclaration); if (modifier) { VirtualLookup lookup = *_invocation.name().annotation().requiredLookup; solAssert(lookup == VirtualLookup::Virtual || lookup == VirtualLookup::Static, ""); solAssert(_contract || lookup == VirtualLookup::Static, "No contract context provided for modifier lookup resolution!"); if (lookup == VirtualLookup::Virtual) modifier = &modifier->resolveVirtual(*_contract); } return modifier; } std::set<FunctionDefinition const*, ASTNode::CompareByID> const& SMTEncoder::contractFunctions(ContractDefinition const& _contract) { if (!m_contractFunctions.count(&_contract)) { auto const& functions = _contract.definedFunctions(); std::set<FunctionDefinition const*, ASTNode::CompareByID> resolvedFunctions(begin(functions), end(functions)); for (auto const* base: _contract.annotation().linearizedBaseContracts) { if (base == &_contract) continue; for (auto const* baseFunction: base->definedFunctions()) { if (baseFunction->isConstructor()) // We don't want to include constructors of parent contracts continue; bool overridden = false; for (auto const* function: resolvedFunctions) if ( function->name() == baseFunction->name() && function->kind() == baseFunction->kind() && FunctionType(*function).asExternallyCallableFunction(false)-> hasEqualParameterTypes(*FunctionType(*baseFunction).asExternallyCallableFunction(false)) ) { overridden = true; break; } if (!overridden) resolvedFunctions.insert(baseFunction); } } m_contractFunctions.emplace(&_contract, std::move(resolvedFunctions)); } return m_contractFunctions.at(&_contract); } std::set<FunctionDefinition const*, ASTNode::CompareByID> const& SMTEncoder::contractFunctionsWithoutVirtual(ContractDefinition const& _contract) { if (!m_contractFunctionsWithoutVirtual.count(&_contract)) { auto allFunctions = contractFunctions(_contract); for (auto const* base: _contract.annotation().linearizedBaseContracts) for (auto const* baseFun: base->definedFunctions()) allFunctions.insert(baseFun); m_contractFunctionsWithoutVirtual.emplace(&_contract, std::move(allFunctions)); } return m_contractFunctionsWithoutVirtual.at(&_contract); } std::map<ContractDefinition const*, std::vector<ASTPointer<frontend::Expression>>> SMTEncoder::baseArguments(ContractDefinition const& _contract) { std::map<ContractDefinition const*, std::vector<ASTPointer<Expression>>> baseArgs; for (auto contract: _contract.annotation().linearizedBaseContracts) { /// Collect base contracts and potential constructor arguments. for (auto specifier: contract->baseContracts()) { solAssert(specifier, ""); auto const& base = dynamic_cast<ContractDefinition const&>(*specifier->name().annotation().referencedDeclaration); if (auto args = specifier->arguments()) baseArgs[&base] = *args; } /// Collect base constructor arguments given as constructor modifiers. if (auto constructor = contract->constructor()) for (auto mod: constructor->modifiers()) { auto decl = mod->name().annotation().referencedDeclaration; if (auto base = dynamic_cast<ContractDefinition const*>(decl)) { solAssert(!baseArgs.count(base), ""); if (auto args = mod->arguments()) baseArgs[base] = *args; } } } return baseArgs; } RationalNumberType const* SMTEncoder::isConstant(Expression const& _expr) { if (auto type = dynamic_cast<RationalNumberType const*>(_expr.annotation().type)) return type; // _expr may not be constant evaluable. // In that case we ignore any warnings emitted by the constant evaluator, // as it will return nullptr in case of failure. ErrorList l; ErrorReporter e(l); if (auto t = ConstantEvaluator::evaluate(e, _expr)) return TypeProvider::rationalNumber(t->value); return nullptr; } std::set<FunctionCall const*, ASTCompareByID<FunctionCall>> SMTEncoder::collectABICalls(ASTNode const* _node) { struct ABIFunctions: public ASTConstVisitor { ABIFunctions(ASTNode const* _node) { _node->accept(*this); } void endVisit(FunctionCall const& _funCall) { if (*_funCall.annotation().kind == FunctionCallKind::FunctionCall) switch (dynamic_cast<FunctionType const&>(*_funCall.expression().annotation().type).kind()) { case FunctionType::Kind::ABIEncode: case FunctionType::Kind::ABIEncodePacked: case FunctionType::Kind::ABIEncodeWithSelector: case FunctionType::Kind::ABIEncodeCall: case FunctionType::Kind::ABIEncodeWithSignature: case FunctionType::Kind::ABIDecode: abiCalls.insert(&_funCall); break; default: {} } } std::set<FunctionCall const*, ASTCompareByID<FunctionCall>> abiCalls; }; return ABIFunctions(_node).abiCalls; } std::set<FunctionCall const*, ASTCompareByID<FunctionCall>> SMTEncoder::collectBytesConcatCalls(ASTNode const* _node) { struct BytesConcatFunctions: public ASTConstVisitor { BytesConcatFunctions(ASTNode const* _node) { _node->accept(*this); } void endVisit(FunctionCall const& _funCall) { if (*_funCall.annotation().kind == FunctionCallKind::FunctionCall) switch (dynamic_cast<FunctionType const&>(*_funCall.expression().annotation().type).kind()) { case FunctionType::Kind::BytesConcat: bytesConcatCalls.insert(&_funCall); break; default: {} } } std::set<FunctionCall const*, ASTCompareByID<FunctionCall>> bytesConcatCalls; }; return BytesConcatFunctions(_node).bytesConcatCalls; } std::set<SourceUnit const*, ASTNode::CompareByID> SMTEncoder::sourceDependencies(SourceUnit const& _source) { std::set<SourceUnit const*, ASTNode::CompareByID> sources; sources.insert(&_source); for (auto const& source: _source.referencedSourceUnits(true)) sources.insert(source); return sources; } void SMTEncoder::createReturnedExpressions(FunctionDefinition const* _funDef, Expression const& _callStackExpr) { if (!_funDef) return; auto const& returnParams = _funDef->returnParameters(); for (auto param: returnParams) createVariable(*param); auto returnValues = applyMap(returnParams, [this](auto const& param) -> std::optional<smtutil::Expression> { solAssert(param && m_context.knownVariable(*param), ""); return currentValue(*param); }); defineExpr(_callStackExpr, returnValues); } std::vector<smtutil::Expression> SMTEncoder::symbolicArguments( std::vector<ASTPointer<VariableDeclaration>> const& _funParameters, std::vector<Expression const*> const& _arguments, std::optional<Expression const*> _boundArgumentCall ) { std::vector<smtutil::Expression> args; unsigned firstParam = 0; if (_boundArgumentCall) { Expression const* calledExpr = innermostTuple(*_boundArgumentCall.value()); auto const& attachedFunction = dynamic_cast<MemberAccess const*>(calledExpr); solAssert(attachedFunction, ""); args.push_back(expr(attachedFunction->expression(), _funParameters.front()->type())); firstParam = 1; } solAssert((_arguments.size() + firstParam) == _funParameters.size(), ""); for (unsigned i = 0; i < _arguments.size(); ++i) args.push_back(expr(*_arguments.at(i), _funParameters.at(i + firstParam)->type())); return args; } smtutil::Expression SMTEncoder::constantExpr(Expression const& _expr, VariableDeclaration const& _var) { if (RationalNumberType const* rationalType = isConstant(_expr)) { if (rationalType->isNegative()) return smtutil::Expression(u2s(rationalType->literalValue(nullptr))); else return smtutil::Expression(rationalType->literalValue(nullptr)); } else { solAssert(_var.value(), ""); _var.value()->accept(*this); return expr(*_var.value(), _expr.annotation().type); } solAssert(false, ""); } void SMTEncoder::collectFreeFunctions(std::set<SourceUnit const*, ASTNode::CompareByID> const& _sources) { for (auto source: _sources) for (auto node: source->nodes()) if (auto function = dynamic_cast<FunctionDefinition const*>(node.get())) m_freeFunctions.insert(function); else if ( auto contract = dynamic_cast<ContractDefinition const*>(node.get()); contract && contract->isLibrary() ) for (auto function: contract->definedFunctions()) // We need to add public library functions too because they can be called // internally by internal library functions that are considered free functions. m_freeFunctions.insert(function); } void SMTEncoder::createFreeConstants(std::set<SourceUnit const*, ASTNode::CompareByID> const& _sources) { for (auto source: _sources) for (auto node: source->nodes()) if (auto var = dynamic_cast<VariableDeclaration const*>(node.get())) createVariable(*var); else if ( auto contract = dynamic_cast<ContractDefinition const*>(node.get()); contract && contract->isLibrary() ) for (auto var: contract->stateVariables()) { solAssert(var->isConstant(), ""); createVariable(*var); } } smt::SymbolicState& SMTEncoder::state() { return m_context.state(); } smtutil::Expression SMTEncoder::createSelectExpressionForFunction( smtutil::Expression symbFunction, std::vector<frontend::ASTPointer<frontend::Expression const>> const& args, frontend::TypePointers const& inTypes, unsigned long argsActualLength ) { solAssert(argsActualLength <= args.size() && inTypes.size() == argsActualLength); if (inTypes.size() == 1) { smtutil::Expression arg = expr(*args.at(0), inTypes.at(0)); return smtutil::Expression::select(symbFunction, arg); } std::vector<smtutil::Expression> symbArgs; for (unsigned i = 0; i < argsActualLength; ++i) if (args.at(i)) symbArgs.emplace_back(expr(*args.at(i), inTypes.at(i))); auto inputSort = dynamic_cast<smtutil::ArraySort&>(*symbFunction.sort).domain; smtutil::Expression arg = smtutil::Expression::tuple_constructor( smtutil::Expression(std::make_shared<smtutil::SortSort>(inputSort), ""), symbArgs ); return smtutil::Expression::select(symbFunction, arg); }
106,819
C++
.cpp
2,933
33.661439
167
0.737541
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
3,168
ExpressionFormatter.cpp
ethereum_solidity/libsolidity/formal/ExpressionFormatter.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libsolidity/formal/ExpressionFormatter.h> #include <libsolidity/formal/SymbolicTypes.h> #include <libsolutil/Algorithms.h> #include <libsolutil/CommonData.h> #include <boost/algorithm/string.hpp> #include <map> #include <vector> #include <string> using boost::algorithm::starts_with; using namespace solidity; using namespace solidity::util; using namespace solidity::smtutil; using namespace solidity::frontend::smt; namespace solidity::frontend::smt { namespace { std::string formatDatatypeAccessor(smtutil::Expression const& _expr, std::vector<std::string> const& _args) { auto const& op = _expr.name; // This is the most complicated part of the translation. // Datatype accessor means access to a field of a datatype. // In our encoding, datatypes are used to encode: // - arrays/mappings as the tuple (array, length) // - structs as the tuple (<member1>, ..., <memberK>) // - hash and signature functions as the tuple (keccak256, sha256, ripemd160, ecrecover), // where each element is an array emulating an UF // - abi.* functions as the tuple (<abiCall1>, ..., <abiCallK>). if (op == "dt_accessor_keccak256") return "keccak256"; if (op == "dt_accessor_sha256") return "sha256"; if (op == "dt_accessor_ripemd160") return "ripemd160"; if (op == "dt_accessor_ecrecover") return "ecrecover"; std::string accessorStr = "accessor_"; // Struct members have suffix "accessor_<memberName>". std::string type = op.substr(op.rfind(accessorStr) + accessorStr.size()); solAssert(_expr.arguments.size() == 1, ""); if (type == "length") return _args.at(0) + ".length"; if (type == "array") return _args.at(0); if ( starts_with(type, "block") || starts_with(type, "msg") || starts_with(type, "tx") || starts_with(type, "abi") ) return type; if (starts_with(type, "t_function_abi")) return type; return _args.at(0) + "." + type; } std::string formatGenericOp(smtutil::Expression const& _expr, std::vector<std::string> const& _args) { return _expr.name + "(" + boost::algorithm::join(_args, ", ") + ")"; } std::string formatInfixOp(std::string const& _op, std::vector<std::string> const& _args) { return "(" + boost::algorithm::join(_args, " " + _op + " ") + ")"; } std::string formatArrayOp(smtutil::Expression const& _expr, std::vector<std::string> const& _args) { if (_expr.name == "select") { auto const& a0 = _args.at(0); static std::set<std::string> const ufs{"keccak256", "sha256", "ripemd160", "ecrecover"}; if (ufs.count(a0) || starts_with(a0, "t_function_abi")) return _args.at(0) + "(" + _args.at(1) + ")"; return _args.at(0) + "[" + _args.at(1) + "]"; } if (_expr.name == "store") return "(" + _args.at(0) + "[" + _args.at(1) + "] := " + _args.at(2) + ")"; return formatGenericOp(_expr, _args); } std::string formatUnaryOp(smtutil::Expression const& _expr, std::vector<std::string> const& _args) { if (_expr.name == "not") return "!" + _args.at(0); if (_expr.name == "-") return "-" + _args.at(0); // Other operators such as exists may end up here. return formatGenericOp(_expr, _args); } } smtutil::Expression substitute(smtutil::Expression _from, std::map<std::string, std::string> const& _subst) { // TODO For now we ignore nested quantifier expressions, // but we should support them in the future. if (_from.name == "forall" || _from.name == "exists") return smtutil::Expression(true); if (_subst.count(_from.name)) _from.name = _subst.at(_from.name); for (auto& arg: _from.arguments) arg = substitute(arg, _subst); return _from; } std::string toSolidityStr(smtutil::Expression const& _expr) { auto const& op = _expr.name; auto const& args = _expr.arguments; auto strArgs = util::applyMap(args, [](auto const& _arg) { return toSolidityStr(_arg); }); // Constant or variable. if (args.empty()) return op; if (starts_with(op, "dt_accessor")) return formatDatatypeAccessor(_expr, strArgs); // Infix operators with format replacements. static std::map<std::string, std::string> const infixOps{ {"and", "&&"}, {"or", "||"}, {"implies", "=>"}, {"=", "="}, {">", ">"}, {">=", ">="}, {"<", "<"}, {"<=", "<="}, {"+", "+"}, {"-", "-"}, {"*", "*"}, {"/", "/"}, {"div", "/"}, {"mod", "%"} }; // Some of these (and, or, +, *) may have >= 2 arguments from z3. if (infixOps.count(op) && args.size() >= 2) return formatInfixOp(infixOps.at(op), strArgs); static std::set<std::string> const arrayOps{"select", "store", "const_array"}; if (arrayOps.count(op)) return formatArrayOp(_expr, strArgs); if (args.size() == 1) return formatUnaryOp(_expr, strArgs); // Other operators such as bv2int, int2bv may end up here. return op + "(" + boost::algorithm::join(strArgs, ", ") + ")"; } namespace { bool fillArray(smtutil::Expression const& _expr, std::vector<std::string>& _array, ArrayType const& _type) { // Base case if (_expr.name == "const_array") { auto length = _array.size(); std::optional<std::string> elemStr = expressionToString(_expr.arguments.at(1), _type.baseType()); if (!elemStr) return false; _array.clear(); _array.resize(length, *elemStr); return true; } // Recursive case. if (_expr.name == "store") { if (!fillArray(_expr.arguments.at(0), _array, _type)) return false; std::optional<std::string> indexStr = expressionToString(_expr.arguments.at(1), TypeProvider::uint256()); if (!indexStr) return false; // Sometimes the solver assigns huge lengths that are not related, // we should catch and ignore those. unsigned long index; try { index = stoul(*indexStr); } catch (std::out_of_range const&) { return true; } catch (std::invalid_argument const&) { return true; } std::optional<std::string> elemStr = expressionToString(_expr.arguments.at(2), _type.baseType()); if (!elemStr) return false; if (index < _array.size()) _array.at(index) = *elemStr; return true; } // Special base case, not supported yet. if (_expr.name.rfind("(_ as-array") == 0) { // Z3 expression representing reinterpretation of a different term as an array return false; } solAssert(false); } } std::optional<std::string> expressionToString(smtutil::Expression const& _expr, frontend::Type const* _type) { if (smt::isNumber(*_type)) { solAssert(_expr.sort->kind == Kind::Int); solAssert(_expr.arguments.empty() || _expr.name == "-"); if (_expr.name == "-") { solAssert(_expr.arguments.size() == 1); smtutil::Expression const& val = _expr.arguments[0]; solAssert(val.sort->kind == Kind::Int && val.arguments.empty()); return "(- " + val.name + ")"; } if ( _type->category() == frontend::Type::Category::Address || _type->category() == frontend::Type::Category::FixedBytes ) { try { if (_expr.name == "0") return "0x0"; // For some reason the code below returns "0x" for "0". return util::toHex(toCompactBigEndian(bigint(_expr.name)), util::HexPrefix::Add, util::HexCase::Lower); } catch (std::out_of_range const&) { } catch (std::invalid_argument const&) { } } return _expr.name; } if (smt::isBool(*_type)) { solAssert(_expr.sort->kind == Kind::Bool); solAssert(_expr.arguments.empty()); solAssert(_expr.name == "true" || _expr.name == "false"); return _expr.name; } if (smt::isFunction(*_type)) { solAssert(_expr.arguments.empty()); return _expr.name; } if (smt::isArray(*_type)) { auto const& arrayType = dynamic_cast<ArrayType const&>(*_type); if (_expr.name != "tuple_constructor") return {}; auto const& tupleSort = dynamic_cast<TupleSort const&>(*_expr.sort); solAssert(tupleSort.components.size() == 2); unsigned long length; try { length = stoul(_expr.arguments.at(1).name); } catch(std::out_of_range const&) { return {}; } catch(std::invalid_argument const&) { return {}; } // Limit this counterexample size to 1k. // Some OSs give you "unlimited" memory through swap and other virtual memory, // so purely relying on bad_alloc being thrown is not a good idea. // In that case, the array allocation might cause OOM and the program is killed. if (length >= 1024) return {}; try { std::vector<std::string> array(length); if (!fillArray(_expr.arguments.at(0), array, arrayType)) return {}; return "[" + boost::algorithm::join(array, ", ") + "]"; } catch (std::bad_alloc const&) { // Solver gave a concrete array but length is too large. } } if (smt::isNonRecursiveStruct(*_type)) { auto const& structType = dynamic_cast<StructType const&>(*_type); solAssert(_expr.name == "tuple_constructor"); auto const& tupleSort = dynamic_cast<TupleSort const&>(*_expr.sort); auto members = structType.structDefinition().members(); solAssert(tupleSort.components.size() == members.size()); solAssert(_expr.arguments.size() == members.size()); std::vector<std::string> elements; for (unsigned i = 0; i < members.size(); ++i) { std::optional<std::string> elementStr = expressionToString(_expr.arguments.at(i), members[i]->type()); elements.push_back(members[i]->name() + (elementStr.has_value() ? ": " + elementStr.value() : "")); } return "{" + boost::algorithm::join(elements, ", ") + "}"; } return {}; } std::vector<std::optional<std::string>> formatExpressions( std::vector<smtutil::Expression> const& _exprs, std::vector<frontend::Type const*> const& _types ) { solAssert(_exprs.size() == _types.size()); std::vector<std::optional<std::string>> strExprs; for (unsigned i = 0; i < _exprs.size(); ++i) strExprs.push_back(expressionToString(_exprs.at(i), _types.at(i))); return strExprs; } }
10,358
C++
.cpp
319
29.855799
108
0.669902
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,169
ModelCheckerSettings.cpp
ethereum_solidity/libsolidity/formal/ModelCheckerSettings.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libsolidity/formal/ModelCheckerSettings.h> #include <optional> #include <range/v3/view.hpp> using namespace solidity; using namespace solidity::frontend; std::map<std::string, InvariantType> const ModelCheckerInvariants::validInvariants{ {"contract", InvariantType::Contract}, {"reentrancy", InvariantType::Reentrancy} }; std::optional<ModelCheckerInvariants> ModelCheckerInvariants::fromString(std::string const& _invs) { std::set<InvariantType> chosenInvs; if (_invs == "default") { // The default is that no invariants are reported. } else if (_invs == "all") for (auto&& v: validInvariants | ranges::views::values) chosenInvs.insert(v); else for (auto&& t: _invs | ranges::views::split(',') | ranges::to<std::vector<std::string>>()) { if (!validInvariants.count(t)) return {}; chosenInvs.insert(validInvariants.at(t)); } return ModelCheckerInvariants{chosenInvs}; } bool ModelCheckerInvariants::setFromString(std::string const& _inv) { if (!validInvariants.count(_inv)) return false; invariants.insert(validInvariants.at(_inv)); return true; } using TargetType = VerificationTargetType; std::map<std::string, TargetType> const ModelCheckerTargets::targetStrings{ {"constantCondition", TargetType::ConstantCondition}, {"underflow", TargetType::Underflow}, {"overflow", TargetType::Overflow}, {"divByZero", TargetType::DivByZero}, {"balance", TargetType::Balance}, {"assert", TargetType::Assert}, {"popEmptyArray", TargetType::PopEmptyArray}, {"outOfBounds", TargetType::OutOfBounds} }; std::map<TargetType, std::string> const ModelCheckerTargets::targetTypeToString{ {TargetType::ConstantCondition, "Constant condition"}, {TargetType::Underflow, "Underflow"}, {TargetType::Overflow, "Overflow"}, {TargetType::DivByZero, "Division by zero"}, {TargetType::Balance, "Insufficient balance"}, {TargetType::Assert, "Assertion failed"}, {TargetType::PopEmptyArray, "Empty array pop"}, {TargetType::OutOfBounds, "Out of bounds access"} }; std::optional<ModelCheckerTargets> ModelCheckerTargets::fromString(std::string const& _targets) { std::set<TargetType> chosenTargets; if (_targets == "default" || _targets == "all") { bool all = _targets == "all"; for (auto&& v: targetStrings | ranges::views::values) { if (!all && (v == TargetType::Underflow || v == TargetType::Overflow)) continue; chosenTargets.insert(v); } } else for (auto&& t: _targets | ranges::views::split(',') | ranges::to<std::vector<std::string>>()) { if (!targetStrings.count(t)) return {}; chosenTargets.insert(targetStrings.at(t)); } return ModelCheckerTargets{chosenTargets}; } bool ModelCheckerTargets::setFromString(std::string const& _target) { if (!targetStrings.count(_target)) return false; targets.insert(targetStrings.at(_target)); return true; } std::optional<ModelCheckerContracts> ModelCheckerContracts::fromString(std::string const& _contracts) { std::map<std::string, std::set<std::string>> chosen; if (_contracts == "default") return ModelCheckerContracts::Default(); for (auto&& sourceContract: _contracts | ranges::views::split(',') | ranges::to<std::vector<std::string>>()) { auto&& names = sourceContract | ranges::views::split(':') | ranges::to<std::vector<std::string>>(); if (names.size() != 2 || names.at(0).empty() || names.at(1).empty()) return {}; chosen[names.at(0)].insert(names.at(1)); } return ModelCheckerContracts{chosen}; } std::optional<ModelCheckerExtCalls> ModelCheckerExtCalls::fromString(std::string const& _mode) { if (_mode == "untrusted") return ModelCheckerExtCalls{Mode::UNTRUSTED}; if (_mode == "trusted") return ModelCheckerExtCalls{Mode::TRUSTED}; return {}; }
4,406
C++
.cpp
121
34.157025
109
0.742147
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
3,171
BMC.cpp
ethereum_solidity/libsolidity/formal/BMC.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libsolidity/formal/BMC.h> #include <libsolidity/formal/Cvc5SMTLib2Interface.h> #include <libsolidity/formal/SymbolicTypes.h> #include <libsolidity/formal/Z3SMTLib2Interface.h> #include <libsmtutil/SMTLib2Interface.h> #include <libsmtutil/SMTPortfolio.h> #include <liblangutil/CharStream.h> #include <liblangutil/CharStreamProvider.h> #include <utility> using namespace solidity; using namespace solidity::util; using namespace solidity::langutil; using namespace solidity::frontend; using namespace solidity::frontend::smt; using namespace solidity::smtutil; BMC::BMC( smt::EncodingContext& _context, UniqueErrorReporter& _errorReporter, UniqueErrorReporter& _unsupportedErrorReporter, ErrorReporter& _provedSafeReporter, std::map<h256, std::string> const& _smtlib2Responses, ReadCallback::Callback const& _smtCallback, ModelCheckerSettings _settings, CharStreamProvider const& _charStreamProvider ): SMTEncoder(_context, _settings, _errorReporter, _unsupportedErrorReporter, _provedSafeReporter, _charStreamProvider) { solAssert(!_settings.printQuery || _settings.solvers == SMTSolverChoice::SMTLIB2(), "Only SMTLib2 solver can be enabled to print queries"); std::vector<std::unique_ptr<BMCSolverInterface>> solvers; if (_settings.solvers.smtlib2) solvers.emplace_back(std::make_unique<SMTLib2Interface>(_smtlib2Responses, _smtCallback, _settings.timeout)); if (_settings.solvers.cvc5) solvers.emplace_back(std::make_unique<Cvc5SMTLib2Interface>(_smtCallback, _settings.timeout)); if (_settings.solvers.z3 ) solvers.emplace_back(std::make_unique<Z3SMTLib2Interface>(_smtCallback, _settings.timeout)); m_interface = std::make_unique<SMTPortfolio>(std::move(solvers), _settings.timeout); #if defined (HAVE_Z3) if (m_settings.solvers.z3) if (!_smtlib2Responses.empty()) m_errorReporter.warning( 5622_error, "SMT-LIB2 query responses were given in the auxiliary input, " "but this Solidity binary uses an SMT solver Z3 directly." "These responses will be ignored." "Consider disabling Z3 at compilation time in order to use SMT-LIB2 responses." ); #endif } void BMC::analyze(SourceUnit const& _source, std::map<ASTNode const*, std::set<VerificationTargetType>, smt::EncodingContext::IdCompare> _solvedTargets) { // At this point every enabled solver is available. if (!m_settings.solvers.cvc5 && !m_settings.solvers.smtlib2 && !m_settings.solvers.z3) { m_errorReporter.warning( 7710_error, SourceLocation(), "BMC analysis was not possible since no SMT solver was found and enabled." " The accepted solvers for BMC are cvc5 and z3." ); return; } SMTEncoder::resetSourceAnalysis(); state().prepareForSourceUnit(_source, false); m_solvedTargets = std::move(_solvedTargets); m_context.setSolver(m_interface.get()); m_context.reset(); m_context.setAssertionAccumulation(true); m_variableUsage.setFunctionInlining(shouldInlineFunctionCall); createFreeConstants(sourceDependencies(_source)); m_unprovedAmt = 0; _source.accept(*this); if (m_unprovedAmt > 0 && !m_settings.showUnproved) m_errorReporter.warning( 2788_error, {}, "BMC: " + std::to_string(m_unprovedAmt) + " verification condition(s) could not be proved." + " Enable the model checker option \"show unproved\" to see all of them." + " Consider choosing a specific contract to be verified in order to reduce the solving problems." + " Consider increasing the timeout per query." ); if (!m_settings.showProvedSafe && !m_safeTargets.empty()) { std::size_t provedSafeNum = 0; for (auto&& [_, targets]: m_safeTargets) provedSafeNum += targets.size(); m_errorReporter.info( 6002_error, "BMC: " + std::to_string(provedSafeNum) + " verification condition(s) proved safe!" + " Enable the model checker option \"show proved safe\" to see all of them." ); } else if (m_settings.showProvedSafe) for (auto const& [node, targets]: m_safeTargets) for (auto const& target: targets) m_provedSafeReporter.info( 2961_error, node->location(), "BMC: " + targetDescription(target) + " check is safe!" ); // If this check is true, Z3 and cvc5 are not available // and the query answers were not provided, since SMTPortfolio // guarantees that SmtLib2Interface is the first solver, if enabled. if ( !m_interface->unhandledQueries().empty() && m_interface->solvers() == 1 && m_settings.solvers.smtlib2 ) m_errorReporter.warning( 8084_error, SourceLocation(), "BMC analysis was not possible. No SMT solver (Z3 or cvc5) was available." " None of the installed solvers was enabled." ); } bool BMC::shouldInlineFunctionCall( FunctionCall const& _funCall, ContractDefinition const* _scopeContract, ContractDefinition const* _contextContract ) { auto funDef = functionCallToDefinition(_funCall, _scopeContract, _contextContract); if (!funDef || !funDef->isImplemented()) return false; FunctionType const& funType = dynamic_cast<FunctionType const&>(*_funCall.expression().annotation().type); if (funType.kind() == FunctionType::Kind::External) return isExternalCallToThis(&_funCall.expression()); else if (funType.kind() != FunctionType::Kind::Internal) return false; return true; } /// AST visitors. bool BMC::visit(ContractDefinition const& _contract) { // Raises UnimplementedFeatureError in the presence of transient storage variables TransientDataLocationChecker checker(_contract); initContract(_contract); SMTEncoder::visit(_contract); return false; } void BMC::endVisit(ContractDefinition const& _contract) { if (auto constructor = _contract.constructor()) constructor->accept(*this); else { /// Visiting implicit constructor - we need a dummy callstack frame pushCallStack({nullptr, nullptr}); inlineConstructorHierarchy(_contract); popCallStack(); /// Check targets created by state variable initialization. checkVerificationTargets(); m_verificationTargets.clear(); } SMTEncoder::endVisit(_contract); } bool BMC::visit(FunctionDefinition const& _function) { // Free functions need to be visited in the context of a contract. if (!m_currentContract) return false; auto contract = dynamic_cast<ContractDefinition const*>(_function.scope()); auto const& hierarchy = m_currentContract->annotation().linearizedBaseContracts; if (contract && find(hierarchy.begin(), hierarchy.end(), contract) == hierarchy.end()) createStateVariables(*contract); if (m_callStack.empty()) { reset(); initFunction(_function); if (_function.isConstructor() || _function.isPublic()) m_context.addAssertion(state().txTypeConstraints() && state().txFunctionConstraints(_function)); resetStateVariables(); } if (_function.isConstructor()) { solAssert(contract, ""); inlineConstructorHierarchy(*contract); } /// Already visits the children. SMTEncoder::visit(_function); return false; } void BMC::endVisit(FunctionDefinition const& _function) { // Free functions need to be visited in the context of a contract. if (!m_currentContract) return; if (isRootFunction()) { checkVerificationTargets(); m_verificationTargets.clear(); m_pathConditions.clear(); } SMTEncoder::endVisit(_function); } bool BMC::visit(IfStatement const& _node) { auto indicesBeforePush = copyVariableIndices(); // This check needs to be done in its own context otherwise // constraints from the If body might influence it. m_context.pushSolver(); _node.condition().accept(*this); // We ignore called functions here because they have // specific input values. if (isRootFunction() && !isInsideLoop()) addVerificationTarget( VerificationTargetType::ConstantCondition, expr(_node.condition()), &_node.condition() ); m_context.popSolver(); resetVariableIndices(std::move(indicesBeforePush)); _node.condition().accept(*this); auto conditionExpr = expr(_node.condition()); // visit true branch auto [indicesEndTrue, trueEndPathCondition] = visitBranch(&_node.trueStatement(), conditionExpr); // visit false branch decltype(indicesEndTrue) indicesEndFalse; auto falseEndPathCondition = currentPathConditions() && !conditionExpr; if (_node.falseStatement()) std::tie(indicesEndFalse, falseEndPathCondition) = visitBranch(_node.falseStatement(), !conditionExpr); else indicesEndFalse = copyVariableIndices(); // merge the information from branches setPathCondition(trueEndPathCondition || falseEndPathCondition); mergeVariables(expr(_node.condition()), indicesEndTrue, indicesEndFalse); return false; } bool BMC::visit(Conditional const& _op) { auto indicesBeforePush = copyVariableIndices(); m_context.pushSolver(); _op.condition().accept(*this); if (isRootFunction() && !isInsideLoop()) addVerificationTarget( VerificationTargetType::ConstantCondition, expr(_op.condition()), &_op.condition() ); m_context.popSolver(); resetVariableIndices(std::move(indicesBeforePush)); SMTEncoder::visit(_op); return false; } // Unrolls while or do-while loop bool BMC::visit(WhileStatement const& _node) { unsigned int bmcLoopIterations = m_settings.bmcLoopIterations.value_or(1); smtutil::Expression broke(false); smtutil::Expression loopCondition(true); if (_node.isDoWhile()) { for (unsigned int i = 0; i < bmcLoopIterations; ++i) { m_loopCheckpoints.emplace(); auto indicesBefore = copyVariableIndices(); _node.body().accept(*this); auto brokeInCurrentIteration = mergeVariablesFromLoopCheckpoints(); auto indicesBreak = copyVariableIndices(); _node.condition().accept(*this); mergeVariables( !brokeInCurrentIteration, copyVariableIndices(), indicesBreak ); mergeVariables( broke || !loopCondition, indicesBefore, copyVariableIndices() ); loopCondition = loopCondition && expr(_node.condition()); broke = broke || brokeInCurrentIteration; m_loopCheckpoints.pop(); } if (bmcLoopIterations > 0) m_context.addAssertion(!loopCondition || broke); } else { smtutil::Expression loopConditionOnPreviousIterations(true); for (unsigned int i = 0; i < bmcLoopIterations; ++i) { m_loopCheckpoints.emplace(); auto indicesBefore = copyVariableIndices(); _node.condition().accept(*this); loopCondition = expr(_node.condition()); auto indicesAfterCondition = copyVariableIndices(); pushPathCondition(loopCondition); _node.body().accept(*this); popPathCondition(); auto brokeInCurrentIteration = mergeVariablesFromLoopCheckpoints(); // merges indices modified when accepting loop condition that no longer holds mergeVariables( !loopCondition, indicesAfterCondition, copyVariableIndices() ); // handles breaks in previous iterations // breaks in current iterations are handled when traversing loop checkpoints // handles case when the loop condition no longer holds but bmc loop iterations still unrolls the loop mergeVariables( broke || !loopConditionOnPreviousIterations, indicesBefore, copyVariableIndices() ); m_loopCheckpoints.pop(); broke = broke || brokeInCurrentIteration; loopConditionOnPreviousIterations = loopConditionOnPreviousIterations && loopCondition; } if (bmcLoopIterations > 0) { //after loop iterations are done, we check the loop condition last final time auto indices = copyVariableIndices(); _node.condition().accept(*this); loopCondition = expr(_node.condition()); // assert that the loop is complete m_context.addAssertion(!loopCondition || broke || !loopConditionOnPreviousIterations); mergeVariables( broke || !loopConditionOnPreviousIterations, indices, copyVariableIndices() ); } } m_loopExecutionHappened = true; return false; } // Unrolls for loop bool BMC::visit(ForStatement const& _node) { if (_node.initializationExpression()) _node.initializationExpression()->accept(*this); smtutil::Expression broke(false); smtutil::Expression forCondition(true); smtutil::Expression forConditionOnPreviousIterations(true); unsigned int bmcLoopIterations = m_settings.bmcLoopIterations.value_or(1); for (unsigned int i = 0; i < bmcLoopIterations; ++i) { auto indicesBefore = copyVariableIndices(); if (_node.condition()) { _node.condition()->accept(*this); // values in loop condition might change during loop iteration forCondition = expr(*_node.condition()); } m_loopCheckpoints.emplace(); auto indicesAfterCondition = copyVariableIndices(); pushPathCondition(forCondition); _node.body().accept(*this); auto brokeInCurrentIteration = mergeVariablesFromLoopCheckpoints(); // accept loop expression if there was no break if (_node.loopExpression()) { auto indicesBreak = copyVariableIndices(); _node.loopExpression()->accept(*this); mergeVariables( !brokeInCurrentIteration, copyVariableIndices(), indicesBreak ); } popPathCondition(); // merges indices modified when accepting loop condition that does no longer hold mergeVariables( !forCondition, indicesAfterCondition, copyVariableIndices() ); // handles breaks in previous iterations // breaks in current iterations are handled when traversing loop checkpoints // handles case when the loop condition no longer holds but bmc loop iterations still unrolls the loop mergeVariables( broke || !forConditionOnPreviousIterations, indicesBefore, copyVariableIndices() ); m_loopCheckpoints.pop(); broke = broke || brokeInCurrentIteration; forConditionOnPreviousIterations = forConditionOnPreviousIterations && forCondition; } if (bmcLoopIterations > 0) { //after loop iterations are done, we check the loop condition last final time auto indices = copyVariableIndices(); if (_node.condition()) { _node.condition()->accept(*this); forCondition = expr(*_node.condition()); } // asseert that the loop is complete m_context.addAssertion(!forCondition || broke || !forConditionOnPreviousIterations); mergeVariables( broke || !forConditionOnPreviousIterations, indices, copyVariableIndices() ); } m_loopExecutionHappened = true; return false; } // merges variables based on loop control statements // returns expression indicating whether there was a break in current loop unroll iteration smtutil::Expression BMC::mergeVariablesFromLoopCheckpoints() { smtutil::Expression continues(false); smtutil::Expression brokeInCurrentIteration(false); for (auto const& loopControl: m_loopCheckpoints.top()) { // use SSAs associated with this break statement only if // loop didn't break or continue earlier in the iteration // loop condition is included in break path conditions mergeVariables( !brokeInCurrentIteration && !continues && loopControl.pathConditions, loopControl.variableIndices, copyVariableIndices() ); if (loopControl.kind == LoopControlKind::Break) brokeInCurrentIteration = brokeInCurrentIteration || loopControl.pathConditions; else if (loopControl.kind == LoopControlKind::Continue) continues = continues || loopControl.pathConditions; } return brokeInCurrentIteration; } bool BMC::visit(TryStatement const& _tryStatement) { FunctionCall const* externalCall = dynamic_cast<FunctionCall const*>(&_tryStatement.externalCall()); solAssert(externalCall && externalCall->annotation().tryCall, ""); externalCall->accept(*this); if (_tryStatement.successClause()->parameters()) expressionToTupleAssignment(_tryStatement.successClause()->parameters()->parameters(), *externalCall); smtutil::Expression clauseId = m_context.newVariable("clause_choice_" + std::to_string(m_context.newUniqueId()), smtutil::SortProvider::uintSort); auto const& clauses = _tryStatement.clauses(); m_context.addAssertion(clauseId >= 0 && clauseId < clauses.size()); solAssert(clauses[0].get() == _tryStatement.successClause(), "First clause of TryStatement should be the success clause"); std::vector<std::pair<VariableIndices, smtutil::Expression>> clausesVisitResults; for (size_t i = 0; i < clauses.size(); ++i) clausesVisitResults.push_back(visitBranch(clauses[i].get())); // merge the information from all clauses smtutil::Expression pathCondition = clausesVisitResults.front().second; auto currentIndices = clausesVisitResults[0].first; for (size_t i = 1; i < clauses.size(); ++i) { mergeVariables(clauseId == i, clausesVisitResults[i].first, currentIndices); currentIndices = copyVariableIndices(); pathCondition = pathCondition || clausesVisitResults[i].second; } setPathCondition(pathCondition); return false; } bool BMC::visit(Break const&) { LoopControl control = { LoopControlKind::Break, currentPathConditions(), copyVariableIndices() }; m_loopCheckpoints.top().emplace_back(control); return false; } bool BMC::visit(Continue const&) { LoopControl control = { LoopControlKind::Continue, currentPathConditions(), copyVariableIndices() }; m_loopCheckpoints.top().emplace_back(control); return false; } void BMC::endVisit(UnaryOperation const& _op) { SMTEncoder::endVisit(_op); // User-defined operators are essentially function calls. if (auto funDef = *_op.annotation().userDefinedFunction) { std::vector<Expression const*> arguments; arguments.push_back(&_op.subExpression()); // pushCallStack and defineExpr inside createReturnedExpression should be called on the expression // in case of a user-defined operator call inlineFunctionCall(funDef, _op, std::nullopt, arguments); return; } if ( _op.annotation().type->category() == Type::Category::RationalNumber || _op.annotation().type->category() == Type::Category::FixedPoint ) return; if (_op.getOperator() == Token::Sub && smt::isInteger(*_op.annotation().type)) { addVerificationTarget( VerificationTargetType::Underflow, expr(_op), &_op ); addVerificationTarget( VerificationTargetType::Overflow, expr(_op), &_op ); } } void BMC::endVisit(BinaryOperation const& _op) { SMTEncoder::endVisit(_op); if (auto funDef = *_op.annotation().userDefinedFunction) { std::vector<Expression const*> arguments; arguments.push_back(&_op.leftExpression()); arguments.push_back(&_op.rightExpression()); // pushCallStack and defineExpr inside createReturnedExpression should be called on the expression // in case of a user-defined operator call inlineFunctionCall(funDef, _op, std::nullopt, arguments); } } void BMC::endVisit(FunctionCall const& _funCall) { auto functionCallKind = *_funCall.annotation().kind; if (functionCallKind != FunctionCallKind::FunctionCall) { SMTEncoder::endVisit(_funCall); return; } FunctionType const& funType = dynamic_cast<FunctionType const&>(*_funCall.expression().annotation().type); switch (funType.kind()) { case FunctionType::Kind::Assert: visitAssert(_funCall); SMTEncoder::endVisit(_funCall); break; case FunctionType::Kind::Require: visitRequire(_funCall); SMTEncoder::endVisit(_funCall); break; case FunctionType::Kind::Internal: case FunctionType::Kind::External: case FunctionType::Kind::DelegateCall: case FunctionType::Kind::BareCall: case FunctionType::Kind::BareCallCode: case FunctionType::Kind::BareDelegateCall: case FunctionType::Kind::BareStaticCall: case FunctionType::Kind::Creation: SMTEncoder::endVisit(_funCall); internalOrExternalFunctionCall(_funCall); break; case FunctionType::Kind::Send: case FunctionType::Kind::Transfer: { auto value = _funCall.arguments().front(); solAssert(value, ""); smtutil::Expression thisBalance = state().balance(); addVerificationTarget( VerificationTargetType::Balance, thisBalance < expr(*value), &_funCall ); SMTEncoder::endVisit(_funCall); break; } case FunctionType::Kind::KECCAK256: case FunctionType::Kind::ECRecover: case FunctionType::Kind::SHA256: case FunctionType::Kind::RIPEMD160: case FunctionType::Kind::BlockHash: case FunctionType::Kind::AddMod: case FunctionType::Kind::MulMod: case FunctionType::Kind::Unwrap: case FunctionType::Kind::Wrap: [[fallthrough]]; default: SMTEncoder::endVisit(_funCall); break; } } void BMC::endVisit(Return const& _return) { SMTEncoder::endVisit(_return); setPathCondition(smtutil::Expression(false)); } /// Visitor helpers. void BMC::visitAssert(FunctionCall const& _funCall) { auto const& args = _funCall.arguments(); solAssert(args.size() == 1, ""); solAssert(args.front()->annotation().type->category() == Type::Category::Bool, ""); addVerificationTarget( VerificationTargetType::Assert, expr(*args.front()), &_funCall ); } void BMC::visitRequire(FunctionCall const& _funCall) { auto const& args = _funCall.arguments(); solAssert(args.size() >= 1, ""); solAssert(args.front()->annotation().type->category() == Type::Category::Bool, ""); if (isRootFunction() && !isInsideLoop()) addVerificationTarget( VerificationTargetType::ConstantCondition, expr(*args.front()), args.front().get() ); } void BMC::visitAddMulMod(FunctionCall const& _funCall) { solAssert(_funCall.arguments().at(2), ""); addVerificationTarget( VerificationTargetType::DivByZero, expr(*_funCall.arguments().at(2)), &_funCall ); SMTEncoder::visitAddMulMod(_funCall); } void BMC::inlineFunctionCall( FunctionDefinition const* _funDef, Expression const& _callStackExpr, std::optional<Expression const*> _boundArgumentCall, std::vector<Expression const*> const& _arguments ) { solAssert(_funDef, ""); if (visitedFunction(_funDef)) { auto const& returnParams = _funDef->returnParameters(); for (auto param: returnParams) { m_context.newValue(*param); m_context.setUnknownValue(*param); } } else { initializeFunctionCallParameters(*_funDef, symbolicArguments(_funDef->parameters(), _arguments, _boundArgumentCall)); // The reason why we need to pushCallStack here instead of visit(FunctionDefinition) // is that there we don't have `_callStackExpr`. pushCallStack({_funDef, &_callStackExpr}); pushPathCondition(currentPathConditions()); auto oldChecked = std::exchange(m_checked, true); _funDef->accept(*this); m_checked = oldChecked; popPathCondition(); } createReturnedExpressions(_funDef, _callStackExpr); } void BMC::inlineFunctionCall(FunctionCall const& _funCall) { solAssert(shouldInlineFunctionCall(_funCall, currentScopeContract(), m_currentContract), ""); auto funDef = functionCallToDefinition(_funCall, currentScopeContract(), m_currentContract); Expression const* expr = &_funCall.expression(); auto funType = dynamic_cast<FunctionType const*>(expr->annotation().type); std::optional<Expression const*> boundArgumentCall = funType->hasBoundFirstArgument() ? std::make_optional(expr) : std::nullopt; std::vector<Expression const*> arguments; for (auto& arg: _funCall.sortedArguments()) arguments.push_back(&(*arg)); // pushCallStack and defineExpr inside createReturnedExpression should be called // on the FunctionCall object for the normal function call case inlineFunctionCall(funDef, _funCall, boundArgumentCall, arguments); } void BMC::internalOrExternalFunctionCall(FunctionCall const& _funCall) { auto const& funType = dynamic_cast<FunctionType const&>(*_funCall.expression().annotation().type); if (shouldInlineFunctionCall(_funCall, currentScopeContract(), m_currentContract)) inlineFunctionCall(_funCall); else if (publicGetter(_funCall.expression())) { // Do nothing here. // The processing happens in SMT Encoder, but we need to prevent the resetting of the state variables. } else if (funType.kind() == FunctionType::Kind::Internal) m_unsupportedErrors.warning( 5729_error, _funCall.location(), "BMC does not yet implement this type of function call." ); else if (funType.kind() == FunctionType::Kind::BareStaticCall) { // Do nothing here. // Neither storage nor balances should be modified. } else { m_externalFunctionCallHappened = true; resetStorageVariables(); resetBalances(); } } std::pair<smtutil::Expression, smtutil::Expression> BMC::arithmeticOperation( Token _op, smtutil::Expression const& _left, smtutil::Expression const& _right, Type const* _commonType, Expression const& _expression ) { // Unchecked does not disable div by 0 checks. if (_op == Token::Div || _op == Token::Mod) addVerificationTarget( VerificationTargetType::DivByZero, _right, &_expression ); auto values = SMTEncoder::arithmeticOperation(_op, _left, _right, _commonType, _expression); if (!m_checked) return values; auto const* intType = dynamic_cast<IntegerType const*>(_commonType); if (!intType) intType = TypeProvider::uint256(); // Mod does not need underflow/overflow checks. if (_op == Token::Mod) return values; // The order matters here: // If _op is Div and intType is signed, we only care about overflow. if (_op == Token::Div) { if (intType->isSigned()) // Signed division can only overflow. addVerificationTarget(VerificationTargetType::Overflow, values.second, &_expression); else // Unsigned division cannot underflow/overflow. return values; } else if (intType->isSigned()) { addVerificationTarget(VerificationTargetType::Overflow, values.second, &_expression); addVerificationTarget(VerificationTargetType::Underflow, values.second, &_expression); } else if (_op == Token::Sub) addVerificationTarget(VerificationTargetType::Underflow, values.second, &_expression); else if (_op == Token::Add || _op == Token::Mul) addVerificationTarget(VerificationTargetType::Overflow, values.second, &_expression); else solAssert(false, ""); return values; } void BMC::reset() { m_externalFunctionCallHappened = false; m_loopExecutionHappened = false; } std::pair<std::vector<smtutil::Expression>, std::vector<std::string>> BMC::modelExpressions() { std::vector<smtutil::Expression> expressionsToEvaluate; std::vector<std::string> expressionNames; for (auto const& var: m_context.variables()) if (var.first->type()->isValueType()) { expressionsToEvaluate.emplace_back(currentValue(*var.first)); expressionNames.push_back(var.first->name()); } for (auto const& var: m_context.globalSymbols()) { auto const& type = var.second->type(); if ( type->isValueType() && smt::smtKind(*type) != smtutil::Kind::Function ) { expressionsToEvaluate.emplace_back(var.second->currentValue()); expressionNames.push_back(var.first); } } for (auto const& uf: m_uninterpretedTerms) if (uf->annotation().type->isValueType()) { expressionsToEvaluate.emplace_back(expr(*uf)); std::string expressionName; if (uf->location().hasText()) expressionName = m_charStreamProvider.charStream(*uf->location().sourceName).text( uf->location() ); expressionNames.push_back(std::move(expressionName)); } return {expressionsToEvaluate, expressionNames}; } /// Verification targets. std::string BMC::targetDescription(BMCVerificationTarget const& _target) { if ( _target.type == VerificationTargetType::Underflow || _target.type == VerificationTargetType::Overflow ) { auto const* intType = dynamic_cast<IntegerType const*>(_target.expression->annotation().type); if (!intType) intType = TypeProvider::uint256(); if (_target.type == VerificationTargetType::Underflow) return "Underflow (resulting value less than " + formatNumberReadable(intType->minValue()) + ")"; return "Overflow (resulting value larger than " + formatNumberReadable(intType->maxValue()) + ")"; } else if (_target.type == VerificationTargetType::DivByZero) return "Division by zero"; else if (_target.type == VerificationTargetType::Assert) return "Assertion violation"; else if (_target.type == VerificationTargetType::Balance) return "Insufficient funds"; solAssert(false); } void BMC::checkVerificationTargets() { for (auto& target: m_verificationTargets) checkVerificationTarget(target); } void BMC::checkVerificationTarget(BMCVerificationTarget& _target) { if ( m_solvedTargets.count(_target.expression) && m_solvedTargets.at(_target.expression).count(_target.type) ) return; switch (_target.type) { case VerificationTargetType::ConstantCondition: checkConstantCondition(_target); break; case VerificationTargetType::Underflow: checkUnderflow(_target); break; case VerificationTargetType::Overflow: checkOverflow(_target); break; case VerificationTargetType::DivByZero: checkDivByZero(_target); break; case VerificationTargetType::Balance: checkBalance(_target); break; case VerificationTargetType::Assert: checkAssert(_target); break; default: solAssert(false, ""); } } void BMC::checkConstantCondition(BMCVerificationTarget& _target) { checkBooleanNotConstant( *_target.expression, _target.constraints, _target.value, _target.callStack ); } void BMC::checkUnderflow(BMCVerificationTarget& _target) { solAssert( _target.type == VerificationTargetType::Underflow, "" ); auto const* intType = dynamic_cast<IntegerType const*>(_target.expression->annotation().type); if (!intType) intType = TypeProvider::uint256(); checkCondition( _target, _target.constraints && _target.value < smt::minValue(*intType), _target.callStack, _target.modelExpressions, _target.expression->location(), 4144_error, 8312_error, "<result>", &_target.value ); } void BMC::checkOverflow(BMCVerificationTarget& _target) { solAssert( _target.type == VerificationTargetType::Overflow, "" ); auto const* intType = dynamic_cast<IntegerType const*>(_target.expression->annotation().type); if (!intType) intType = TypeProvider::uint256(); checkCondition( _target, _target.constraints && _target.value > smt::maxValue(*intType), _target.callStack, _target.modelExpressions, _target.expression->location(), 2661_error, 8065_error, "<result>", &_target.value ); } void BMC::checkDivByZero(BMCVerificationTarget& _target) { solAssert(_target.type == VerificationTargetType::DivByZero, ""); checkCondition( _target, _target.constraints && (_target.value == 0), _target.callStack, _target.modelExpressions, _target.expression->location(), 3046_error, 5272_error, "<result>", &_target.value ); } void BMC::checkBalance(BMCVerificationTarget& _target) { solAssert(_target.type == VerificationTargetType::Balance, ""); checkCondition( _target, _target.constraints && _target.value, _target.callStack, _target.modelExpressions, _target.expression->location(), 1236_error, 4010_error, "address(this).balance" ); } void BMC::checkAssert(BMCVerificationTarget& _target) { solAssert(_target.type == VerificationTargetType::Assert, ""); checkCondition( _target, _target.constraints && !_target.value, _target.callStack, _target.modelExpressions, _target.expression->location(), 4661_error, 7812_error ); } void BMC::addVerificationTarget( VerificationTargetType _type, smtutil::Expression const& _value, Expression const* _expression ) { if (!m_settings.targets.has(_type) || (m_currentContract && !shouldAnalyze(*m_currentContract))) return; BMCVerificationTarget target{ { _type, _value, currentPathConditions() && m_context.assertions() }, _expression, m_callStack, modelExpressions() }; if (_type == VerificationTargetType::ConstantCondition) checkVerificationTarget(target); else m_verificationTargets.emplace_back(std::move(target)); } /// Solving. void BMC::checkCondition( BMCVerificationTarget const& _target, smtutil::Expression _condition, std::vector<SMTEncoder::CallStackEntry> const& _callStack, std::pair<std::vector<smtutil::Expression>, std::vector<std::string>> const& _modelExpressions, SourceLocation const& _location, ErrorId _errorHappens, ErrorId _errorMightHappen, std::string const& _additionalValueName, smtutil::Expression const* _additionalValue ) { m_interface->push(); m_interface->addAssertion(_condition); std::vector<smtutil::Expression> expressionsToEvaluate; std::vector<std::string> expressionNames; tie(expressionsToEvaluate, expressionNames) = _modelExpressions; if (!_callStack.empty()) if (_additionalValue) { expressionsToEvaluate.emplace_back(*_additionalValue); expressionNames.push_back(_additionalValueName); } smtutil::CheckResult result; std::vector<std::string> values; tie(result, values) = checkSatisfiableAndGenerateModel(expressionsToEvaluate); std::string extraComment = SMTEncoder::extraComment(); if (m_loopExecutionHappened) extraComment += "False negatives are possible when unrolling loops.\n" "This is due to the possibility that the BMC loop iteration setting is" " smaller than the actual number of iterations needed to complete a loop."; if (m_externalFunctionCallHappened) extraComment += "\nNote that external function calls are not inlined," " even if the source code of the function is available." " This is due to the possibility that the actual called contract" " has the same ABI but implements the function differently."; SecondarySourceLocation secondaryLocation{}; secondaryLocation.append(extraComment, SourceLocation{}); switch (result) { case smtutil::CheckResult::SATISFIABLE: { solAssert(!_callStack.empty(), ""); std::ostringstream message; message << "BMC: " << targetDescription(_target) << " happens here."; std::ostringstream modelMessage; // Sometimes models have complex smtlib2 expressions that SMTLib2Interface fails to parse. if (values.size() == expressionNames.size()) { modelMessage << "Counterexample:\n"; std::map<std::string, std::string> sortedModel; for (size_t i = 0; i < values.size(); ++i) if (expressionsToEvaluate.at(i).name != values.at(i)) sortedModel[expressionNames.at(i)] = values.at(i); for (auto const& eval: sortedModel) modelMessage << " " << eval.first << " = " << eval.second << "\n"; } m_errorReporter.warning( _errorHappens, _location, message.str(), SecondarySourceLocation().append(modelMessage.str(), SourceLocation{}) .append(SMTEncoder::callStackMessage(_callStack)) .append(std::move(secondaryLocation)) ); break; } case smtutil::CheckResult::UNSATISFIABLE: { m_safeTargets[_target.expression].insert(_target); break; } case smtutil::CheckResult::UNKNOWN: { ++m_unprovedAmt; if (m_settings.showUnproved) m_errorReporter.warning(_errorMightHappen, _location, "BMC: " + targetDescription(_target) + " might happen here.", secondaryLocation); break; } case smtutil::CheckResult::CONFLICTING: m_errorReporter.warning(1584_error, _location, "BMC: At least two SMT solvers provided conflicting answers. Results might not be sound."); break; case smtutil::CheckResult::ERROR: m_errorReporter.warning(1823_error, _location, "BMC: Error during interaction with the SMT solver."); break; } m_interface->pop(); } void BMC::checkBooleanNotConstant( Expression const& _condition, smtutil::Expression const& _constraints, smtutil::Expression const& _value, std::vector<SMTEncoder::CallStackEntry> const& _callStack ) { // Do not check for const-ness if this is a constant. if (dynamic_cast<Literal const*>(&_condition)) return; m_interface->push(); m_interface->addAssertion(_constraints && _value); auto positiveResult = checkSatisfiable(); m_interface->pop(); m_interface->push(); m_interface->addAssertion(_constraints && !_value); auto negatedResult = checkSatisfiable(); m_interface->pop(); if (positiveResult == smtutil::CheckResult::ERROR || negatedResult == smtutil::CheckResult::ERROR) m_errorReporter.warning(8592_error, _condition.location(), "BMC: Error trying to invoke SMT solver."); else if (positiveResult == smtutil::CheckResult::CONFLICTING || negatedResult == smtutil::CheckResult::CONFLICTING) m_errorReporter.warning(3356_error, _condition.location(), "BMC: At least two SMT solvers provided conflicting answers. Results might not be sound."); else if (positiveResult == smtutil::CheckResult::SATISFIABLE && negatedResult == smtutil::CheckResult::SATISFIABLE) { // everything fine. } else if (positiveResult == smtutil::CheckResult::UNKNOWN || negatedResult == smtutil::CheckResult::UNKNOWN) { // can't do anything. } else if (positiveResult == smtutil::CheckResult::UNSATISFIABLE && negatedResult == smtutil::CheckResult::UNSATISFIABLE) m_errorReporter.warning(2512_error, _condition.location(), "BMC: Condition unreachable.", SMTEncoder::callStackMessage(_callStack)); else { std::string description; if (positiveResult == smtutil::CheckResult::SATISFIABLE) { solAssert(negatedResult == smtutil::CheckResult::UNSATISFIABLE, ""); description = "BMC: Condition is always true."; } else { solAssert(positiveResult == smtutil::CheckResult::UNSATISFIABLE, ""); solAssert(negatedResult == smtutil::CheckResult::SATISFIABLE, ""); description = "BMC: Condition is always false."; } m_errorReporter.warning( 6838_error, _condition.location(), description, SMTEncoder::callStackMessage(_callStack) ); } } std::pair<smtutil::CheckResult, std::vector<std::string>> BMC::checkSatisfiableAndGenerateModel(std::vector<smtutil::Expression> const& _expressionsToEvaluate) { smtutil::CheckResult result; std::vector<std::string> values; try { if (m_settings.printQuery) { auto portfolio = dynamic_cast<smtutil::SMTPortfolio*>(m_interface.get()); std::string smtlibCode = portfolio->dumpQuery(_expressionsToEvaluate); m_errorReporter.info( 6240_error, "BMC: Requested query:\n" + smtlibCode ); } tie(result, values) = m_interface->check(_expressionsToEvaluate); } catch (smtutil::SolverError const& _e) { std::string description("BMC: Error querying SMT solver"); if (_e.comment()) description += ": " + *_e.comment(); m_errorReporter.warning(8140_error, description); result = smtutil::CheckResult::ERROR; } for (std::string& value: values) { try { // Parse and re-format nicely value = formatNumberReadable(bigint(value)); } catch (...) { } } return make_pair(result, values); } smtutil::CheckResult BMC::checkSatisfiable() { return checkSatisfiableAndGenerateModel({}).first; } void BMC::assignment(smt::SymbolicVariable& _symVar, smtutil::Expression const& _value) { auto oldVar = _symVar.currentValue(); auto newVar = _symVar.increaseIndex(); m_context.addAssertion(smtutil::Expression::ite( currentPathConditions(), newVar == _value, newVar == oldVar )); } bool BMC::isInsideLoop() const { return !m_loopCheckpoints.empty(); }
39,243
C++
.cpp
1,168
30.898116
152
0.755946
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
3,173
CHC.cpp
ethereum_solidity/libsolidity/formal/CHC.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libsolidity/formal/CHC.h> #include <libsolidity/formal/ArraySlicePredicate.h> #include <libsolidity/formal/EldaricaCHCSmtLib2Interface.h> #include <libsolidity/formal/Invariants.h> #include <libsolidity/formal/ModelChecker.h> #include <libsolidity/formal/PredicateInstance.h> #include <libsolidity/formal/PredicateSort.h> #include <libsolidity/formal/SymbolicTypes.h> #include <libsolidity/formal/Z3CHCSmtLib2Interface.h> #include <libsolidity/ast/TypeProvider.h> #include <libsmtutil/CHCSmtLib2Interface.h> #include <liblangutil/CharStreamProvider.h> #include <libsolutil/Algorithms.h> #include <libsolutil/StringUtils.h> #include <boost/algorithm/string.hpp> #include <range/v3/algorithm/for_each.hpp> #include <range/v3/view.hpp> #include <range/v3/view/enumerate.hpp> #include <range/v3/view/reverse.hpp> #include <charconv> #include <queue> using namespace solidity; using namespace solidity::util; using namespace solidity::langutil; using namespace solidity::smtutil; using namespace solidity::frontend; using namespace solidity::frontend::smt; CHC::CHC( EncodingContext& _context, UniqueErrorReporter& _errorReporter, UniqueErrorReporter& _unsupportedErrorReporter, ErrorReporter& _provedSafeReporter, std::map<util::h256, std::string> const& _smtlib2Responses, ReadCallback::Callback const& _smtCallback, ModelCheckerSettings _settings, CharStreamProvider const& _charStreamProvider ): SMTEncoder(_context, _settings, _errorReporter, _unsupportedErrorReporter, _provedSafeReporter, _charStreamProvider), m_smtlib2Responses(_smtlib2Responses), m_smtCallback(_smtCallback) { solAssert(!_settings.printQuery || _settings.solvers == smtutil::SMTSolverChoice::SMTLIB2(), "Only SMTLib2 solver can be enabled to print queries"); } void CHC::analyze(SourceUnit const& _source) { // At this point every enabled solver is available. if (!m_settings.solvers.eld && !m_settings.solvers.smtlib2 && !m_settings.solvers.z3) { m_errorReporter.warning( 7649_error, SourceLocation(), "CHC analysis was not possible since no Horn solver was found and enabled." " The accepted solvers for CHC are Eldarica and z3." ); return; } if (m_settings.solvers.eld && m_settings.solvers.z3) m_errorReporter.warning( 5798_error, SourceLocation(), "Multiple Horn solvers were selected for CHC." " CHC only supports one solver at a time, therefore only z3 will be used." " If you wish to use Eldarica, please enable Eldarica only." ); if (!shouldAnalyze(_source)) return; resetSourceAnalysis(); auto sources = sourceDependencies(_source); collectFreeFunctions(sources); createFreeConstants(sources); state().prepareForSourceUnit(_source, encodeExternalCallsAsTrusted()); for (auto const* source: sources) defineInterfacesAndSummaries(*source); for (auto const* source: sources) source->accept(*this); checkVerificationTargets(); bool ranSolver = true; // If ranSolver is true here it's because an SMT solver callback was // actually given and the queries were solved, // or Eldarica was chosen and was present in the system. if (auto const* smtLibInterface = dynamic_cast<CHCSmtLib2Interface const*>(m_interface.get())) ranSolver = smtLibInterface->unhandledQueries().empty(); if (!ranSolver) m_errorReporter.warning( 3996_error, SourceLocation(), "CHC analysis was not possible. No Horn solver was available." " None of the installed solvers was enabled." ); } std::vector<std::string> CHC::unhandledQueries() const { if (auto smtlib2 = dynamic_cast<CHCSmtLib2Interface const*>(m_interface.get())) return smtlib2->unhandledQueries(); return {}; } bool CHC::visit(ContractDefinition const& _contract) { if (!shouldAnalyze(_contract)) return false; // Raises UnimplementedFeatureError in the presence of transient storage variables TransientDataLocationChecker checker(_contract); resetContractAnalysis(); initContract(_contract); clearIndices(&_contract); m_scopes.push_back(&_contract); m_stateVariables = SMTEncoder::stateVariablesIncludingInheritedAndPrivate(_contract); solAssert(m_currentContract, ""); SMTEncoder::visit(_contract); return false; } void CHC::endVisit(ContractDefinition const& _contract) { if (!shouldAnalyze(_contract)) return; for (auto base: _contract.annotation().linearizedBaseContracts) { if (auto constructor = base->constructor()) constructor->accept(*this); defineContractInitializer(*base, _contract); } auto const& entry = *createConstructorBlock(_contract, "implicit_constructor_entry"); // In case constructors use uninitialized state variables, // they need to be zeroed. // This is not part of `initialConstraints` because it's only true here, // at the beginning of the deployment routine. smtutil::Expression zeroes(true); for (auto var: stateVariablesIncludingInheritedAndPrivate(_contract)) zeroes = zeroes && currentValue(*var) == smt::zeroValue(var->type()); smtutil::Expression newAddress = encodeExternalCallsAsTrusted() ? !state().addressActive(state().thisAddress()) : smtutil::Expression(true); // The contract's address might already have funds before deployment, // so the balance must be at least `msg.value`, but not equals. auto initialBalanceConstraint = state().balance(state().thisAddress()) >= state().txMember("msg.value"); addRule(smtutil::Expression::implies( initialConstraints(_contract) && zeroes && newAddress && initialBalanceConstraint, predicate(entry) ), entry.functor().name); setCurrentBlock(entry); if (encodeExternalCallsAsTrusted()) { auto const& entryAfterAddress = *createConstructorBlock(_contract, "implicit_constructor_entry_after_address"); state().setAddressActive(state().thisAddress(), true); connectBlocks(m_currentBlock, predicate(entryAfterAddress)); setCurrentBlock(entryAfterAddress); } solAssert(!m_errorDest, ""); m_errorDest = m_constructorSummaries.at(&_contract); // We need to evaluate the base constructor calls (arguments) from derived -> base auto baseArgs = baseArguments(_contract); for (auto base: _contract.annotation().linearizedBaseContracts) if (base != &_contract) { m_callGraph[&_contract].insert(base); auto baseConstructor = base->constructor(); if (baseConstructor && baseArgs.count(base)) { std::vector<ASTPointer<Expression>> const& args = baseArgs.at(base); auto const& params = baseConstructor->parameters(); solAssert(params.size() == args.size(), ""); for (unsigned i = 0; i < params.size(); ++i) { args.at(i)->accept(*this); if (params.at(i)) { solAssert(m_context.knownVariable(*params.at(i)), ""); m_context.addAssertion(currentValue(*params.at(i)) == expr(*args.at(i), params.at(i)->type())); } } } } m_errorDest = nullptr; // Then call initializer_Base from base -> derived for (auto base: _contract.annotation().linearizedBaseContracts | ranges::views::reverse) { errorFlag().increaseIndex(); m_context.addAssertion(smt::constructorCall(*m_contractInitializers.at(&_contract).at(base), m_context)); connectBlocks(m_currentBlock, summary(_contract), errorFlag().currentValue() > 0); m_context.addAssertion(errorFlag().currentValue() == 0); } if (encodeExternalCallsAsTrusted()) state().writeStateVars(_contract, state().thisAddress()); connectBlocks(m_currentBlock, summary(_contract)); setCurrentBlock(*m_constructorSummaries.at(&_contract)); solAssert(&_contract == m_currentContract, ""); if (shouldAnalyze(_contract)) { auto constructor = _contract.constructor(); auto txConstraints = state().txTypeConstraints(); if (!constructor || !constructor->isPayable()) txConstraints = txConstraints && state().txNonPayableConstraint(); m_queryPlaceholders[&_contract].push_back({txConstraints, errorFlag().currentValue(), m_currentBlock}); connectBlocks(m_currentBlock, interface(), txConstraints && errorFlag().currentValue() == 0); } solAssert(m_scopes.back() == &_contract, ""); m_scopes.pop_back(); SMTEncoder::endVisit(_contract); } bool CHC::visit(FunctionDefinition const& _function) { // Free functions need to be visited in the context of a contract. if (!m_currentContract) return false; if ( !_function.isImplemented() || abstractAsNondet(_function) ) { smtutil::Expression conj(true); if ( _function.stateMutability() == StateMutability::Pure || _function.stateMutability() == StateMutability::View ) conj = conj && currentEqualInitialVarsConstraints(stateVariablesIncludingInheritedAndPrivate(_function)); conj = conj && errorFlag().currentValue() == 0; addRule(smtutil::Expression::implies(conj, summary(_function)), "summary_function_" + std::to_string(_function.id())); return false; } // No inlining. solAssert(!m_currentFunction, "Function inlining should not happen in CHC."); m_currentFunction = &_function; m_scopes.push_back(&_function); initFunction(_function); auto functionEntryBlock = createBlock(m_currentFunction, PredicateType::FunctionBlock); auto bodyBlock = createBlock(&m_currentFunction->body(), PredicateType::FunctionBlock); auto functionPred = predicate(*functionEntryBlock); auto bodyPred = predicate(*bodyBlock); addRule(functionPred, functionPred.name); solAssert(m_currentContract, ""); m_context.addAssertion(initialConstraints(*m_currentContract, &_function)); connectBlocks(functionPred, bodyPred); setCurrentBlock(*bodyBlock); solAssert(!m_errorDest, ""); m_errorDest = m_summaries.at(m_currentContract).at(&_function); SMTEncoder::visit(*m_currentFunction); m_errorDest = nullptr; return false; } void CHC::endVisit(FunctionDefinition const& _function) { // Free functions need to be visited in the context of a contract. if (!m_currentContract) return; if ( !_function.isImplemented() || abstractAsNondet(_function) ) return; solAssert(m_currentFunction && m_currentContract, ""); // No inlining. solAssert(m_currentFunction == &_function, ""); solAssert(m_scopes.back() == &_function, ""); m_scopes.pop_back(); connectBlocks(m_currentBlock, summary(_function)); setCurrentBlock(*m_summaries.at(m_currentContract).at(&_function)); // Query placeholders for constructors are not created here because // of contracts without constructors. // Instead, those are created in endVisit(ContractDefinition). if ( !_function.isConstructor() && _function.isPublic() && contractFunctions(*m_currentContract).count(&_function) && shouldAnalyze(*m_currentContract) ) { defineExternalFunctionInterface(_function, *m_currentContract); setCurrentBlock(*m_interfaces.at(m_currentContract)); // Create the rule // interface \land externalFunctionEntry => interface' auto ifacePre = smt::interfacePre(*m_interfaces.at(m_currentContract), *m_currentContract, m_context); auto sum = externalSummary(_function); m_queryPlaceholders[&_function].push_back({sum, errorFlag().currentValue(), ifacePre}); connectBlocks(ifacePre, interface(), sum && errorFlag().currentValue() == 0); } m_currentFunction = nullptr; SMTEncoder::endVisit(_function); } bool CHC::visit(Block const& _block) { m_scopes.push_back(&_block); return SMTEncoder::visit(_block); } void CHC::endVisit(Block const& _block) { solAssert(m_scopes.back() == &_block, ""); m_scopes.pop_back(); SMTEncoder::endVisit(_block); } bool CHC::visit(IfStatement const& _if) { solAssert(m_currentFunction, ""); bool unknownFunctionCallWasSeen = m_unknownFunctionCallSeen; m_unknownFunctionCallSeen = false; solAssert(m_currentFunction, ""); auto const& functionBody = m_currentFunction->body(); auto ifHeaderBlock = createBlock(&_if, PredicateType::FunctionBlock, "if_header_"); auto trueBlock = createBlock(&_if.trueStatement(), PredicateType::FunctionBlock, "if_true_"); auto falseBlock = _if.falseStatement() ? createBlock(_if.falseStatement(), PredicateType::FunctionBlock, "if_false_") : nullptr; auto afterIfBlock = createBlock(&functionBody, PredicateType::FunctionBlock); connectBlocks(m_currentBlock, predicate(*ifHeaderBlock)); setCurrentBlock(*ifHeaderBlock); _if.condition().accept(*this); auto condition = expr(_if.condition()); connectBlocks(m_currentBlock, predicate(*trueBlock), condition); if (_if.falseStatement()) connectBlocks(m_currentBlock, predicate(*falseBlock), !condition); else connectBlocks(m_currentBlock, predicate(*afterIfBlock), !condition); setCurrentBlock(*trueBlock); _if.trueStatement().accept(*this); connectBlocks(m_currentBlock, predicate(*afterIfBlock)); if (_if.falseStatement()) { setCurrentBlock(*falseBlock); _if.falseStatement()->accept(*this); connectBlocks(m_currentBlock, predicate(*afterIfBlock)); } setCurrentBlock(*afterIfBlock); if (m_unknownFunctionCallSeen) eraseKnowledge(); m_unknownFunctionCallSeen = unknownFunctionCallWasSeen; return false; } bool CHC::visit(WhileStatement const& _while) { bool unknownFunctionCallWasSeen = m_unknownFunctionCallSeen; m_unknownFunctionCallSeen = false; solAssert(m_currentFunction, ""); auto const& functionBody = m_currentFunction->body(); auto namePrefix = std::string(_while.isDoWhile() ? "do_" : "") + "while"; auto loopHeaderBlock = createBlock(&_while, PredicateType::FunctionBlock, namePrefix + "_header_"); auto loopBodyBlock = createBlock(&_while.body(), PredicateType::FunctionBlock, namePrefix + "_body_"); auto afterLoopBlock = createBlock(&functionBody, PredicateType::FunctionBlock); auto outerBreakDest = m_breakDest; auto outerContinueDest = m_continueDest; m_breakDest = afterLoopBlock; m_continueDest = loopHeaderBlock; if (_while.isDoWhile()) _while.body().accept(*this); connectBlocks(m_currentBlock, predicate(*loopHeaderBlock)); setCurrentBlock(*loopHeaderBlock); _while.condition().accept(*this); auto condition = expr(_while.condition()); connectBlocks(m_currentBlock, predicate(*loopBodyBlock), condition); connectBlocks(m_currentBlock, predicate(*afterLoopBlock), !condition); // Loop body visit. setCurrentBlock(*loopBodyBlock); _while.body().accept(*this); m_breakDest = outerBreakDest; m_continueDest = outerContinueDest; // Back edge. connectBlocks(m_currentBlock, predicate(*loopHeaderBlock)); setCurrentBlock(*afterLoopBlock); if (m_unknownFunctionCallSeen) eraseKnowledge(); m_unknownFunctionCallSeen = unknownFunctionCallWasSeen; return false; } bool CHC::visit(ForStatement const& _for) { m_scopes.push_back(&_for); bool unknownFunctionCallWasSeen = m_unknownFunctionCallSeen; m_unknownFunctionCallSeen = false; solAssert(m_currentFunction, ""); auto const& functionBody = m_currentFunction->body(); auto loopHeaderBlock = createBlock(&_for, PredicateType::FunctionBlock, "for_header_"); auto loopBodyBlock = createBlock(&_for.body(), PredicateType::FunctionBlock, "for_body_"); auto afterLoopBlock = createBlock(&functionBody, PredicateType::FunctionBlock); auto postLoop = _for.loopExpression(); auto postLoopBlock = postLoop ? createBlock(postLoop, PredicateType::FunctionBlock, "for_post_") : nullptr; auto outerBreakDest = m_breakDest; auto outerContinueDest = m_continueDest; m_breakDest = afterLoopBlock; m_continueDest = postLoop ? postLoopBlock : loopHeaderBlock; if (auto init = _for.initializationExpression()) init->accept(*this); connectBlocks(m_currentBlock, predicate(*loopHeaderBlock)); setCurrentBlock(*loopHeaderBlock); auto condition = smtutil::Expression(true); if (auto forCondition = _for.condition()) { forCondition->accept(*this); condition = expr(*forCondition); } connectBlocks(m_currentBlock, predicate(*loopBodyBlock), condition); connectBlocks(m_currentBlock, predicate(*afterLoopBlock), !condition); // Loop body visit. setCurrentBlock(*loopBodyBlock); _for.body().accept(*this); if (postLoop) { connectBlocks(m_currentBlock, predicate(*postLoopBlock)); setCurrentBlock(*postLoopBlock); postLoop->accept(*this); } m_breakDest = outerBreakDest; m_continueDest = outerContinueDest; // Back edge. connectBlocks(m_currentBlock, predicate(*loopHeaderBlock)); setCurrentBlock(*afterLoopBlock); if (m_unknownFunctionCallSeen) eraseKnowledge(); m_unknownFunctionCallSeen = unknownFunctionCallWasSeen; return false; } void CHC::endVisit(ForStatement const& _for) { solAssert(m_scopes.back() == &_for, ""); m_scopes.pop_back(); } void CHC::endVisit(UnaryOperation const& _op) { SMTEncoder::endVisit(_op); if (auto funDef = *_op.annotation().userDefinedFunction) { std::vector<Expression const*> arguments; arguments.push_back(&_op.subExpression()); internalFunctionCall(funDef, std::nullopt, _op.userDefinedFunctionType(), arguments, state().thisAddress()); createReturnedExpressions(funDef, _op); return; } if ( _op.annotation().type->category() == Type::Category::RationalNumber || _op.annotation().type->category() == Type::Category::FixedPoint ) return; if (_op.getOperator() == Token::Sub && smt::isInteger(*_op.annotation().type)) { auto const* intType = dynamic_cast<IntegerType const*>(_op.annotation().type); if (!intType) intType = TypeProvider::uint256(); verificationTargetEncountered(&_op, VerificationTargetType::Underflow, expr(_op) < intType->minValue()); verificationTargetEncountered(&_op, VerificationTargetType::Overflow, expr(_op) > intType->maxValue()); } } void CHC::endVisit(BinaryOperation const& _op) { SMTEncoder::endVisit(_op); if (auto funDef = *_op.annotation().userDefinedFunction) { std::vector<Expression const*> arguments; arguments.push_back(&_op.leftExpression()); arguments.push_back(&_op.rightExpression()); internalFunctionCall(funDef, std::nullopt, _op.userDefinedFunctionType(), arguments, state().thisAddress()); createReturnedExpressions(funDef, _op); } } void CHC::endVisit(FunctionCall const& _funCall) { auto functionCallKind = *_funCall.annotation().kind; if (functionCallKind != FunctionCallKind::FunctionCall) { SMTEncoder::endVisit(_funCall); return; } FunctionType const& funType = dynamic_cast<FunctionType const&>(*_funCall.expression().annotation().type); switch (funType.kind()) { case FunctionType::Kind::Assert: visitAssert(_funCall); SMTEncoder::endVisit(_funCall); break; case FunctionType::Kind::Internal: internalFunctionCall(_funCall); break; case FunctionType::Kind::External: case FunctionType::Kind::BareStaticCall: case FunctionType::Kind::BareCall: externalFunctionCall(_funCall); SMTEncoder::endVisit(_funCall); break; case FunctionType::Kind::Creation: visitDeployment(_funCall); break; case FunctionType::Kind::DelegateCall: case FunctionType::Kind::BareCallCode: case FunctionType::Kind::BareDelegateCall: SMTEncoder::endVisit(_funCall); unknownFunctionCall(_funCall); break; case FunctionType::Kind::Send: case FunctionType::Kind::Transfer: { auto value = _funCall.arguments().front(); solAssert(value, ""); smtutil::Expression thisBalance = state().balance(); verificationTargetEncountered( &_funCall, VerificationTargetType::Balance, thisBalance < expr(*value) ); SMTEncoder::endVisit(_funCall); break; } case FunctionType::Kind::KECCAK256: case FunctionType::Kind::ECRecover: case FunctionType::Kind::SHA256: case FunctionType::Kind::RIPEMD160: case FunctionType::Kind::BlockHash: case FunctionType::Kind::AddMod: case FunctionType::Kind::MulMod: case FunctionType::Kind::Unwrap: case FunctionType::Kind::Wrap: [[fallthrough]]; default: SMTEncoder::endVisit(_funCall); break; } auto funDef = functionCallToDefinition(_funCall, currentScopeContract(), m_currentContract); createReturnedExpressions(funDef, _funCall); } void CHC::endVisit(Break const& _break) { solAssert(m_breakDest, ""); connectBlocks(m_currentBlock, predicate(*m_breakDest)); // Add an unreachable ghost node to collect unreachable statements after a break. auto breakGhost = createBlock(&_break, PredicateType::FunctionBlock, "break_ghost_"); m_currentBlock = predicate(*breakGhost); } void CHC::endVisit(Continue const& _continue) { solAssert(m_continueDest, ""); connectBlocks(m_currentBlock, predicate(*m_continueDest)); // Add an unreachable ghost node to collect unreachable statements after a continue. auto continueGhost = createBlock(&_continue, PredicateType::FunctionBlock, "continue_ghost_"); m_currentBlock = predicate(*continueGhost); } void CHC::endVisit(IndexRangeAccess const& _range) { createExpr(_range); auto baseArray = std::dynamic_pointer_cast<SymbolicArrayVariable>(m_context.expression(_range.baseExpression())); auto sliceArray = std::dynamic_pointer_cast<SymbolicArrayVariable>(m_context.expression(_range)); solAssert(baseArray && sliceArray, ""); auto const& sliceData = ArraySlicePredicate::create(sliceArray->sort(), m_context); if (!sliceData.first) { for (auto pred: sliceData.second.predicates) m_interface->registerRelation(pred->functor()); for (auto const& rule: sliceData.second.rules) addRule(rule, ""); } auto start = _range.startExpression() ? expr(*_range.startExpression()) : 0; auto end = _range.endExpression() ? expr(*_range.endExpression()) : baseArray->length(); auto slicePred = (*sliceData.second.predicates.at(0))({ baseArray->elements(), sliceArray->elements(), start, end }); m_context.addAssertion(slicePred); m_context.addAssertion(sliceArray->length() == end - start); } void CHC::endVisit(Return const& _return) { SMTEncoder::endVisit(_return); connectBlocks(m_currentBlock, predicate(*m_returnDests.back())); // Add an unreachable ghost node to collect unreachable statements after a return. auto returnGhost = createBlock(&_return, PredicateType::FunctionBlock, "return_ghost_"); m_currentBlock = predicate(*returnGhost); } bool CHC::visit(TryCatchClause const& _tryStatement) { m_scopes.push_back(&_tryStatement); return SMTEncoder::visit(_tryStatement); } void CHC::endVisit(TryCatchClause const& _tryStatement) { solAssert(m_scopes.back() == &_tryStatement, ""); m_scopes.pop_back(); } bool CHC::visit(TryStatement const& _tryStatement) { FunctionCall const* externalCall = dynamic_cast<FunctionCall const*>(&_tryStatement.externalCall()); solAssert(externalCall && externalCall->annotation().tryCall, ""); solAssert(m_currentFunction, ""); auto tryHeaderBlock = createBlock(&_tryStatement, PredicateType::FunctionBlock, "try_header_"); auto afterTryBlock = createBlock(&m_currentFunction->body(), PredicateType::FunctionBlock); auto const& clauses = _tryStatement.clauses(); solAssert(clauses[0].get() == _tryStatement.successClause(), "First clause of TryStatement should be the success clause"); auto clauseBlocks = applyMap(clauses, [this](ASTPointer<TryCatchClause> clause) { return createBlock(clause.get(), PredicateType::FunctionBlock, "try_clause_" + std::to_string(clause->id())); }); connectBlocks(m_currentBlock, predicate(*tryHeaderBlock)); setCurrentBlock(*tryHeaderBlock); // Visit everything, except the actual external call. externalCall->expression().accept(*this); ASTNode::listAccept(externalCall->arguments(), *this); // Branch directly to all catch clauses, since in these cases, any effects of the external call are reverted. for (size_t i = 1; i < clauseBlocks.size(); ++i) connectBlocks(m_currentBlock, predicate(*clauseBlocks[i])); // Only now visit the actual call to record its effects and connect to the success clause. endVisit(*externalCall); if (_tryStatement.successClause()->parameters()) expressionToTupleAssignment(_tryStatement.successClause()->parameters()->parameters(), *externalCall); connectBlocks(m_currentBlock, predicate(*clauseBlocks[0])); for (size_t i = 0; i < clauses.size(); ++i) { setCurrentBlock(*clauseBlocks[i]); clauses[i]->accept(*this); connectBlocks(m_currentBlock, predicate(*afterTryBlock)); } setCurrentBlock(*afterTryBlock); return false; } void CHC::pushInlineFrame(CallableDeclaration const& _callable) { m_returnDests.push_back(createBlock(&_callable, PredicateType::FunctionBlock, "return_")); } void CHC::popInlineFrame(CallableDeclaration const& _callable) { solAssert(!m_returnDests.empty(), ""); auto const& ret = *m_returnDests.back(); solAssert(ret.programNode() == &_callable, ""); connectBlocks(m_currentBlock, predicate(ret)); setCurrentBlock(ret); m_returnDests.pop_back(); } void CHC::visitAssert(FunctionCall const& _funCall) { auto const& args = _funCall.arguments(); solAssert(args.size() == 1, ""); solAssert(args.front()->annotation().type->category() == Type::Category::Bool, ""); solAssert(m_currentContract, ""); solAssert(m_currentFunction, ""); auto errorCondition = !m_context.expression(*args.front())->currentValue(); verificationTargetEncountered(&_funCall, VerificationTargetType::Assert, errorCondition); } void CHC::visitPublicGetter(FunctionCall const& _funCall) { createExpr(_funCall); if (encodeExternalCallsAsTrusted()) { auto const& access = dynamic_cast<MemberAccess const&>(_funCall.expression()); auto const& contractType = dynamic_cast<ContractType const&>(*access.expression().annotation().type); state().writeStateVars(*m_currentContract, state().thisAddress()); state().readStateVars(contractType.contractDefinition(), expr(access.expression())); } SMTEncoder::visitPublicGetter(_funCall); } void CHC::visitAddMulMod(FunctionCall const& _funCall) { solAssert(_funCall.arguments().at(2), ""); verificationTargetEncountered(&_funCall, VerificationTargetType::DivByZero, expr(*_funCall.arguments().at(2)) == 0); SMTEncoder::visitAddMulMod(_funCall); } void CHC::visitDeployment(FunctionCall const& _funCall) { if (!encodeExternalCallsAsTrusted()) { SMTEncoder::endVisit(_funCall); unknownFunctionCall(_funCall); return; } auto [callExpr, callOptions] = functionCallExpression(_funCall); auto funType = dynamic_cast<FunctionType const*>(callExpr->annotation().type); ContractDefinition const* contract = &dynamic_cast<ContractType const&>(*funType->returnParameterTypes().front()).contractDefinition(); // copy state variables from m_currentContract to state.storage. state().writeStateVars(*m_currentContract, state().thisAddress()); errorFlag().increaseIndex(); Expression const* value = valueOption(callOptions); if (value) decreaseBalanceFromOptionsValue(*value); auto originalTx = state().tx(); newTxConstraints(value); auto prevThisAddr = state().thisAddress(); auto newAddr = state().newThisAddress(); if (auto constructor = contract->constructor()) { auto const& args = _funCall.sortedArguments(); auto const& params = constructor->parameters(); solAssert(args.size() == params.size(), ""); for (auto [arg, param]: ranges::zip_view(args, params)) m_context.addAssertion(expr(*arg) == m_context.variable(*param)->currentValue()); } for (auto var: stateVariablesIncludingInheritedAndPrivate(*contract)) m_context.variable(*var)->increaseIndex(); Predicate const& constructorSummary = *m_constructorSummaries.at(contract); m_context.addAssertion(smt::constructorCall(constructorSummary, m_context, false)); solAssert(m_errorDest, ""); connectBlocks( m_currentBlock, predicate(*m_errorDest), errorFlag().currentValue() > 0 ); m_context.addAssertion(errorFlag().currentValue() == 0); m_context.addAssertion(state().newThisAddress() == prevThisAddr); // copy state variables from state.storage to m_currentContract. state().readStateVars(*m_currentContract, state().thisAddress()); state().newTx(); m_context.addAssertion(originalTx == state().tx()); defineExpr(_funCall, newAddr); } void CHC::internalFunctionCall( FunctionDefinition const* _funDef, std::optional<Expression const*> _boundArgumentCall, FunctionType const* _funType, std::vector<Expression const*> const& _arguments, smtutil::Expression _contractAddressValue ) { solAssert(m_currentContract, ""); solAssert(_funType, ""); if (_funDef) { if (m_currentFunction && !m_currentFunction->isConstructor()) m_callGraph[m_currentFunction].insert(_funDef); else m_callGraph[m_currentContract].insert(_funDef); } m_context.addAssertion(predicate(_funDef, _boundArgumentCall, _funType, _arguments, _contractAddressValue)); solAssert(m_errorDest, ""); connectBlocks( m_currentBlock, predicate(*m_errorDest), errorFlag().currentValue() > 0 && currentPathConditions() ); m_context.addAssertion(smtutil::Expression::implies(currentPathConditions(), errorFlag().currentValue() == 0)); m_context.addAssertion(errorFlag().increaseIndex() == 0); } void CHC::internalFunctionCall(FunctionCall const& _funCall) { solAssert(m_currentContract, ""); auto funDef = functionCallToDefinition(_funCall, currentScopeContract(), m_currentContract); if (funDef) { if (m_currentFunction && !m_currentFunction->isConstructor()) m_callGraph[m_currentFunction].insert(funDef); else m_callGraph[m_currentContract].insert(funDef); } Expression const* calledExpr = &_funCall.expression(); auto funType = dynamic_cast<FunctionType const*>(calledExpr->annotation().type); auto contractAddressValue = [this](FunctionCall const& _f) { auto [callExpr, callOptions] = functionCallExpression(_f); FunctionType const& funType = dynamic_cast<FunctionType const&>(*callExpr->annotation().type); if (funType.kind() == FunctionType::Kind::Internal) return state().thisAddress(); if (MemberAccess const* callBase = dynamic_cast<MemberAccess const*>(callExpr)) return expr(callBase->expression()); solAssert(false, "Unreachable!"); }; std::vector<Expression const*> arguments; for (auto& arg: _funCall.sortedArguments()) arguments.push_back(&(*arg)); std::optional<Expression const*> boundArgumentCall = funType->hasBoundFirstArgument() ? std::make_optional(calledExpr) : std::nullopt; internalFunctionCall(funDef, boundArgumentCall, funType, arguments, contractAddressValue(_funCall)); } void CHC::addNondetCalls(ContractDefinition const& _contract) { for (auto var: _contract.stateVariables()) if (auto contractType = dynamic_cast<ContractType const*>(var->type())) { auto const& symbVar = m_context.variable(*var); m_context.addAssertion(symbVar->currentValue() == symbVar->valueAtIndex(0)); nondetCall(contractType->contractDefinition(), *var); } } void CHC::nondetCall(ContractDefinition const& _contract, VariableDeclaration const& _var) { auto address = m_context.variable(_var)->currentValue(); // Load the called contract's state variables from the global state. state().readStateVars(_contract, address); m_context.addAssertion(state().state() == state().state(0)); auto preCallState = std::vector<smtutil::Expression>{state().state()} + currentStateVariables(_contract); state().newState(); for (auto const* var: _contract.stateVariables()) m_context.variable(*var)->increaseIndex(); Predicate const& callPredicate = *createSymbolicBlock( nondetInterfaceSort(_contract, state()), "nondet_call_" + uniquePrefix(), PredicateType::FunctionSummary, &_var, m_currentContract ); auto postCallState = std::vector<smtutil::Expression>{state().state()} + currentStateVariables(_contract); std::vector<smtutil::Expression> stateExprs = commonStateExpressions(errorFlag().increaseIndex(), address); auto nondet = (*m_nondetInterfaces.at(&_contract))(stateExprs + preCallState + postCallState); auto nondetCall = callPredicate(stateExprs + preCallState + postCallState); addRule(smtutil::Expression::implies(nondet, nondetCall), nondetCall.name); m_context.addAssertion(nondetCall); // Load the called contract's state variables into the global state. state().writeStateVars(_contract, address); } void CHC::externalFunctionCall(FunctionCall const& _funCall) { /// In external function calls we do not add a "predicate call" /// because we do not trust their function body anyway, /// so we just add the nondet_interface predicate. solAssert(m_currentContract, ""); auto [callExpr, callOptions] = functionCallExpression(_funCall); FunctionType const& funType = dynamic_cast<FunctionType const&>(*callExpr->annotation().type); auto kind = funType.kind(); solAssert( kind == FunctionType::Kind::External || kind == FunctionType::Kind::BareCall || kind == FunctionType::Kind::BareStaticCall, "" ); // Only consider high level external calls in trusted mode. if ( kind == FunctionType::Kind::External && (encodeExternalCallsAsTrusted() || isExternalCallToThis(callExpr)) ) { externalFunctionCallToTrustedCode(_funCall); return; } // Low level calls are still encoded nondeterministically. auto function = functionCallToDefinition(_funCall, currentScopeContract(), m_currentContract); if (function) for (auto var: function->returnParameters()) m_context.variable(*var)->increaseIndex(); // If we see a low level call in trusted mode, // we need to havoc the global state. if ( kind == FunctionType::Kind::BareCall && encodeExternalCallsAsTrusted() ) state().newStorage(); // No reentrancy from constructor calls. if (!m_currentFunction || m_currentFunction->isConstructor()) return; if (Expression const* value = valueOption(callOptions)) decreaseBalanceFromOptionsValue(*value); auto preCallState = std::vector<smtutil::Expression>{state().state()} + currentStateVariables(); if (!usesStaticCall(_funCall)) { state().newState(); for (auto const* var: m_stateVariables) m_context.variable(*var)->increaseIndex(); } Predicate const& callPredicate = *createSymbolicBlock( nondetInterfaceSort(*m_currentContract, state()), "nondet_call_" + uniquePrefix(), PredicateType::ExternalCallUntrusted, &_funCall ); auto postCallState = std::vector<smtutil::Expression>{state().state()} + currentStateVariables(); std::vector<smtutil::Expression> stateExprs = commonStateExpressions(errorFlag().increaseIndex(), state().thisAddress()); auto nondet = (*m_nondetInterfaces.at(m_currentContract))(stateExprs + preCallState + postCallState); auto nondetCall = callPredicate(stateExprs + preCallState + postCallState); addRule(smtutil::Expression::implies(nondet, nondetCall), nondetCall.name); m_context.addAssertion(nondetCall); solAssert(m_errorDest, ""); connectBlocks(m_currentBlock, predicate(*m_errorDest), errorFlag().currentValue() > 0 && currentPathConditions()); // To capture the possibility of a reentrant call, we record in the call graph that the current function // can call any of the external methods of the current contract. if (m_currentFunction) for (auto const* definedFunction: contractFunctions(*m_currentContract)) if (!definedFunction->isConstructor() && definedFunction->isPublic()) m_callGraph[m_currentFunction].insert(definedFunction); m_context.addAssertion(errorFlag().currentValue() == 0); } void CHC::externalFunctionCallToTrustedCode(FunctionCall const& _funCall) { if (publicGetter(_funCall.expression())) visitPublicGetter(_funCall); solAssert(m_currentContract, ""); auto [callExpr, callOptions] = functionCallExpression(_funCall); FunctionType const& funType = dynamic_cast<FunctionType const&>(*callExpr->annotation().type); auto kind = funType.kind(); solAssert(kind == FunctionType::Kind::External || kind == FunctionType::Kind::BareStaticCall, ""); auto function = functionCallToDefinition(_funCall, currentScopeContract(), m_currentContract); if (!function) return; // Remember the external call in the call graph to properly detect verification targets for the current function if (m_currentFunction && !m_currentFunction->isConstructor()) m_callGraph[m_currentFunction].insert(function); else m_callGraph[m_currentContract].insert(function); // External call creates a new transaction. auto originalTx = state().tx(); Expression const* value = valueOption(callOptions); newTxConstraints(value); auto calledAddress = contractAddressValue(_funCall); if (value) { decreaseBalanceFromOptionsValue(*value); state().addBalance(calledAddress, expr(*value)); } if (encodeExternalCallsAsTrusted()) { // The order here is important!! Write should go first. // Load the caller contract's state variables into the global state. state().writeStateVars(*m_currentContract, state().thisAddress()); // Load the called contract's state variables from the global state. state().readStateVars(*function->annotation().contract, contractAddressValue(_funCall)); } std::vector<Expression const*> arguments; for (auto& arg: _funCall.sortedArguments()) arguments.push_back(&(*arg)); smtutil::Expression pred = predicate(function, std::nullopt, &funType, arguments, calledAddress); auto txConstraints = state().txTypeConstraints() && state().txFunctionConstraints(*function); m_context.addAssertion(pred && txConstraints); // restore the original transaction data state().newTx(); m_context.addAssertion(originalTx == state().tx()); solAssert(m_errorDest, ""); connectBlocks( m_currentBlock, predicate(*m_errorDest), (errorFlag().currentValue() > 0) ); m_context.addAssertion(errorFlag().currentValue() == 0); if (!usesStaticCall(_funCall)) if (encodeExternalCallsAsTrusted()) { // The order here is important!! Write should go first. // Load the called contract's state variables into the global state. state().writeStateVars(*function->annotation().contract, contractAddressValue(_funCall)); // Load the caller contract's state variables from the global state. state().readStateVars(*m_currentContract, state().thisAddress()); } } void CHC::unknownFunctionCall(FunctionCall const&) { /// Function calls are not handled at the moment, /// so always erase knowledge. /// TODO remove when function calls get predicates/blocks. eraseKnowledge(); /// Used to erase outer scope knowledge in loops and ifs. /// TODO remove when function calls get predicates/blocks. m_unknownFunctionCallSeen = true; } void CHC::makeArrayPopVerificationTarget(FunctionCall const& _arrayPop) { FunctionType const& funType = dynamic_cast<FunctionType const&>(*_arrayPop.expression().annotation().type); solAssert(funType.kind() == FunctionType::Kind::ArrayPop, ""); auto memberAccess = dynamic_cast<MemberAccess const*>(cleanExpression(_arrayPop.expression())); solAssert(memberAccess, ""); auto symbArray = std::dynamic_pointer_cast<SymbolicArrayVariable>(m_context.expression(memberAccess->expression())); solAssert(symbArray, ""); verificationTargetEncountered(&_arrayPop, VerificationTargetType::PopEmptyArray, symbArray->length() <= 0); } void CHC::makeOutOfBoundsVerificationTarget(IndexAccess const& _indexAccess) { if (_indexAccess.annotation().type->category() == Type::Category::TypeType) return; auto baseType = _indexAccess.baseExpression().annotation().type; std::optional<smtutil::Expression> length; if (smt::isArray(*baseType)) length = dynamic_cast<smt::SymbolicArrayVariable const&>( *m_context.expression(_indexAccess.baseExpression()) ).length(); else if (auto const* type = dynamic_cast<FixedBytesType const*>(baseType)) length = smtutil::Expression(static_cast<size_t>(type->numBytes())); std::optional<smtutil::Expression> target; if ( auto index = _indexAccess.indexExpression(); index && length ) target = expr(*index) < 0 || expr(*index) >= *length; if (target) verificationTargetEncountered(&_indexAccess, VerificationTargetType::OutOfBounds, *target); } std::pair<smtutil::Expression, smtutil::Expression> CHC::arithmeticOperation( Token _op, smtutil::Expression const& _left, smtutil::Expression const& _right, Type const* _commonType, frontend::Expression const& _expression ) { // Unchecked does not disable div by 0 checks. if (_op == Token::Mod || _op == Token::Div) verificationTargetEncountered(&_expression, VerificationTargetType::DivByZero, _right == 0); auto values = SMTEncoder::arithmeticOperation(_op, _left, _right, _commonType, _expression); if (!m_checked) return values; IntegerType const* intType = nullptr; if (auto const* type = dynamic_cast<IntegerType const*>(_commonType)) intType = type; else intType = TypeProvider::uint256(); // Mod does not need underflow/overflow checks. // Div only needs overflow check for signed types. if (_op == Token::Mod || (_op == Token::Div && !intType->isSigned())) return values; if (_op == Token::Div) verificationTargetEncountered(&_expression, VerificationTargetType::Overflow, values.second > intType->maxValue()); else if (intType->isSigned()) { verificationTargetEncountered(&_expression, VerificationTargetType::Underflow, values.second < intType->minValue()); verificationTargetEncountered(&_expression, VerificationTargetType::Overflow, values.second > intType->maxValue()); } else if (_op == Token::Sub) verificationTargetEncountered(&_expression, VerificationTargetType::Underflow, values.second < intType->minValue()); else if (_op == Token::Add || _op == Token::Mul) verificationTargetEncountered(&_expression, VerificationTargetType::Overflow, values.second > intType->maxValue()); else solAssert(false, ""); return values; } void CHC::resetSourceAnalysis() { SMTEncoder::resetSourceAnalysis(); m_unprovedTargets.clear(); m_invariants.clear(); m_functionTargetIds.clear(); m_verificationTargets.clear(); m_queryPlaceholders.clear(); m_callGraph.clear(); m_summaries.clear(); m_externalSummaries.clear(); m_interfaces.clear(); m_nondetInterfaces.clear(); m_constructorSummaries.clear(); m_contractInitializers.clear(); Predicate::reset(); ArraySlicePredicate::reset(); m_blockCounter = 0; solAssert(m_settings.solvers.smtlib2 || m_settings.solvers.eld || m_settings.solvers.z3); if (!m_interface) { if (m_settings.solvers.z3) m_interface = std::make_unique<Z3CHCSmtLib2Interface>( m_smtCallback, m_settings.timeout, m_settings.invariants != ModelCheckerInvariants::None() ); else if (m_settings.solvers.eld) m_interface = std::make_unique<EldaricaCHCSmtLib2Interface>( m_smtCallback, m_settings.timeout, m_settings.invariants != ModelCheckerInvariants::None() ); else m_interface = std::make_unique<CHCSmtLib2Interface>(m_smtlib2Responses, m_smtCallback, m_settings.timeout); } auto smtlib2Interface = dynamic_cast<CHCSmtLib2Interface*>(m_interface.get()); solAssert(smtlib2Interface); smtlib2Interface->reset(); m_context.setSolver(smtlib2Interface); m_context.reset(); m_context.resetUniqueId(); m_context.setAssertionAccumulation(false); } void CHC::resetContractAnalysis() { m_stateVariables.clear(); m_unknownFunctionCallSeen = false; m_breakDest = nullptr; m_continueDest = nullptr; m_returnDests.clear(); errorFlag().resetIndex(); } void CHC::eraseKnowledge() { resetStorageVariables(); resetBalances(); } void CHC::clearIndices(ContractDefinition const* _contract, FunctionDefinition const* _function) { SMTEncoder::clearIndices(_contract, _function); for (auto const* var: m_stateVariables) /// SSA index 0 is reserved for state variables at the beginning /// of the current transaction. m_context.variable(*var)->increaseIndex(); if (_function) { for (auto const& var: _function->parameters() + _function->returnParameters()) m_context.variable(*var)->increaseIndex(); for (auto const& var: localVariablesIncludingModifiers(*_function, _contract)) m_context.variable(*var)->increaseIndex(); } state().newState(); } void CHC::setCurrentBlock(Predicate const& _block) { if (m_context.solverStackHeigh() > 0) m_context.popSolver(); solAssert(m_currentContract, ""); clearIndices(m_currentContract, m_currentFunction); m_context.pushSolver(); m_currentBlock = predicate(_block); } std::set<unsigned> CHC::transactionVerificationTargetsIds(ASTNode const* _txRoot) { std::set<unsigned> verificationTargetsIds; struct ASTNodeCompare: EncodingContext::IdCompare { bool operator<(ASTNodeCompare _other) const { return operator()(node, _other.node); } ASTNode const* node; }; solidity::util::BreadthFirstSearch<ASTNodeCompare>{{{{}, _txRoot}}}.run([&](auto _node, auto&& _addChild) { verificationTargetsIds.insert(m_functionTargetIds[_node.node].begin(), m_functionTargetIds[_node.node].end()); for (ASTNode const* called: m_callGraph[_node.node]) _addChild({{}, called}); }); return verificationTargetsIds; } bool CHC::usesStaticCall(FunctionDefinition const* _funDef, FunctionType const* _funType) { auto kind = _funType->kind(); return (_funDef && (_funDef->stateMutability() == StateMutability::Pure || _funDef->stateMutability() == StateMutability::View)) || kind == FunctionType::Kind::BareStaticCall; } bool CHC::usesStaticCall(FunctionCall const& _funCall) { FunctionType const& funType = dynamic_cast<FunctionType const&>(*_funCall.expression().annotation().type); auto kind = funType.kind(); auto function = functionCallToDefinition(_funCall, currentScopeContract(), m_currentContract); return (function && (function->stateMutability() == StateMutability::Pure || function->stateMutability() == StateMutability::View)) || kind == FunctionType::Kind::BareStaticCall; } std::optional<CHC::CHCNatspecOption> CHC::natspecOptionFromString(std::string const& _option) { static std::map<std::string, CHCNatspecOption> options{ {"abstract-function-nondet", CHCNatspecOption::AbstractFunctionNondet} }; if (options.count(_option)) return options.at(_option); return {}; } std::set<CHC::CHCNatspecOption> CHC::smtNatspecTags(FunctionDefinition const& _function) { std::set<CHC::CHCNatspecOption> options; std::string smtStr = "custom:smtchecker"; bool errorSeen = false; for (auto const& [tag, value]: _function.annotation().docTags) if (tag == smtStr) { std::string const& content = value.content; if (auto option = natspecOptionFromString(content)) options.insert(*option); else if (!errorSeen) { errorSeen = true; m_errorReporter.warning(3130_error, _function.location(), "Unknown option for \"" + smtStr + "\": \"" + content + "\""); } } return options; } bool CHC::abstractAsNondet(FunctionDefinition const& _function) { return smtNatspecTags(_function).count(CHCNatspecOption::AbstractFunctionNondet); } SortPointer CHC::sort(FunctionDefinition const& _function) { return functionBodySort(_function, m_currentContract, state()); } bool CHC::encodeExternalCallsAsTrusted() { return m_settings.externalCalls.isTrusted(); } SortPointer CHC::sort(ASTNode const* _node) { if (auto funDef = dynamic_cast<FunctionDefinition const*>(_node)) return sort(*funDef); solAssert(m_currentFunction, ""); return functionBodySort(*m_currentFunction, m_currentContract, state()); } Predicate const* CHC::createSymbolicBlock(SortPointer _sort, std::string const& _name, PredicateType _predType, ASTNode const* _node, ContractDefinition const* _contractContext) { auto const* block = Predicate::create(_sort, _name, _predType, m_context, _node, _contractContext, m_scopes); m_interface->registerRelation(block->functor()); return block; } void CHC::defineInterfacesAndSummaries(SourceUnit const& _source) { for (auto const& node: _source.nodes()) if (auto const* contract = dynamic_cast<ContractDefinition const*>(node.get())) { std::string suffix = contract->name() + "_" + std::to_string(contract->id()); m_interfaces[contract] = createSymbolicBlock(interfaceSort(*contract, state()), "interface_" + uniquePrefix() + "_" + suffix, PredicateType::Interface, contract, contract); m_nondetInterfaces[contract] = createSymbolicBlock(nondetInterfaceSort(*contract, state()), "nondet_interface_" + uniquePrefix() + "_" + suffix, PredicateType::NondetInterface, contract, contract); m_constructorSummaries[contract] = createConstructorBlock(*contract, "summary_constructor"); for (auto const* var: stateVariablesIncludingInheritedAndPrivate(*contract)) if (!m_context.knownVariable(*var)) createVariable(*var); /// Base nondeterministic interface that allows /// 0 steps to be taken, used as base for the inductive /// rule for each function. auto const& iface = *m_nondetInterfaces.at(contract); addRule(smtutil::Expression::implies(errorFlag().currentValue() == 0, smt::nondetInterface(iface, *contract, m_context, 0, 0)), "base_nondet"); auto const& resolved = contractFunctions(*contract); for (auto const* function: contractFunctionsWithoutVirtual(*contract) + allFreeFunctions()) { for (auto var: function->parameters()) createVariable(*var); for (auto var: function->returnParameters()) createVariable(*var); for (auto const* var: localVariablesIncludingModifiers(*function, contract)) createVariable(*var); m_summaries[contract].emplace(function, createSummaryBlock(*function, *contract)); if ( !function->isConstructor() && function->isPublic() && // Public library functions should have interfaces only for the libraries // they're declared in. (!function->libraryFunction() || (function->scope() == contract)) && resolved.count(function) ) { m_externalSummaries[contract].emplace(function, createSummaryBlock(*function, *contract)); auto state1 = stateVariablesAtIndex(1, *contract); auto state2 = stateVariablesAtIndex(2, *contract); auto errorPre = errorFlag().currentValue(); auto nondetPre = smt::nondetInterface(iface, *contract, m_context, 0, 1); auto errorPost = errorFlag().increaseIndex(); auto nondetPost = smt::nondetInterface(iface, *contract, m_context, 0, 2); std::vector<smtutil::Expression> args = commonStateExpressions(errorPost, state().thisAddress()) + std::vector<smtutil::Expression>{state().tx(), state().state(1)}; args += state1 + applyMap(function->parameters(), [this](auto _var) { return valueAtIndex(*_var, 0); }) + std::vector<smtutil::Expression>{state().state(2)} + state2 + applyMap(function->parameters(), [this](auto _var) { return valueAtIndex(*_var, 1); }) + applyMap(function->returnParameters(), [this](auto _var) { return valueAtIndex(*_var, 1); }); connectBlocks(nondetPre, nondetPost, errorPre == 0 && (*m_externalSummaries.at(contract).at(function))(args)); } } } } void CHC::defineExternalFunctionInterface(FunctionDefinition const& _function, ContractDefinition const& _contract) { // Create a rule that represents an external call to this function. // This contains more things than the function body itself, // such as balance updates because of ``msg.value``. auto functionEntryBlock = createBlock(&_function, PredicateType::FunctionBlock); auto functionPred = predicate(*functionEntryBlock); addRule(functionPred, functionPred.name); setCurrentBlock(*functionEntryBlock); m_context.addAssertion(initialConstraints(_contract, &_function)); m_context.addAssertion(state().txTypeConstraints() && state().txFunctionConstraints(_function)); // The contract may have received funds through a selfdestruct or // block.coinbase, which do not trigger calls into the contract. // So the only constraint we can add here is that the balance of // the contract grows by at least `msg.value`. SymbolicIntVariable k{TypeProvider::uint256(), TypeProvider::uint256(), "funds_" + std::to_string(m_context.newUniqueId()), m_context}; m_context.addAssertion(k.currentValue() >= state().txMember("msg.value")); // Assume that address(this).balance cannot overflow. m_context.addAssertion(smt::symbolicUnknownConstraints(state().balance(state().thisAddress()) + k.currentValue(), TypeProvider::uint256())); state().addBalance(state().thisAddress(), k.currentValue()); if (encodeExternalCallsAsTrusted()) { // If the contract has state variables that are addresses to other contracts, // we need to encode the fact that those contracts may have been called in between // transactions to _contract. // // We do that by adding nondet_interface constraints for those contracts, // in the last line of this if block. // // If there are state variables of container types like structs or arrays // that indirectly contain contract types, we havoc the state for simplicity, // in the first part of this block. // TODO: This could actually be supported. // For structs: simply collect the SMT expressions of all the indirect contract type members. // For arrays: more involved, needs to traverse the array symbolically and do the same for each contract. // For mappings: way more complicated if the element type is a contract. auto hasContractOrAddressSubType = [&](VariableDeclaration const* _var) -> bool { bool foundContract = false; solidity::util::BreadthFirstSearch<Type const*> bfs{{_var->type()}}; bfs.run([&](auto _type, auto&& _addChild) { if ( _type->category() == Type::Category::Address || _type->category() == Type::Category::Contract ) { foundContract = true; bfs.abort(); } if (auto const* mapType = dynamic_cast<MappingType const*>(_type)) _addChild(mapType->valueType()); else if (auto const* arrayType = dynamic_cast<ArrayType const*>(_type)) _addChild(arrayType->baseType()); else if (auto const* structType = dynamic_cast<StructType const*>(_type)) for (auto const& member: structType->nativeMembers(nullptr)) _addChild(member.type); }); return foundContract; }; bool found = false; for (auto var: m_currentContract->stateVariables()) if ( var->type()->category() != Type::Category::Address && var->type()->category() != Type::Category::Contract && hasContractOrAddressSubType(var) ) { found = true; break; } if (found) state().newStorage(); else addNondetCalls(*m_currentContract); } errorFlag().increaseIndex(); m_context.addAssertion(summaryCall(_function)); connectBlocks(functionPred, externalSummary(_function)); } void CHC::defineContractInitializer(ContractDefinition const& _contract, ContractDefinition const& _contextContract) { m_contractInitializers[&_contextContract][&_contract] = createConstructorBlock(_contract, "contract_initializer"); auto const& implicitConstructorPredicate = *createConstructorBlock(_contract, "contract_initializer_entry"); auto implicitFact = smt::constructor(implicitConstructorPredicate, m_context); addRule(smtutil::Expression::implies(initialConstraints(_contract), implicitFact), implicitFact.name); setCurrentBlock(implicitConstructorPredicate); auto prevErrorDest = m_errorDest; m_errorDest = m_contractInitializers.at(&_contextContract).at(&_contract); for (auto var: _contract.stateVariables()) if (var->value()) { var->value()->accept(*this); assignment(*var, *var->value()); } m_errorDest = prevErrorDest; auto const& afterInit = *createConstructorBlock(_contract, "contract_initializer_after_init"); connectBlocks(m_currentBlock, predicate(afterInit)); setCurrentBlock(afterInit); if (auto constructor = _contract.constructor()) { errorFlag().increaseIndex(); m_context.addAssertion(smt::functionCall(*m_summaries.at(&_contextContract).at(constructor), &_contextContract, m_context)); connectBlocks(m_currentBlock, initializer(_contract, _contextContract), errorFlag().currentValue() > 0); m_context.addAssertion(errorFlag().currentValue() == 0); } connectBlocks(m_currentBlock, initializer(_contract, _contextContract)); } smtutil::Expression CHC::interface() { solAssert(m_currentContract, ""); return interface(*m_currentContract); } smtutil::Expression CHC::interface(ContractDefinition const& _contract) { return ::interface(*m_interfaces.at(&_contract), _contract, m_context); } smtutil::Expression CHC::error() { return (*m_errorPredicate)({}); } smtutil::Expression CHC::initializer(ContractDefinition const& _contract, ContractDefinition const& _contractContext) { return predicate(*m_contractInitializers.at(&_contractContext).at(&_contract)); } smtutil::Expression CHC::summary(ContractDefinition const& _contract) { return predicate(*m_constructorSummaries.at(&_contract)); } smtutil::Expression CHC::summary(FunctionDefinition const& _function, ContractDefinition const& _contract) { return smt::function(*m_summaries.at(&_contract).at(&_function), &_contract, m_context); } smtutil::Expression CHC::summary(FunctionDefinition const& _function) { solAssert(m_currentContract, ""); return summary(_function, *m_currentContract); } smtutil::Expression CHC::summaryCall(FunctionDefinition const& _function, ContractDefinition const& _contract) { return smt::functionCall(*m_summaries.at(&_contract).at(&_function), &_contract, m_context); } smtutil::Expression CHC::summaryCall(FunctionDefinition const& _function) { solAssert(m_currentContract, ""); return summaryCall(_function, *m_currentContract); } smtutil::Expression CHC::externalSummary(FunctionDefinition const& _function, ContractDefinition const& _contract) { return smt::function(*m_externalSummaries.at(&_contract).at(&_function), &_contract, m_context); } smtutil::Expression CHC::externalSummary(FunctionDefinition const& _function) { solAssert(m_currentContract, ""); return externalSummary(_function, *m_currentContract); } Predicate const* CHC::createBlock(ASTNode const* _node, PredicateType _predType, std::string const& _prefix) { auto block = createSymbolicBlock( sort(_node), "block_" + uniquePrefix() + "_" + _prefix + predicateName(_node), _predType, _node, m_currentContract ); solAssert(m_currentFunction, ""); return block; } Predicate const* CHC::createSummaryBlock(FunctionDefinition const& _function, ContractDefinition const& _contract, PredicateType _type) { return createSymbolicBlock( functionSort(_function, &_contract, state()), "summary_" + uniquePrefix() + "_" + predicateName(&_function, &_contract), _type, &_function, &_contract ); } Predicate const* CHC::createConstructorBlock(ContractDefinition const& _contract, std::string const& _prefix) { return createSymbolicBlock( constructorSort(_contract, state()), _prefix + "_" + uniquePrefix() + "_" + contractSuffix(_contract), PredicateType::ConstructorSummary, &_contract, &_contract ); } void CHC::createErrorBlock() { m_errorPredicate = createSymbolicBlock( arity0FunctionSort(), "error_target_" + std::to_string(m_context.newUniqueId()), PredicateType::Error ); } void CHC::connectBlocks(smtutil::Expression const& _from, smtutil::Expression const& _to, smtutil::Expression const& _constraints) { smtutil::Expression edge = smtutil::Expression::implies( _from && m_context.assertions() && _constraints, _to ); addRule(edge, _from.name + "_to_" + _to.name); } smtutil::Expression CHC::initialConstraints(ContractDefinition const& _contract, FunctionDefinition const* _function) { smtutil::Expression conj = state().state() == state().state(0); conj = conj && errorFlag().currentValue() == 0; conj = conj && currentEqualInitialVarsConstraints(stateVariablesIncludingInheritedAndPrivate(_contract)); FunctionDefinition const* function = _function ? _function : _contract.constructor(); if (function) conj = conj && currentEqualInitialVarsConstraints(applyMap(function->parameters(), [](auto&& _var) -> VariableDeclaration const* { return _var.get(); })); return conj; } std::vector<smtutil::Expression> CHC::initialStateVariables() { return stateVariablesAtIndex(0); } std::vector<smtutil::Expression> CHC::stateVariablesAtIndex(unsigned _index) { solAssert(m_currentContract, ""); return stateVariablesAtIndex(_index, *m_currentContract); } std::vector<smtutil::Expression> CHC::stateVariablesAtIndex(unsigned _index, ContractDefinition const& _contract) { return applyMap( SMTEncoder::stateVariablesIncludingInheritedAndPrivate(_contract), [&](auto _var) { return valueAtIndex(*_var, _index); } ); } std::vector<smtutil::Expression> CHC::currentStateVariables() { solAssert(m_currentContract, ""); return currentStateVariables(*m_currentContract); } std::vector<smtutil::Expression> CHC::currentStateVariables(ContractDefinition const& _contract) { return applyMap(SMTEncoder::stateVariablesIncludingInheritedAndPrivate(_contract), [this](auto _var) { return currentValue(*_var); }); } smtutil::Expression CHC::currentEqualInitialVarsConstraints(std::vector<VariableDeclaration const*> const& _vars) const { return fold(_vars, smtutil::Expression(true), [this](auto&& _conj, auto _var) { return std::move(_conj) && currentValue(*_var) == m_context.variable(*_var)->valueAtIndex(0); }); } std::string CHC::predicateName(ASTNode const* _node, ContractDefinition const* _contract) { std::string prefix; if (auto funDef = dynamic_cast<FunctionDefinition const*>(_node)) { prefix += TokenTraits::toString(funDef->kind()); if (!funDef->name().empty()) prefix += "_" + funDef->name() + "_"; } else if (m_currentFunction && !m_currentFunction->name().empty()) prefix += m_currentFunction->name(); auto contract = _contract ? _contract : m_currentContract; solAssert(contract, ""); return prefix + "_" + std::to_string(_node->id()) + "_" + std::to_string(contract->id()); } smtutil::Expression CHC::predicate(Predicate const& _block) { switch (_block.type()) { case PredicateType::Interface: solAssert(m_currentContract, ""); return ::interface(_block, *m_currentContract, m_context); case PredicateType::ConstructorSummary: return constructor(_block, m_context); case PredicateType::FunctionSummary: case PredicateType::InternalCall: case PredicateType::ExternalCallTrusted: case PredicateType::ExternalCallUntrusted: return smt::function(_block, m_currentContract, m_context); case PredicateType::FunctionBlock: case PredicateType::FunctionErrorBlock: solAssert(m_currentFunction, ""); return functionBlock(_block, *m_currentFunction, m_currentContract, m_context); case PredicateType::Error: return _block({}); case PredicateType::NondetInterface: // Nondeterministic interface predicates are handled differently. solAssert(false, ""); case PredicateType::Custom: // Custom rules are handled separately. solAssert(false, ""); } solAssert(false, ""); } smtutil::Expression CHC::predicate( FunctionDefinition const* _funDef, std::optional<Expression const*> _boundArgumentCall, FunctionType const* _funType, std::vector<Expression const*> _arguments, smtutil::Expression _contractAddressValue ) { solAssert(_funType, ""); auto kind = _funType->kind(); solAssert(kind == FunctionType::Kind::Internal || kind == FunctionType::Kind::External || kind == FunctionType::Kind::BareStaticCall, ""); if (!_funDef) return smtutil::Expression(true); errorFlag().increaseIndex(); std::vector<smtutil::Expression> args = commonStateExpressions(errorFlag().currentValue(), _contractAddressValue) + std::vector<smtutil::Expression>{state().tx(), state().state()}; auto const* contract = _funDef->annotation().contract; auto const& hierarchy = m_currentContract->annotation().linearizedBaseContracts; solAssert(kind != FunctionType::Kind::Internal || _funDef->isFree() || (contract && contract->isLibrary()) || util::contains(hierarchy, contract), ""); if (kind == FunctionType::Kind::Internal) contract = m_currentContract; args += currentStateVariables(*contract); args += symbolicArguments(_funDef->parameters(), _arguments, _boundArgumentCall); if (!usesStaticCall(_funDef, _funType)) { state().newState(); for (auto const& var: stateVariablesIncludingInheritedAndPrivate(*contract)) m_context.variable(*var)->increaseIndex(); } args += std::vector<smtutil::Expression>{state().state()}; args += currentStateVariables(*contract); for (auto var: _funDef->parameters() + _funDef->returnParameters()) { if (m_context.knownVariable(*var)) m_context.variable(*var)->increaseIndex(); else createVariable(*var); args.push_back(currentValue(*var)); } Predicate const& summary = *m_summaries.at(contract).at(_funDef); auto from = smt::function(summary, contract, m_context); Predicate const& callPredicate = *createSummaryBlock( *_funDef, *contract, kind == FunctionType::Kind::Internal ? PredicateType::InternalCall : PredicateType::ExternalCallTrusted ); auto to = smt::function(callPredicate, contract, m_context); addRule(smtutil::Expression::implies(from, to), to.name); return callPredicate(args); } void CHC::addRule(smtutil::Expression const& _rule, std::string const& _ruleName) { m_interface->addRule(_rule, _ruleName); } CHCSolverInterface::QueryResult CHC::query(smtutil::Expression const& _query, langutil::SourceLocation const& _location) { if (m_settings.printQuery) { auto smtLibInterface = dynamic_cast<CHCSmtLib2Interface*>(m_interface.get()); solAssert(smtLibInterface, "Requested to print queries but CHCSmtLib2Interface not available"); std::string smtLibCode = smtLibInterface->dumpQuery(_query); m_errorReporter.info( 2339_error, "CHC: Requested query:\n" + smtLibCode ); } auto result = m_interface->query(_query); switch (result.answer) { case CheckResult::SATISFIABLE: case CheckResult::UNSATISFIABLE: case CheckResult::UNKNOWN: break; case CheckResult::CONFLICTING: m_errorReporter.warning(1988_error, _location, "CHC: At least two SMT solvers provided conflicting answers. Results might not be sound."); break; case CheckResult::ERROR: m_errorReporter.warning(1218_error, _location, "CHC: Error during interaction with the solver."); break; } return result; } void CHC::verificationTargetEncountered( ASTNode const* const _errorNode, VerificationTargetType _type, smtutil::Expression const& _errorCondition ) { if (!m_settings.targets.has(_type)) return; if (!(m_currentContract || m_currentFunction)) return; bool scopeIsFunction = m_currentFunction && !m_currentFunction->isConstructor(); auto errorId = newErrorId(); solAssert(m_verificationTargets.count(errorId) == 0, "Error ID is not unique!"); m_verificationTargets.emplace(errorId, CHCVerificationTarget{{_type, _errorCondition, smtutil::Expression(true)}, errorId, _errorNode}); if (scopeIsFunction) m_functionTargetIds[m_currentFunction].push_back(errorId); else m_functionTargetIds[m_currentContract].push_back(errorId); auto previousError = errorFlag().currentValue(); errorFlag().increaseIndex(); auto extendedErrorCondition = currentPathConditions() && _errorCondition; Predicate const* localBlock = m_currentFunction ? createBlock(m_currentFunction, PredicateType::FunctionErrorBlock) : createConstructorBlock(*m_currentContract, "local_error"); auto pred = predicate(*localBlock); connectBlocks( m_currentBlock, pred, extendedErrorCondition && errorFlag().currentValue() == errorId ); solAssert(m_errorDest, ""); addRule(smtutil::Expression::implies(pred, predicate(*m_errorDest)), pred.name); m_context.addAssertion(errorFlag().currentValue() == previousError); } std::pair<std::string, ErrorId> CHC::targetDescription(CHCVerificationTarget const& _target) { if (_target.type == VerificationTargetType::PopEmptyArray) { solAssert(dynamic_cast<FunctionCall const*>(_target.errorNode), ""); return {"Empty array \"pop\"", 2529_error}; } else if (_target.type == VerificationTargetType::OutOfBounds) { solAssert(dynamic_cast<IndexAccess const*>(_target.errorNode), ""); return {"Out of bounds access", 6368_error}; } else if ( _target.type == VerificationTargetType::Underflow || _target.type == VerificationTargetType::Overflow ) { auto const* expr = dynamic_cast<Expression const*>(_target.errorNode); solAssert(expr, ""); auto const* intType = dynamic_cast<IntegerType const*>(expr->annotation().type); if (!intType) intType = TypeProvider::uint256(); if (_target.type == VerificationTargetType::Underflow) return { "Underflow (resulting value less than " + formatNumberReadable(intType->minValue()) + ")", 3944_error }; return { "Overflow (resulting value larger than " + formatNumberReadable(intType->maxValue()) + ")", 4984_error }; } else if (_target.type == VerificationTargetType::DivByZero) return {"Division by zero", 4281_error}; else if (_target.type == VerificationTargetType::Assert) return {"Assertion violation", 6328_error}; else if (_target.type == VerificationTargetType::Balance) return {"Insufficient funds", 8656_error}; else solAssert(false); } void CHC::checkVerificationTargets() { // The verification conditions have been collected per function where they have been encountered (m_verificationTargets). // Also, all possible contexts in which an external function can be called has been recorded (m_queryPlaceholders). // Here we combine every context in which an external function can be called with all possible verification conditions // in its call graph. Each such combination forms a unique verification target. std::map<unsigned, std::vector<CHCQueryPlaceholder>> targetEntryPoints; for (auto const& [function, placeholders]: m_queryPlaceholders) { auto functionTargets = transactionVerificationTargetsIds(function); for (auto const& placeholder: placeholders) for (unsigned id: functionTargets) targetEntryPoints[id].push_back(placeholder); } std::set<unsigned> checkedErrorIds; for (auto const& [targetId, placeholders]: targetEntryPoints) { auto const& target = m_verificationTargets.at(targetId); auto [errorType, errorReporterId] = targetDescription(target); checkAndReportTarget(target, placeholders, errorReporterId, errorType + " happens here.", errorType + " might happen here."); checkedErrorIds.insert(target.errorId); } auto toReport = m_unsafeTargets; if (m_settings.showUnproved) for (auto const& [node, targets]: m_unprovedTargets) for (auto const& [target, info]: targets) toReport[node].emplace(target, info); for (auto const& [node, targets]: toReport) for (auto const& [target, info]: targets) m_errorReporter.warning( info.error, info.location, info.message ); if (!m_settings.showUnproved && !m_unprovedTargets.empty()) m_errorReporter.warning( 5840_error, {}, "CHC: " + std::to_string(m_unprovedTargets.size()) + " verification condition(s) could not be proved." + " Enable the model checker option \"show unproved\" to see all of them." + " Consider choosing a specific contract to be verified in order to reduce the solving problems." + " Consider increasing the timeout per query." ); if (!m_settings.showProvedSafe && !m_safeTargets.empty()) { std::size_t provedSafeNum = 0; for (auto&& [_, targets]: m_safeTargets) provedSafeNum += targets.size(); m_errorReporter.info( 1391_error, "CHC: " + std::to_string(provedSafeNum) + " verification condition(s) proved safe!" + " Enable the model checker option \"show proved safe\" to see all of them." ); } else if (m_settings.showProvedSafe) for (auto const& [node, targets]: m_safeTargets) for (auto const& target: targets) m_provedSafeReporter.info( 9576_error, node->location(), "CHC: " + targetDescription(target).first + " check is safe!" ); if (!m_settings.invariants.invariants.empty()) { std::string msg; for (auto pred: m_invariants | ranges::views::keys) { ASTNode const* node = pred->programNode(); std::string what; if (auto contract = dynamic_cast<ContractDefinition const*>(node)) what = contract->fullyQualifiedName(); else solAssert(false, ""); std::string invType; if (pred->type() == PredicateType::Interface) invType = "Contract invariant(s)"; else if (pred->type() == PredicateType::NondetInterface) invType = "Reentrancy property(ies)"; else solAssert(false, ""); msg += invType + " for " + what + ":\n"; for (auto const& inv: m_invariants.at(pred)) msg += inv + "\n"; } if (msg.find("<errorCode>") != std::string::npos) { std::set<unsigned> seenErrors; msg += "<errorCode> = 0 -> no errors\n"; for (auto const& [id, target]: m_verificationTargets) if (!seenErrors.count(target.errorId)) { seenErrors.insert(target.errorId); std::string loc = std::string(m_charStreamProvider.charStream(*target.errorNode->location().sourceName).text(target.errorNode->location())); msg += "<errorCode> = " + std::to_string(target.errorId) + " -> " + ModelCheckerTargets::targetTypeToString.at(target.type) + " at " + loc + "\n"; } } if (!msg.empty()) m_errorReporter.info(1180_error, msg); } // There can be targets in internal functions that are not reachable from the external interface. // These are safe by definition and are not even checked by the CHC engine, but this information // must still be reported safe by the BMC engine. std::set<unsigned> allErrorIds; for (auto const& entry: m_functionTargetIds) for (unsigned id: entry.second) allErrorIds.insert(id); std::set<unsigned> unreachableErrorIds; set_difference( allErrorIds.begin(), allErrorIds.end(), checkedErrorIds.begin(), checkedErrorIds.end(), inserter(unreachableErrorIds, unreachableErrorIds.begin()) ); for (auto id: unreachableErrorIds) m_safeTargets[m_verificationTargets.at(id).errorNode].insert(m_verificationTargets.at(id)); } void CHC::checkAndReportTarget( CHCVerificationTarget const& _target, std::vector<CHCQueryPlaceholder> const& _placeholders, ErrorId _errorReporterId, std::string _satMsg, std::string _unknownMsg ) { if (m_unsafeTargets.count(_target.errorNode) && m_unsafeTargets.at(_target.errorNode).count(_target.type)) return; createErrorBlock(); for (auto const& placeholder: _placeholders) connectBlocks( placeholder.fromPredicate, error(), placeholder.constraints && placeholder.errorExpression == _target.errorId ); auto const& location = _target.errorNode->location(); auto [result, invariant, model] = query(error(), location); if (result == CheckResult::UNSATISFIABLE) { m_safeTargets[_target.errorNode].insert(_target); std::set<Predicate const*> predicates; for (auto const* pred: m_interfaces | ranges::views::values) predicates.insert(pred); for (auto const* pred: m_nondetInterfaces | ranges::views::values) predicates.insert(pred); std::map<Predicate const*, std::set<std::string>> invariants = collectInvariants(invariant, predicates, m_settings.invariants); for (auto pred: invariants | ranges::views::keys) m_invariants[pred] += std::move(invariants.at(pred)); } else if (result == CheckResult::SATISFIABLE) { solAssert(!_satMsg.empty(), ""); auto cex = generateCounterexample(model, error().name); if (cex) m_unsafeTargets[_target.errorNode][_target.type] = { _errorReporterId, location, "CHC: " + _satMsg + "\nCounterexample:\n" + *cex }; else m_unsafeTargets[_target.errorNode][_target.type] = { _errorReporterId, location, "CHC: " + _satMsg }; } else if (!_unknownMsg.empty()) m_unprovedTargets[_target.errorNode][_target.type] = { _errorReporterId, location, "CHC: " + _unknownMsg }; } /** The counterexample DAG has the following properties: 1) The root node represents the reachable error predicate. 2) The root node has 1 or 2 children: - One of them is the summary of the function that was called and led to that node. If this is the only child, this function must be the constructor. - If it has 2 children, the function is not the constructor and the other child is the interface node, that is, it represents the state of the contract before the function described above was called. 3) Interface nodes also have property 2. We run a BFS on the DAG from the root node collecting the reachable function summaries from the given node. When a function summary is seen, the search continues with that summary as the new root for its subgraph. The result of the search is a callgraph containing: - Functions calls needed to reach the root node, that is, transaction entry points. - Functions called by other functions (internal calls or external calls/internal transactions). The BFS visit order and the shape of the DAG described in the previous paragraph guarantee that the order of the function summaries in the callgraph of the error node is the reverse transaction trace. The first function summary seen contains the values for the state, input and output variables at the error point. */ std::optional<std::string> CHC::generateCounterexample(CHCSolverInterface::CexGraph const& _graph, std::string const& _root) { std::optional<unsigned> rootId; for (auto const& [id, node]: _graph.nodes) if (node.name == _root) { rootId = id; break; } if (!rootId) return {}; std::vector<std::string> path; std::string localState; auto callGraph = summaryCalls(_graph, *rootId); auto nodePred = [&](auto _node) { return Predicate::predicate(_graph.nodes.at(_node).name); }; auto nodeArgs = [&](auto _node) { return _graph.nodes.at(_node).arguments; }; bool first = true; for (auto summaryId: callGraph.at(*rootId)) { CHCSolverInterface::CexNode const& summaryNode = _graph.nodes.at(summaryId); Predicate const* summaryPredicate = Predicate::predicate(summaryNode.name); auto const& summaryArgs = summaryNode.arguments; if (!summaryPredicate->programVariable()) { auto stateVars = summaryPredicate->stateVariables(); solAssert(stateVars.has_value(), ""); auto stateValues = summaryPredicate->summaryStateValues(summaryArgs); solAssert(stateValues.size() == stateVars->size(), ""); if (first) { first = false; /// Generate counterexample message local to the failed target. localState = formatVariableModel(*stateVars, stateValues, ", ") + "\n"; if (auto calledFun = summaryPredicate->programFunction()) { auto inValues = summaryPredicate->summaryPostInputValues(summaryArgs); auto const& inParams = calledFun->parameters(); if (auto inStr = formatVariableModel(inParams, inValues, "\n"); !inStr.empty()) localState += inStr + "\n"; auto outValues = summaryPredicate->summaryPostOutputValues(summaryArgs); auto const& outParams = calledFun->returnParameters(); if (auto outStr = formatVariableModel(outParams, outValues, "\n"); !outStr.empty()) localState += outStr + "\n"; std::optional<unsigned> localErrorId; solidity::util::BreadthFirstSearch<unsigned> bfs{{summaryId}}; bfs.run([&](auto _nodeId, auto&& _addChild) { auto const& children = _graph.edges.at(_nodeId); if ( children.size() == 1 && nodePred(children.front())->isFunctionErrorBlock() ) { localErrorId = children.front(); bfs.abort(); } ranges::for_each(children, _addChild); }); if (localErrorId.has_value()) { auto const* localError = nodePred(*localErrorId); solAssert(localError && localError->isFunctionErrorBlock(), ""); auto const [localValues, localVars] = localError->localVariableValues(nodeArgs(*localErrorId)); if (auto localStr = formatVariableModel(localVars, localValues, "\n"); !localStr.empty()) localState += localStr + "\n"; } } } else { auto modelMsg = formatVariableModel(*stateVars, stateValues, ", "); /// We report the state after every tx in the trace except for the last, which is reported /// first in the code above. if (!modelMsg.empty()) path.emplace_back("State: " + modelMsg); } } std::string txCex = summaryPredicate->formatSummaryCall(summaryArgs, m_charStreamProvider); std::list<std::string> calls; auto dfs = [&](unsigned parent, unsigned node, unsigned depth, auto&& _dfs) -> void { auto pred = nodePred(node); auto parentPred = nodePred(parent); solAssert(pred && pred->isSummary(), ""); solAssert(parentPred && parentPred->isSummary(), ""); auto callTraceSize = calls.size(); if (!pred->isConstructorSummary()) for (unsigned v: callGraph[node]) _dfs(node, v, depth + 1, _dfs); bool appendTxVars = pred->isConstructorSummary() || pred->isFunctionSummary() || pred->isExternalCallUntrusted(); calls.push_front(std::string(depth * 4, ' ') + pred->formatSummaryCall(nodeArgs(node), m_charStreamProvider, appendTxVars)); if (pred->isInternalCall()) calls.front() += " -- internal call"; else if (pred->isExternalCallTrusted()) calls.front() += " -- trusted external call"; else if (pred->isExternalCallUntrusted()) { calls.front() += " -- untrusted external call"; if (calls.size() > callTraceSize + 1) calls.front() += ", synthesized as:"; } else if (pred->programVariable()) { calls.front() += "-- action on external contract in state variable \"" + pred->programVariable()->name() + "\""; if (calls.size() > callTraceSize + 1) calls.front() += ", synthesized as:"; } else if (pred->isFunctionSummary() && parentPred->isExternalCallUntrusted()) calls.front() += " -- reentrant call"; }; dfs(summaryId, summaryId, 0, dfs); path.emplace_back(boost::algorithm::join(calls, "\n")); } return localState + "\nTransaction trace:\n" + boost::algorithm::join(path | ranges::views::reverse, "\n"); } std::map<unsigned, std::vector<unsigned>> CHC::summaryCalls(CHCSolverInterface::CexGraph const& _graph, unsigned _root) { std::map<unsigned, std::vector<unsigned>> calls; auto compare = [&](unsigned _a, unsigned _b) { auto extract = [&](std::string const& _s) { // We want to sort sibling predicates in the counterexample graph by their unique predicate id. // For most predicates, this actually doesn't matter. // The cases where this matters are internal and external function calls which have the form: // summary_<CALLID>_<suffix> // nondet_call_<CALLID>_<suffix> // Those have the extra unique <CALLID> numbers based on the traversal order, and are necessary // to infer the call order so that's shown property in the counterexample trace. // For other predicates, we do not care. auto beg = _s.data(); while (beg != _s.data() + _s.size() && !isDigit(*beg)) ++beg; int result = -1; static_cast<void>(std::from_chars(beg, _s.data() + _s.size(), result)); return result; }; auto anum = extract(_graph.nodes.at(_a).name); auto bnum = extract(_graph.nodes.at(_b).name); // The second part of the condition is needed to ensure that two different predicates are not considered equal return (anum > bnum) || (anum == bnum && _graph.nodes.at(_a).name > _graph.nodes.at(_b).name); }; std::queue<std::pair<unsigned, unsigned>> q; q.push({_root, _root}); while (!q.empty()) { auto [node, root] = q.front(); q.pop(); Predicate const* nodePred = Predicate::predicate(_graph.nodes.at(node).name); Predicate const* rootPred = Predicate::predicate(_graph.nodes.at(root).name); if (nodePred->isSummary() && ( _root == root || nodePred->isInternalCall() || nodePred->isExternalCallTrusted() || nodePred->isExternalCallUntrusted() || rootPred->isExternalCallUntrusted() || rootPred->programVariable() )) { calls[root].push_back(node); root = node; } auto const& edges = _graph.edges.at(node); for (unsigned v: std::set<unsigned, decltype(compare)>(begin(edges), end(edges), compare)) q.push({v, root}); } return calls; } std::string CHC::cex2dot(CHCSolverInterface::CexGraph const& _cex) { std::string dot = "digraph {\n"; auto pred = [&](CHCSolverInterface::CexNode const& _node) { std::vector<std::string> args = applyMap( _node.arguments, [&](auto const& arg) { return arg.name; } ); return "\"" + _node.name + "(" + boost::algorithm::join(args, ", ") + ")\""; }; for (auto const& [u, vs]: _cex.edges) for (auto v: vs) dot += pred(_cex.nodes.at(v)) + " -> " + pred(_cex.nodes.at(u)) + "\n"; dot += "}"; return dot; } std::string CHC::uniquePrefix() { return std::to_string(m_blockCounter++); } std::string CHC::contractSuffix(ContractDefinition const& _contract) { return _contract.name() + "_" + std::to_string(_contract.id()); } unsigned CHC::newErrorId() { unsigned errorId = m_context.newUniqueId(); // We need to make sure the error id is not zero, // because error id zero actually means no error in the CHC encoding. if (errorId == 0) errorId = m_context.newUniqueId(); return errorId; } SymbolicIntVariable& CHC::errorFlag() { return state().errorFlag(); } void CHC::newTxConstraints(Expression const* _value) { auto txOrigin = state().txMember("tx.origin"); state().newTx(); // set the transaction sender as this contract m_context.addAssertion(state().txMember("msg.sender") == state().thisAddress()); // set the origin to be the current transaction origin m_context.addAssertion(state().txMember("tx.origin") == txOrigin); if (_value) // set the msg value m_context.addAssertion(state().txMember("msg.value") == expr(*_value)); } frontend::Expression const* CHC::valueOption(FunctionCallOptions const* _options) { if (_options) for (auto&& [i, name]: _options->names() | ranges::views::enumerate) if (name && *name == "value") return _options->options().at(i).get(); return nullptr; } void CHC::decreaseBalanceFromOptionsValue(Expression const& _value) { state().addBalance(state().thisAddress(), 0 - expr(_value)); } std::vector<smtutil::Expression> CHC::commonStateExpressions(smtutil::Expression const& error, smtutil::Expression const& address) { if (state().hasBytesConcatFunction()) return {error, address, state().abi(), state().bytesConcat(), state().crypto()}; return {error, address, state().abi(), state().crypto()}; }
86,222
C++
.cpp
2,102
38.310181
200
0.747815
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
3,174
SymbolicVariables.cpp
ethereum_solidity/libsolidity/formal/SymbolicVariables.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libsolidity/formal/SymbolicVariables.h> #include <libsolidity/formal/EncodingContext.h> #include <libsolidity/formal/SymbolicTypes.h> #include <libsolutil/Algorithms.h> using namespace solidity; using namespace solidity::util; using namespace solidity::smtutil; using namespace solidity::frontend; using namespace solidity::frontend::smt; SymbolicVariable::SymbolicVariable( frontend::Type const* _type, frontend::Type const* _originalType, std::string _uniqueName, EncodingContext& _context ): m_type(_type), m_originalType(_originalType), m_uniqueName(std::move(_uniqueName)), m_context(_context), m_ssa(std::make_unique<SSAVariable>()) { solAssert(m_type, ""); m_sort = smtSort(*m_type); solAssert(m_sort, ""); } SymbolicVariable::SymbolicVariable( SortPointer _sort, std::string _uniqueName, EncodingContext& _context ): m_sort(std::move(_sort)), m_uniqueName(std::move(_uniqueName)), m_context(_context), m_ssa(std::make_unique<SSAVariable>()) { solAssert(m_sort, ""); } smtutil::Expression SymbolicVariable::currentValue(frontend::Type const*) const { return valueAtIndex(m_ssa->index()); } std::string SymbolicVariable::currentName() const { return uniqueSymbol(m_ssa->index()); } smtutil::Expression SymbolicVariable::valueAtIndex(unsigned _index) const { return m_context.newVariable(uniqueSymbol(_index), m_sort); } std::string SymbolicVariable::nameAtIndex(unsigned _index) const { return uniqueSymbol(_index); } std::string SymbolicVariable::uniqueSymbol(unsigned _index) const { return m_uniqueName + "_" + std::to_string(_index); } smtutil::Expression SymbolicVariable::resetIndex() { m_ssa->resetIndex(); return currentValue(); } smtutil::Expression SymbolicVariable::setIndex(unsigned _index) { m_ssa->setIndex(_index); return currentValue(); } smtutil::Expression SymbolicVariable::increaseIndex() { ++(*m_ssa); return currentValue(); } SymbolicBoolVariable::SymbolicBoolVariable( frontend::Type const* _type, std::string _uniqueName, EncodingContext& _context ): SymbolicVariable(_type, _type, std::move(_uniqueName), _context) { solAssert(m_type->category() == frontend::Type::Category::Bool, ""); } SymbolicIntVariable::SymbolicIntVariable( frontend::Type const* _type, frontend::Type const* _originalType, std::string _uniqueName, EncodingContext& _context ): SymbolicVariable(_type, _originalType, std::move(_uniqueName), _context) { solAssert(isNumber(*m_type), ""); } SymbolicAddressVariable::SymbolicAddressVariable( std::string _uniqueName, EncodingContext& _context ): SymbolicIntVariable(TypeProvider::uint(160), TypeProvider::uint(160), std::move(_uniqueName), _context) { } SymbolicFixedBytesVariable::SymbolicFixedBytesVariable( frontend::Type const* _originalType, unsigned _numBytes, std::string _uniqueName, EncodingContext& _context ): SymbolicIntVariable(TypeProvider::uint(_numBytes * 8), _originalType, std::move(_uniqueName), _context) { } SymbolicFunctionVariable::SymbolicFunctionVariable( frontend::Type const* _type, std::string _uniqueName, EncodingContext& _context ): SymbolicVariable(_type, _type, std::move(_uniqueName), _context), m_declaration(m_context.newVariable(currentName(), m_sort)) { solAssert(m_type->category() == frontend::Type::Category::Function, ""); } SymbolicFunctionVariable::SymbolicFunctionVariable( SortPointer _sort, std::string _uniqueName, EncodingContext& _context ): SymbolicVariable(std::move(_sort), std::move(_uniqueName), _context), m_declaration(m_context.newVariable(currentName(), m_sort)) { solAssert(m_sort->kind == Kind::Function, ""); } smtutil::Expression SymbolicFunctionVariable::currentValue(frontend::Type const* _targetType) const { return m_abstract.currentValue(_targetType); } smtutil::Expression SymbolicFunctionVariable::currentFunctionValue() const { return m_declaration; } smtutil::Expression SymbolicFunctionVariable::valueAtIndex(unsigned _index) const { return m_abstract.valueAtIndex(_index); } smtutil::Expression SymbolicFunctionVariable::functionValueAtIndex(unsigned _index) const { return SymbolicVariable::valueAtIndex(_index); } smtutil::Expression SymbolicFunctionVariable::resetIndex() { SymbolicVariable::resetIndex(); return m_abstract.resetIndex(); } smtutil::Expression SymbolicFunctionVariable::setIndex(unsigned _index) { SymbolicVariable::setIndex(_index); return m_abstract.setIndex(_index); } smtutil::Expression SymbolicFunctionVariable::increaseIndex() { ++(*m_ssa); resetDeclaration(); m_abstract.increaseIndex(); return m_abstract.currentValue(); } smtutil::Expression SymbolicFunctionVariable::operator()(std::vector<smtutil::Expression> const& _arguments) const { return m_declaration(_arguments); } void SymbolicFunctionVariable::resetDeclaration() { m_declaration = m_context.newVariable(currentName(), m_sort); } SymbolicEnumVariable::SymbolicEnumVariable( frontend::Type const* _type, std::string _uniqueName, EncodingContext& _context ): SymbolicVariable(_type, _type, std::move(_uniqueName), _context) { solAssert(isEnum(*m_type), ""); } SymbolicTupleVariable::SymbolicTupleVariable( frontend::Type const* _type, std::string _uniqueName, EncodingContext& _context ): SymbolicVariable(_type, _type, std::move(_uniqueName), _context) { solAssert(isTuple(*m_type), ""); } SymbolicTupleVariable::SymbolicTupleVariable( SortPointer _sort, std::string _uniqueName, EncodingContext& _context ): SymbolicVariable(std::move(_sort), std::move(_uniqueName), _context) { solAssert(m_sort->kind == Kind::Tuple, ""); } smtutil::Expression SymbolicTupleVariable::currentValue(frontend::Type const* _targetType) const { if (!_targetType || sort() == smtSort(*_targetType)) return SymbolicVariable::currentValue(); auto thisTuple = std::dynamic_pointer_cast<TupleSort>(sort()); auto otherTuple = std::dynamic_pointer_cast<TupleSort>(smtSort(*_targetType)); solAssert(thisTuple && otherTuple, ""); solAssert(thisTuple->components.size() == otherTuple->components.size(), ""); std::vector<smtutil::Expression> args; for (size_t i = 0; i < thisTuple->components.size(); ++i) args.emplace_back(component(i, type(), _targetType)); return smtutil::Expression::tuple_constructor( smtutil::Expression(std::make_shared<smtutil::SortSort>(smtSort(*_targetType)), ""), args ); } std::vector<SortPointer> const& SymbolicTupleVariable::components() const { auto tupleSort = std::dynamic_pointer_cast<TupleSort>(m_sort); solAssert(tupleSort, ""); return tupleSort->components; } smtutil::Expression SymbolicTupleVariable::component( size_t _index, frontend::Type const* _fromType, frontend::Type const* _toType ) const { std::optional<smtutil::Expression> conversion = symbolicTypeConversion(_fromType, _toType); if (conversion) return *conversion; return smtutil::Expression::tuple_get(currentValue(), _index); } SymbolicArrayVariable::SymbolicArrayVariable( frontend::Type const* _type, frontend::Type const* _originalType, std::string _uniqueName, EncodingContext& _context ): SymbolicVariable(_type, _originalType, std::move(_uniqueName), _context), m_pair( smtSort(*_type), m_uniqueName + "_length_pair", m_context ) { solAssert(isArray(*m_type) || isMapping(*m_type), ""); } SymbolicArrayVariable::SymbolicArrayVariable( SortPointer _sort, std::string _uniqueName, EncodingContext& _context ): SymbolicVariable(std::move(_sort), std::move(_uniqueName), _context), m_pair( std::make_shared<TupleSort>( "array_length_pair", std::vector<std::string>{"array", "length"}, std::vector<SortPointer>{m_sort, SortProvider::uintSort} ), m_uniqueName + "_array_length_pair", m_context ) { solAssert(m_sort->kind == Kind::Array, ""); } smtutil::Expression SymbolicArrayVariable::currentValue(frontend::Type const* _targetType) const { std::optional<smtutil::Expression> conversion = symbolicTypeConversion(m_originalType, _targetType); if (conversion) return *conversion; return m_pair.currentValue(); } smtutil::Expression SymbolicArrayVariable::valueAtIndex(unsigned _index) const { return m_pair.valueAtIndex(_index); } smtutil::Expression SymbolicArrayVariable::elements() const { return m_pair.component(0); } smtutil::Expression SymbolicArrayVariable::length() const { return m_pair.component(1); } SymbolicStructVariable::SymbolicStructVariable( frontend::Type const* _type, std::string _uniqueName, EncodingContext& _context ): SymbolicVariable(_type, _type, std::move(_uniqueName), _context) { solAssert(isNonRecursiveStruct(*m_type), ""); auto const* structType = dynamic_cast<StructType const*>(_type); solAssert(structType, ""); auto const& members = structType->structDefinition().members(); for (unsigned i = 0; i < members.size(); ++i) { solAssert(members.at(i), ""); m_memberIndices.emplace(members.at(i)->name(), i); } } smtutil::Expression SymbolicStructVariable::member(std::string const& _member) const { return smtutil::Expression::tuple_get(currentValue(), m_memberIndices.at(_member)); } smtutil::Expression SymbolicStructVariable::assignMember(std::string const& _member, smtutil::Expression const& _memberValue) { auto const* structType = dynamic_cast<StructType const*>(m_type); solAssert(structType, ""); auto const& structDef = structType->structDefinition(); auto const& structMembers = structDef.members(); auto oldMembers = applyMap( structMembers, [&](auto _member) { return member(_member->name()); } ); increaseIndex(); for (unsigned i = 0; i < structMembers.size(); ++i) { auto const& memberName = structMembers.at(i)->name(); auto newMember = memberName == _member ? _memberValue : oldMembers.at(i); m_context.addAssertion(member(memberName) == newMember); } return currentValue(); } smtutil::Expression SymbolicStructVariable::assignAllMembers(std::vector<smtutil::Expression> const& _memberValues) { auto structType = dynamic_cast<StructType const*>(m_type); solAssert(structType, ""); auto const& structDef = structType->structDefinition(); auto const& structMembers = structDef.members(); solAssert(_memberValues.size() == structMembers.size(), ""); increaseIndex(); for (unsigned i = 0; i < _memberValues.size(); ++i) m_context.addAssertion(_memberValues[i] == member(structMembers[i]->name())); return currentValue(); }
11,017
C++
.cpp
346
30.040462
125
0.770745
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
3,175
Z3CHCSmtLib2Interface.cpp
ethereum_solidity/libsolidity/formal/Z3CHCSmtLib2Interface.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libsolidity/formal/Z3CHCSmtLib2Interface.h> #include <libsolidity/interface/UniversalCallback.h> #include <libsmtutil/SMTLib2Parser.h> #include <boost/algorithm/string/predicate.hpp> #include <stack> #ifdef EMSCRIPTEN_BUILD #include <z3++.h> #endif using namespace solidity::frontend::smt; using namespace solidity::smtutil; Z3CHCSmtLib2Interface::Z3CHCSmtLib2Interface( frontend::ReadCallback::Callback _smtCallback, std::optional<unsigned int> _queryTimeout, bool _computeInvariants ): CHCSmtLib2Interface({}, std::move(_smtCallback), _queryTimeout), m_computeInvariants(_computeInvariants) { #ifdef EMSCRIPTEN_BUILD constexpr int resourceLimit = 2000000; if (m_queryTimeout) z3::set_param("timeout", int(*m_queryTimeout)); else z3::set_param("rlimit", resourceLimit); z3::set_param("rewriter.pull_cheap_ite", true); z3::set_param("fp.spacer.q3.use_qgen", true); z3::set_param("fp.spacer.mbqi", false); z3::set_param("fp.spacer.ground_pobs", false); #endif } void Z3CHCSmtLib2Interface::setupSmtCallback(bool _enablePreprocessing) { if (auto* universalCallback = m_smtCallback.target<frontend::UniversalCallback>()) universalCallback->smtCommand().setZ3(m_queryTimeout, _enablePreprocessing, m_computeInvariants); } CHCSolverInterface::QueryResult Z3CHCSmtLib2Interface::query(smtutil::Expression const& _block) { setupSmtCallback(true); std::string query = dumpQuery(_block); try { #ifdef EMSCRIPTEN_BUILD z3::set_param("fp.xform.slice", true); z3::set_param("fp.xform.inline_linear", true); z3::set_param("fp.xform.inline_eager", true); std::string response = Z3_eval_smtlib2_string(z3::context{}, query.c_str()); #else std::string response = querySolver(query); #endif // NOTE: Our internal semantics is UNSAT -> SAFE and SAT -> UNSAFE, which corresponds to usual SMT-based model checking // However, with CHC solvers, the meaning is flipped, UNSAT -> UNSAFE and SAT -> SAFE. // So we have to flip the answer. if (boost::starts_with(response, "unsat")) { // Repeat the query with preprocessing disabled, to get the full proof setupSmtCallback(false); query = "(set-option :produce-proofs true)" + query + "\n(get-proof)"; #ifdef EMSCRIPTEN_BUILD z3::set_param("fp.xform.slice", false); z3::set_param("fp.xform.inline_linear", false); z3::set_param("fp.xform.inline_eager", false); response = Z3_eval_smtlib2_string(z3::context{}, query.c_str()); #else response = querySolver(query); #endif setupSmtCallback(true); if (!boost::starts_with(response, "unsat")) return {CheckResult::SATISFIABLE, Expression(true), {}}; return {CheckResult::SATISFIABLE, Expression(true), graphFromZ3Answer(response)}; } CheckResult result; if (boost::starts_with(response, "sat")) { auto maybeInvariants = invariantsFromSolverResponse(response); return {CheckResult::UNSATISFIABLE, maybeInvariants.value_or(Expression(true)), {}}; } else if (boost::starts_with(response, "unknown")) result = CheckResult::UNKNOWN; else result = CheckResult::ERROR; return {result, Expression(true), {}}; } catch(smtutil::SMTSolverInteractionError const&) { return {CheckResult::ERROR, Expression(true), {}}; } } CHCSolverInterface::CexGraph Z3CHCSmtLib2Interface::graphFromZ3Answer(std::string const& _proof) const { std::stringstream ss(_proof); std::string answer; ss >> answer; smtSolverInteractionRequire(answer == "unsat", "Proof must follow an unsat answer"); SMTLib2Parser parser(ss); if (parser.isEOF()) // No proof from Z3 return {}; // For some reason Z3 outputs everything as a single s-expression SMTLib2Expression parsedOutput; try { parsedOutput = parser.parseExpression(); } catch (SMTLib2Parser::ParsingException&) { smtSolverInteractionRequire(false, "Error during parsing Z3's proof"); } smtSolverInteractionRequire(parser.isEOF(), "Error during parsing Z3's proof"); smtSolverInteractionRequire(!isAtom(parsedOutput), "Encountered unexpected format of Z3's proof"); auto& commands = asSubExpressions(parsedOutput); ScopedParser expressionParser(m_context); for (auto& command: commands) { if (isAtom(command)) continue; auto const& args = asSubExpressions(command); smtSolverInteractionRequire(args.size() > 0, "Encountered unexpected format of Z3's proof"); auto const& head = args[0]; if (!isAtom(head)) continue; // Z3 can introduce new helper predicates to be used in the proof // e.g., "(declare-fun query!0 (Bool Bool Bool Int Int Bool Bool Bool Bool Bool Bool Bool Int) Bool)" if (asAtom(head) == "declare-fun") { smtSolverInteractionRequire(args.size() == 4, "Encountered unexpected format of Z3's proof"); auto const& name = args[1]; auto const& domainSorts = args[2]; auto const& codomainSort = args[3]; smtSolverInteractionRequire(isAtom(name), "Encountered unexpected format of Z3's proof"); smtSolverInteractionRequire(!isAtom(domainSorts), "Encountered unexpected format of Z3's proof"); expressionParser.addVariableDeclaration(asAtom(name), expressionParser.toSort(codomainSort)); } // The subexpression starting with "proof" contains the whole proof, which we need to transform to our internal // representation else if (asAtom(head) == "proof") { inlineLetExpressions(command); return graphFromSMTLib2Expression(command, expressionParser); } } return {}; } CHCSolverInterface::CexGraph Z3CHCSmtLib2Interface::graphFromSMTLib2Expression( SMTLib2Expression const& _proof, ScopedParser& _context ) { auto fact = [](SMTLib2Expression const& _node) -> SMTLib2Expression const& { if (isAtom(_node)) return _node; smtSolverInteractionRequire(!asSubExpressions(_node).empty(), "Encountered unexpected format of Z3's proof"); return asSubExpressions(_node).back(); }; smtSolverInteractionRequire(!isAtom(_proof), "Encountered unexpected format of Z3's proof"); auto const& proofArgs = asSubExpressions(_proof); smtSolverInteractionRequire(proofArgs.size() == 2, "Encountered unexpected format of Z3's proof"); smtSolverInteractionRequire(isAtom(proofArgs.at(0)) && asAtom(proofArgs.at(0)) == "proof", "Encountered unexpected format of Z3's proof"); auto const& proofNode = proofArgs.at(1); auto const& derivedFact = fact(proofNode); if (isAtom(proofNode) || !isAtom(derivedFact) || asAtom(derivedFact) != "false") return {}; CHCSolverInterface::CexGraph graph; std::stack<SMTLib2Expression const*> proofStack; proofStack.push(&asSubExpressions(proofNode).at(1)); std::map<SMTLib2Expression const*, unsigned> visitedIds; unsigned nextId = 0; auto const* root = proofStack.top(); auto const& derivedRootFact = fact(*root); visitedIds.emplace(root, nextId++); graph.nodes.emplace(visitedIds.at(root), _context.toSMTUtilExpression(derivedRootFact)); auto isHyperRes = [](SMTLib2Expression const& expr) { if (isAtom(expr)) return false; auto const& subExprs = asSubExpressions(expr); smtSolverInteractionRequire(!subExprs.empty(), "Encountered unexpected format of Z3's proof"); auto const& op = subExprs.at(0); if (isAtom(op)) return false; auto const& opExprs = asSubExpressions(op); if (opExprs.size() < 2) return false; auto const& ruleName = opExprs.at(1); return isAtom(ruleName) && asAtom(ruleName) == "hyper-res"; }; while (!proofStack.empty()) { auto const* currentNode = proofStack.top(); smtSolverInteractionRequire(visitedIds.find(currentNode) != visitedIds.end(), "Error in processing Z3's proof"); auto id = visitedIds.at(currentNode); smtSolverInteractionRequire(graph.nodes.count(id), "Error in processing Z3's proof"); proofStack.pop(); if (isHyperRes(*currentNode)) { auto const& args = asSubExpressions(*currentNode); smtSolverInteractionRequire(args.size() > 1, "Unexpected format of hyper-resolution rule in Z3's proof"); // args[0] is the name of the rule // args[1] is the clause used // last argument is the derived fact // the arguments in the middle are the facts where we need to recurse for (unsigned i = 2; i < args.size() - 1; ++i) { auto const* child = &args[i]; if (!visitedIds.count(child)) { visitedIds.emplace(child, nextId++); proofStack.push(child); } auto childId = visitedIds.at(child); if (!graph.nodes.count(childId)) { graph.nodes.emplace(childId, _context.toSMTUtilExpression(fact(*child))); graph.edges[childId] = {}; } graph.edges[id].push_back(childId); } } } return graph; }
9,191
C++
.cpp
227
37.731278
139
0.749804
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,176
Z3SMTLib2Interface.cpp
ethereum_solidity/libsolidity/formal/Z3SMTLib2Interface.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libsolidity/formal/Z3SMTLib2Interface.h> #include <libsolidity/interface/UniversalCallback.h> #ifdef EMSCRIPTEN_BUILD #include <z3++.h> #endif using namespace solidity::frontend::smt; Z3SMTLib2Interface::Z3SMTLib2Interface( frontend::ReadCallback::Callback _smtCallback, std::optional<unsigned int> _queryTimeout ): SMTLib2Interface({}, std::move(_smtCallback), _queryTimeout) { #ifdef EMSCRIPTEN_BUILD constexpr int resourceLimit = 2000000; if (m_queryTimeout) z3::set_param("timeout", int(*m_queryTimeout)); else z3::set_param("rlimit", resourceLimit); z3::set_param("rewriter.pull_cheap_ite", true); z3::set_param("fp.spacer.q3.use_qgen", true); z3::set_param("fp.spacer.mbqi", false); z3::set_param("fp.spacer.ground_pobs", false); #endif } void Z3SMTLib2Interface::setupSmtCallback() { if (auto* universalCallback = m_smtCallback.target<frontend::UniversalCallback>()) universalCallback->smtCommand().setZ3(m_queryTimeout, true, false); } std::string Z3SMTLib2Interface::querySolver(std::string const& _query) { #ifdef EMSCRIPTEN_BUILD z3::context context; return Z3_eval_smtlib2_string(context, _query.c_str()); #else return SMTLib2Interface::querySolver(_query); #endif }
1,900
C++
.cpp
50
36.2
83
0.782609
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,177
SymbolicState.cpp
ethereum_solidity/libsolidity/formal/SymbolicState.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libsolidity/formal/SymbolicState.h> #include <libsolidity/formal/SymbolicTypes.h> #include <libsolidity/formal/EncodingContext.h> #include <libsolidity/formal/SMTEncoder.h> #include <libsmtutil/Sorts.h> #include <range/v3/view.hpp> using namespace solidity; using namespace solidity::util; using namespace solidity::smtutil; using namespace solidity::frontend::smt; BlockchainVariable::BlockchainVariable( std::string _name, std::map<std::string, smtutil::SortPointer> _members, EncodingContext& _context ): m_name(std::move(_name)), m_members(std::move(_members)), m_context(_context) { std::vector<std::string> members; std::vector<SortPointer> sorts; for (auto const& [component, sort]: m_members) { members.emplace_back(component); sorts.emplace_back(sort); m_componentIndices[component] = static_cast<unsigned>(members.size() - 1); } m_tuple = std::make_unique<SymbolicTupleVariable>( std::make_shared<smtutil::TupleSort>(m_name + "_type", members, sorts), m_name, m_context ); } smtutil::Expression BlockchainVariable::member(std::string const& _member) const { return m_tuple->component(m_componentIndices.at(_member)); } smtutil::Expression BlockchainVariable::assignMember(std::string const& _member, smtutil::Expression const& _value) { smtutil::Expression newTuple = smt::assignMember(m_tuple->currentValue(), {{_member, _value}}); m_context.addAssertion(m_tuple->increaseIndex() == newTuple); return m_tuple->currentValue(); } void SymbolicState::reset() { m_error.resetIndex(); m_thisAddress.resetIndex(); m_tx.reset(); m_crypto.reset(); if (m_abi) m_abi->reset(); /// We don't reset nor clear these pointers on purpose, /// since it only helps to keep the already generated types. if (m_state) m_state->reset(); } smtutil::Expression SymbolicState::balances() const { return m_state->member("balances"); } smtutil::Expression SymbolicState::balance() const { return balance(thisAddress()); } smtutil::Expression SymbolicState::balance(smtutil::Expression _address) const { return smtutil::Expression::select(balances(), std::move(_address)); } smtutil::Expression SymbolicState::blockhash(smtutil::Expression _blockNumber) const { return smtutil::Expression::select(m_tx.member("blockhash"), std::move(_blockNumber)); } void SymbolicState::newBalances() { auto tupleSort = std::dynamic_pointer_cast<TupleSort>(stateSort()); auto balanceSort = tupleSort->components.at(tupleSort->memberToIndex.at("balances")); SymbolicVariable newBalances(balanceSort, "fresh_balances_" + std::to_string(m_context.newUniqueId()), m_context); m_state->assignMember("balances", newBalances.currentValue()); } void SymbolicState::transfer(smtutil::Expression _from, smtutil::Expression _to, smtutil::Expression _value) { unsigned indexBefore = m_state->index(); addBalance(_from, 0 - _value); addBalance(_to, std::move(_value)); unsigned indexAfter = m_state->index(); solAssert(indexAfter > indexBefore, ""); m_state->newVar(); /// Do not apply the transfer operation if _from == _to. auto newState = smtutil::Expression::ite( std::move(_from) == std::move(_to), m_state->value(indexBefore), m_state->value(indexAfter) ); m_context.addAssertion(m_state->value() == newState); } smtutil::Expression SymbolicState::storage(ContractDefinition const& _contract) const { return smt::member(m_state->member("storage"), contractStorageKey(_contract)); } smtutil::Expression SymbolicState::storage(ContractDefinition const& _contract, smtutil::Expression _address) const { return smtutil::Expression::select(storage(_contract), std::move(_address)); } smtutil::Expression SymbolicState::addressActive(smtutil::Expression _address) const { return smtutil::Expression::select(m_state->member("isActive"), std::move(_address)); } void SymbolicState::setAddressActive( smtutil::Expression _address, bool _active ) { m_state->assignMember("isActive", smtutil::Expression::store( m_state->member("isActive"), std::move(_address), smtutil::Expression(_active)) ); } void SymbolicState::newStorage() { auto newStorageVar = SymbolicTupleVariable( m_state->member("storage").sort, "havoc_storage_" + std::to_string(m_context.newUniqueId()), m_context ); m_state->assignMember("storage", newStorageVar.currentValue()); } void SymbolicState::writeStateVars(ContractDefinition const& _contract, smtutil::Expression _address) { auto stateVars = SMTEncoder::stateVariablesIncludingInheritedAndPrivate(_contract); if (stateVars.empty()) return; std::map<std::string, smtutil::Expression> values; for (auto var: stateVars) values.emplace(stateVarStorageKey(*var, _contract), m_context.variable(*var)->currentValue()); smtutil::Expression thisStorage = storage(_contract, _address); smtutil::Expression newStorage = smt::assignMember(thisStorage, values); auto newContractStorage = smtutil::Expression::store( storage(_contract), std::move(_address), newStorage ); smtutil::Expression newAllStorage = smt::assignMember(m_state->member("storage"), {{contractStorageKey(_contract), newContractStorage}}); m_state->assignMember("storage", newAllStorage); } void SymbolicState::readStateVars(ContractDefinition const& _contract, smtutil::Expression _address) { auto stateVars = SMTEncoder::stateVariablesIncludingInheritedAndPrivate(_contract); if (stateVars.empty()) return; auto contractStorage = storage(_contract, std::move(_address)); for (auto var: stateVars) m_context.addAssertion( m_context.variable(*var)->increaseIndex() == smt::member(contractStorage, stateVarStorageKey(*var, _contract)) ); } void SymbolicState::addBalance(smtutil::Expression _address, smtutil::Expression _value) { auto newBalances = smtutil::Expression::store( balances(), _address, balance(_address) + std::move(_value) ); m_state->assignMember("balances", newBalances); } smtutil::Expression SymbolicState::txMember(std::string const& _member) const { return m_tx.member(_member); } smtutil::Expression SymbolicState::evmParisConstraints() const { // Ensure prevrandao range as defined by EIP-4399. return txMember("block.prevrandao") > (u256(1) << 64); } smtutil::Expression SymbolicState::txTypeConstraints() const { return evmParisConstraints() && smt::symbolicUnknownConstraints(m_tx.member("block.basefee"), TypeProvider::uint256()) && smt::symbolicUnknownConstraints(m_tx.member("block.chainid"), TypeProvider::uint256()) && smt::symbolicUnknownConstraints(m_tx.member("block.coinbase"), TypeProvider::address()) && smt::symbolicUnknownConstraints(m_tx.member("block.prevrandao"), TypeProvider::uint256()) && smt::symbolicUnknownConstraints(m_tx.member("block.gaslimit"), TypeProvider::uint256()) && smt::symbolicUnknownConstraints(m_tx.member("block.number"), TypeProvider::uint256()) && smt::symbolicUnknownConstraints(m_tx.member("block.timestamp"), TypeProvider::uint256()) && smt::symbolicUnknownConstraints(m_tx.member("msg.sender"), TypeProvider::address()) && smt::symbolicUnknownConstraints(m_tx.member("msg.value"), TypeProvider::uint256()) && smt::symbolicUnknownConstraints(m_tx.member("tx.origin"), TypeProvider::address()) && smt::symbolicUnknownConstraints(m_tx.member("tx.gasprice"), TypeProvider::uint256()); } smtutil::Expression SymbolicState::txNonPayableConstraint() const { return m_tx.member("msg.value") == 0; } smtutil::Expression SymbolicState::txFunctionConstraints(FunctionDefinition const& _function) const { smtutil::Expression conj = _function.isPayable() ? smtutil::Expression(true) : txNonPayableConstraint(); if (_function.isPartOfExternalInterface()) { auto sig = TypeProvider::function(_function)->externalIdentifier(); conj = conj && m_tx.member("msg.sig") == sig; auto b0 = sig >> (3 * 8); auto b1 = (sig & 0x00ff0000) >> (2 * 8); auto b2 = (sig & 0x0000ff00) >> (1 * 8); auto b3 = (sig & 0x000000ff); auto data = smtutil::Expression::tuple_get(m_tx.member("msg.data"), 0); conj = conj && smtutil::Expression::select(data, 0) == b0; conj = conj && smtutil::Expression::select(data, 1) == b1; conj = conj && smtutil::Expression::select(data, 2) == b2; conj = conj && smtutil::Expression::select(data, 3) == b3; auto length = smtutil::Expression::tuple_get(m_tx.member("msg.data"), 1); // TODO add ABI size of function input parameters here \/ conj = conj && length >= 4; } return conj; } void SymbolicState::prepareForSourceUnit(SourceUnit const& _source, bool _storage) { auto allSources = _source.referencedSourceUnits(true); allSources.insert(&_source); std::set<FunctionCall const*, ASTCompareByID<FunctionCall>> abiCalls; std::set<FunctionCall const*, ASTCompareByID<FunctionCall>> bytesConcatCalls; std::set<ContractDefinition const*, ASTCompareByID<ContractDefinition>> contracts; for (auto const& source: allSources) { abiCalls += SMTEncoder::collectABICalls(source); bytesConcatCalls += SMTEncoder::collectBytesConcatCalls(source); for (auto node: source->nodes()) if (auto contract = dynamic_cast<ContractDefinition const*>(node.get())) contracts.insert(contract); } buildState(contracts, _storage); buildABIFunctions(abiCalls); buildBytesConcatFunctions(bytesConcatCalls); } /// Private helpers. std::string SymbolicState::contractSuffix(ContractDefinition const& _contract) const { return "_" + _contract.name() + "_" + std::to_string(_contract.id()); } std::string SymbolicState::contractStorageKey(ContractDefinition const& _contract) const { return "storage" + contractSuffix(_contract); } std::string SymbolicState::stateVarStorageKey(VariableDeclaration const& _var, ContractDefinition const& _contract) const { return _var.name() + "_" + std::to_string(_var.id()) + contractSuffix(_contract); } void SymbolicState::buildState(std::set<ContractDefinition const*, ASTCompareByID<ContractDefinition>> const& _contracts, bool _allStorages) { std::map<std::string, SortPointer> stateMembers{ {"balances", std::make_shared<smtutil::ArraySort>(smtutil::SortProvider::uintSort, smtutil::SortProvider::uintSort)} }; if (_allStorages) { std::vector<std::string> memberNames; std::vector<SortPointer> memberSorts; for (auto contract: _contracts) { std::string suffix = contractSuffix(*contract); // z3 doesn't like empty tuples, so if the contract has 0 // state vars we can't put it there. auto stateVars = SMTEncoder::stateVariablesIncludingInheritedAndPrivate(*contract); if (stateVars.empty()) continue; auto names = applyMap(stateVars, [&](auto var) { return var->name() + "_" + std::to_string(var->id()) + suffix; }); auto sorts = applyMap(stateVars, [](auto var) { return smtSortAbstractFunction(*var->type()); }); std::string name = "storage" + suffix; auto storageTuple = std::make_shared<smtutil::TupleSort>( name + "_type", names, sorts ); auto storageSort = std::make_shared<smtutil::ArraySort>( smtSort(*TypeProvider::address()), storageTuple ); memberNames.emplace_back(name); memberSorts.emplace_back(storageSort); } stateMembers.emplace( "isActive", std::make_shared<smtutil::ArraySort>(smtSort(*TypeProvider::address()), smtutil::SortProvider::boolSort) ); stateMembers.emplace( "storage", std::make_shared<smtutil::TupleSort>( "storage_type", memberNames, memberSorts ) ); } m_state = std::make_unique<BlockchainVariable>( "state", std::move(stateMembers), m_context ); } void SymbolicState::buildBytesConcatFunctions(std::set<FunctionCall const*, ASTCompareByID<FunctionCall>> const& _bytesConcatCalls) { std::map<std::string, SortPointer> functions; for (auto const* funCall: _bytesConcatCalls) { auto t = dynamic_cast<FunctionType const*>(funCall->expression().annotation().type); solAssert(t->kind() == FunctionType::Kind::BytesConcat, "Expected bytes.concat function"); auto const& args = funCall->sortedArguments(); auto argTypes = [](auto const& _args) { return util::applyMap(_args, [](auto arg) { return arg->annotation().type; }); }; // bytes.concat : (bytes/literal/fixed bytes, ... ) -> bytes std::vector<frontend::Type const*> inTypes = argTypes(args); auto replaceUserDefinedValueTypes = [](auto& _types) { for (auto& t: _types) if (auto userType = dynamic_cast<UserDefinedValueType const*>(t)) t = &userType->underlyingType(); }; auto replaceStringLiteralTypes = [](auto& _types) { for (auto& t: _types) if (t->category() == frontend::Type::Category::StringLiteral) t = TypeProvider::bytesMemory(); }; replaceUserDefinedValueTypes(inTypes); replaceStringLiteralTypes(inTypes); auto name = t->richIdentifier(); for (auto paramType: inTypes) name += "_" + paramType->richIdentifier(); frontend::Type const* outType = TypeProvider::bytesMemory(); name += "_" + outType->richIdentifier(); m_bytesConcatMembers[funCall] = {name, inTypes, outType}; if (functions.count(name)) continue; /// If there is only one parameter, we use that type directly. /// Otherwise we create a tuple wrapping the necessary types. auto typesToSort = [](auto const& _types, std::string const& _name) -> std::shared_ptr<Sort> { if (_types.size() == 1) return smtSortAbstractFunction(*_types.front()); std::vector<std::string> inNames; std::vector<SortPointer> sorts; for (unsigned i = 0; i < _types.size(); ++i) { inNames.emplace_back(_name + "_input_" + std::to_string(i)); sorts.emplace_back(smtSortAbstractFunction(*_types.at(i))); } return std::make_shared<smtutil::TupleSort>( _name + "_input", inNames, sorts ); }; auto functionSort = std::make_shared<smtutil::ArraySort>( typesToSort(inTypes, name), smtSortAbstractFunction(*outType) ); functions[name] = functionSort; } m_bytesConcat = std::make_unique<BlockchainVariable>("bytesConcat", std::move(functions), m_context); } void SymbolicState::buildABIFunctions(std::set<FunctionCall const*, ASTCompareByID<FunctionCall>> const& _abiFunctions) { std::map<std::string, SortPointer> functions; for (auto const* funCall: _abiFunctions) { auto t = dynamic_cast<FunctionType const*>(funCall->expression().annotation().type); auto const& args = funCall->sortedArguments(); auto const& paramTypes = t->parameterTypes(); auto const& returnTypes = t->returnParameterTypes(); auto argTypes = [](auto const& _args) { return util::applyMap(_args, [](auto arg) { return arg->annotation().type; }); }; /// Since each abi.* function may have a different number of input/output parameters, /// we generically compute those types. std::vector<frontend::Type const*> inTypes; std::vector<frontend::Type const*> outTypes; if (t->kind() == FunctionType::Kind::ABIDecode) { /// abi.decode : (bytes, tuple_of_types(return_types)) -> (return_types) solAssert(args.size() == 2, "Unexpected number of arguments for abi.decode"); inTypes.emplace_back(TypeProvider::bytesMemory()); auto argType = args.at(1)->annotation().type; if (auto const* tupleType = dynamic_cast<TupleType const*>(argType)) for (auto componentType: tupleType->components()) { auto typeType = dynamic_cast<TypeType const*>(componentType); solAssert(typeType, ""); outTypes.emplace_back(typeType->actualType()); } else if (auto const* typeType = dynamic_cast<TypeType const*>(argType)) outTypes.emplace_back(typeType->actualType()); else solAssert(false, "Unexpected argument of abi.decode"); } else if (t->kind() == FunctionType::Kind::ABIEncodeCall) { // abi.encodeCall : (functionPointer, tuple_of_args_or_one_non_tuple_arg(arguments)) -> bytes solAssert(args.size() == 2, "Unexpected number of arguments for abi.encodeCall"); outTypes.emplace_back(TypeProvider::bytesMemory()); inTypes.emplace_back(args.at(0)->annotation().type); inTypes.emplace_back(args.at(1)->annotation().type); } else { outTypes = returnTypes; if ( t->kind() == FunctionType::Kind::ABIEncodeWithSelector || t->kind() == FunctionType::Kind::ABIEncodeWithSignature ) { /// abi.encodeWithSelector : (bytes4, one_or_more_types) -> bytes /// abi.encodeWithSignature : (string, one_or_more_types) -> bytes inTypes.emplace_back(paramTypes.front()); inTypes += argTypes(std::vector<ASTPointer<Expression const>>(args.begin() + 1, args.end())); } else { /// abi.encode/abi.encodePacked : one_or_more_types -> bytes solAssert( t->kind() == FunctionType::Kind::ABIEncode || t->kind() == FunctionType::Kind::ABIEncodePacked, "" ); inTypes = argTypes(args); } } /// Rational numbers and string literals add the concrete values to the type name, /// so we replace them by uint256 and bytes since those are the same as their SMT types. /// TODO we could also replace all types by their ABI type. auto replaceTypes = [](auto& _types) { for (auto& t: _types) if (t->category() == frontend::Type::Category::RationalNumber) t = TypeProvider::uint256(); else if (t->category() == frontend::Type::Category::StringLiteral) t = TypeProvider::bytesMemory(); else if (auto userType = dynamic_cast<UserDefinedValueType const*>(t)) t = &userType->underlyingType(); }; replaceTypes(inTypes); replaceTypes(outTypes); auto name = t->richIdentifier(); for (auto paramType: inTypes + outTypes) name += "_" + paramType->richIdentifier(); m_abiMembers[funCall] = {name, inTypes, outTypes}; if (functions.count(name)) continue; /// If there is only one input or output parameter, we use that type directly. /// Otherwise we create a tuple wrapping the necessary input or output types. auto typesToSort = [](auto const& _types, std::string const& _name) -> std::shared_ptr<Sort> { if (_types.size() == 1) return smtSortAbstractFunction(*_types.front()); std::vector<std::string> inNames; std::vector<SortPointer> sorts; for (unsigned i = 0; i < _types.size(); ++i) { inNames.emplace_back(_name + "_input_" + std::to_string(i)); sorts.emplace_back(smtSortAbstractFunction(*_types.at(i))); } return std::make_shared<smtutil::TupleSort>( _name + "_input", inNames, sorts ); }; auto functionSort = std::make_shared<smtutil::ArraySort>( typesToSort(inTypes, name), typesToSort(outTypes, name) ); functions[name] = functionSort; } m_abi = std::make_unique<BlockchainVariable>("abi", std::move(functions), m_context); } smtutil::Expression SymbolicState::abiFunction(frontend::FunctionCall const* _funCall) { solAssert(m_abi, ""); return m_abi->member(std::get<0>(m_abiMembers.at(_funCall))); } SymbolicState::SymbolicABIFunction const& SymbolicState::abiFunctionTypes(FunctionCall const* _funCall) const { return m_abiMembers.at(_funCall); } smtutil::Expression SymbolicState::bytesConcatFunction(frontend::FunctionCall const* _funCall) { solAssert(m_bytesConcat, ""); return m_bytesConcat->member(std::get<0>(m_bytesConcatMembers.at(_funCall))); } SymbolicState::SymbolicBytesConcatFunction const& SymbolicState::bytesConcatFunctionTypes(FunctionCall const* _funCall) const { return m_bytesConcatMembers.at(_funCall); }
19,944
C++
.cpp
499
37.164329
140
0.733757
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,180
MultiUseYulFunctionCollector.cpp
ethereum_solidity/libsolidity/codegen/MultiUseYulFunctionCollector.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 /** * Container of (unparsed) Yul functions identified by name which are meant to be generated * only once. */ #include <libsolidity/codegen/MultiUseYulFunctionCollector.h> #include <liblangutil/Exceptions.h> #include <libsolutil/Whiskers.h> #include <libsolutil/StringUtils.h> using namespace solidity; using namespace solidity::frontend; using namespace solidity::util; std::string MultiUseYulFunctionCollector::requestedFunctions() { std::string result = std::move(m_code); m_code.clear(); m_requestedFunctions.clear(); return result; } std::string MultiUseYulFunctionCollector::createFunction(std::string const& _name, std::function<std::string()> const& _creator) { if (!m_requestedFunctions.count(_name)) { m_requestedFunctions.insert(_name); std::string fun = _creator(); solAssert(!fun.empty(), ""); solAssert(fun.find("function " + _name + "(") != std::string::npos, "Function not properly named."); m_code += std::move(fun); } return _name; } std::string MultiUseYulFunctionCollector::createFunction( std::string const& _name, std::function<std::string(std::vector<std::string>&, std::vector<std::string>&)> const& _creator ) { solAssert(!_name.empty(), ""); if (!m_requestedFunctions.count(_name)) { m_requestedFunctions.insert(_name); std::vector<std::string> arguments; std::vector<std::string> returnParameters; std::string body = _creator(arguments, returnParameters); solAssert(!body.empty(), ""); m_code += Whiskers(R"( function <functionName>(<args>)<?+retParams> -> <retParams></+retParams> { <body> } )") ("functionName", _name) ("args", joinHumanReadable(arguments)) ("retParams", joinHumanReadable(returnParameters)) ("body", body) .render(); } return _name; }
2,437
C++
.cpp
70
32.628571
128
0.745439
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
true
false
3,184
Compiler.cpp
ethereum_solidity/libsolidity/codegen/Compiler.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 /** * @author Christian <c@ethdev.com> * @date 2014 * Solidity compiler. */ #include <libsolidity/codegen/Compiler.h> #include <libsolidity/codegen/ContractCompiler.h> #include <libevmasm/Assembly.h> #include <range/v3/algorithm/none_of.hpp> using namespace solidity; using namespace solidity::frontend; void Compiler::compileContract( ContractDefinition const& _contract, std::map<ContractDefinition const*, std::shared_ptr<Compiler const>> const& _otherCompilers, bytes const& _metadata ) { auto static isTransientReferenceType = [](VariableDeclaration const* _varDeclaration) { solAssert(_varDeclaration && _varDeclaration->type()); return _varDeclaration->referenceLocation() == VariableDeclaration::Location::Transient && !_varDeclaration->type()->isValueType(); }; solUnimplementedAssert( ranges::none_of(_contract.stateVariables(), isTransientReferenceType), "Transient storage reference type variables are not supported." ); ContractCompiler runtimeCompiler(nullptr, m_runtimeContext, m_optimiserSettings); runtimeCompiler.compileContract(_contract, _otherCompilers); m_runtimeContext.appendToAuxiliaryData(_metadata); // This might modify m_runtimeContext because it can access runtime functions at // creation time. OptimiserSettings creationSettings{m_optimiserSettings}; // The creation code will be executed at most once, so we modify the optimizer // settings accordingly. creationSettings.expectedExecutionsPerDeployment = 1; ContractCompiler creationCompiler(&runtimeCompiler, m_context, creationSettings); m_runtimeSub = creationCompiler.compileConstructor(_contract, _otherCompilers); m_context.optimise(m_optimiserSettings); solAssert(m_context.appendYulUtilityFunctionsRan(), "appendYulUtilityFunctions() was not called."); solAssert(m_runtimeContext.appendYulUtilityFunctionsRan(), "appendYulUtilityFunctions() was not called."); } std::shared_ptr<evmasm::Assembly> Compiler::runtimeAssemblyPtr() const { solAssert(m_context.runtimeContext(), ""); return m_context.runtimeContext()->assemblyPtr(); }
2,758
C++
.cpp
61
43.131148
107
0.802087
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,187
YulUtilFunctions.cpp
ethereum_solidity/libsolidity/codegen/YulUtilFunctions.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 /** * Component that can generate various useful Yul functions. */ #include <libsolidity/codegen/YulUtilFunctions.h> #include <libsolidity/codegen/MultiUseYulFunctionCollector.h> #include <libsolidity/ast/AST.h> #include <libsolidity/codegen/CompilerUtils.h> #include <libsolidity/codegen/ir/IRVariable.h> #include <libsolutil/CommonData.h> #include <libsolutil/FunctionSelector.h> #include <libsolutil/Whiskers.h> #include <libsolutil/StringUtils.h> #include <libsolidity/ast/TypeProvider.h> #include <range/v3/algorithm/all_of.hpp> using namespace solidity; using namespace solidity::util; using namespace solidity::frontend; using namespace std::string_literals; namespace { std::optional<size_t> staticEncodingSize(std::vector<Type const*> const& _parameterTypes) { size_t encodedSize = 0; for (auto* type: _parameterTypes) { if (type->isDynamicallyEncoded()) return std::nullopt; encodedSize += type->calldataHeadSize(); } return encodedSize; } } std::string YulUtilFunctions::identityFunction() { std::string functionName = "identity"; return m_functionCollector.createFunction("identity", [&](std::vector<std::string>& _args, std::vector<std::string>& _rets) { _args.push_back("value"); _rets.push_back("ret"); return "ret := value"; }); } std::string YulUtilFunctions::combineExternalFunctionIdFunction() { std::string functionName = "combine_external_function_id"; return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(addr, selector) -> combined { combined := <shl64>(or(<shl32>(addr), and(selector, 0xffffffff))) } )") ("functionName", functionName) ("shl32", shiftLeftFunction(32)) ("shl64", shiftLeftFunction(64)) .render(); }); } std::string YulUtilFunctions::splitExternalFunctionIdFunction() { std::string functionName = "split_external_function_id"; return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(combined) -> addr, selector { combined := <shr64>(combined) selector := and(combined, 0xffffffff) addr := <shr32>(combined) } )") ("functionName", functionName) ("shr32", shiftRightFunction(32)) ("shr64", shiftRightFunction(64)) .render(); }); } std::string YulUtilFunctions::copyToMemoryFunction(bool _fromCalldata, bool _cleanup) { std::string functionName = "copy_"s + (_fromCalldata ? "calldata"s : "memory"s) + "_to_memory"s + (_cleanup ? "_with_cleanup"s : ""s); return m_functionCollector.createFunction(functionName, [&](std::vector<std::string>& _args, std::vector<std::string>&) { _args = {"src", "dst", "length"}; if (_fromCalldata) return Whiskers(R"( calldatacopy(dst, src, length) <?cleanup>mstore(add(dst, length), 0)</cleanup> )") ("cleanup", _cleanup) .render(); else { if (m_evmVersion.hasMcopy()) return Whiskers(R"( mcopy(dst, src, length) <?cleanup>mstore(add(dst, length), 0)</cleanup> )") ("cleanup", _cleanup) .render(); else return Whiskers(R"( let i := 0 for { } lt(i, length) { i := add(i, 32) } { mstore(add(dst, i), mload(add(src, i))) } <?cleanup>mstore(add(dst, length), 0)</cleanup> )") ("cleanup", _cleanup) .render(); } }); } std::string YulUtilFunctions::copyLiteralToMemoryFunction(std::string const& _literal) { std::string functionName = "copy_literal_to_memory_" + util::toHex(util::keccak256(_literal).asBytes()); return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>() -> memPtr { memPtr := <arrayAllocationFunction>(<size>) <storeLiteralInMem>(add(memPtr, 32)) } )") ("functionName", functionName) ("arrayAllocationFunction", allocateMemoryArrayFunction(*TypeProvider::array(DataLocation::Memory, true))) ("size", std::to_string(_literal.size())) ("storeLiteralInMem", storeLiteralInMemoryFunction(_literal)) .render(); }); } std::string YulUtilFunctions::storeLiteralInMemoryFunction(std::string const& _literal) { std::string functionName = "store_literal_in_memory_" + util::toHex(util::keccak256(_literal).asBytes()); return m_functionCollector.createFunction(functionName, [&]() { size_t words = (_literal.length() + 31) / 32; std::vector<std::map<std::string, std::string>> wordParams(words); for (size_t i = 0; i < words; ++i) { wordParams[i]["offset"] = std::to_string(i * 32); wordParams[i]["wordValue"] = formatAsStringOrNumber(_literal.substr(32 * i, 32)); } return Whiskers(R"( function <functionName>(memPtr) { <#word> mstore(add(memPtr, <offset>), <wordValue>) </word> } )") ("functionName", functionName) ("word", wordParams) .render(); }); } std::string YulUtilFunctions::copyLiteralToStorageFunction(std::string const& _literal) { std::string functionName = "copy_literal_to_storage_" + util::toHex(util::keccak256(_literal).asBytes()); return m_functionCollector.createFunction(functionName, [&](std::vector<std::string>& _args, std::vector<std::string>&) { _args = {"slot"}; if (_literal.size() >= 32) { size_t words = (_literal.length() + 31) / 32; std::vector<std::map<std::string, std::string>> wordParams(words); for (size_t i = 0; i < words; ++i) { wordParams[i]["offset"] = std::to_string(i); wordParams[i]["wordValue"] = formatAsStringOrNumber(_literal.substr(32 * i, 32)); } return Whiskers(R"( let oldLen := <byteArrayLength>(sload(slot)) <cleanUpArrayEnd>(slot, oldLen, <length>) sstore(slot, <encodedLen>) let dstPtr := <dataArea>(slot) <#word> sstore(add(dstPtr, <offset>), <wordValue>) </word> )") ("byteArrayLength", extractByteArrayLengthFunction()) ("cleanUpArrayEnd", cleanUpDynamicByteArrayEndSlotsFunction(*TypeProvider::bytesStorage())) ("dataArea", arrayDataAreaFunction(*TypeProvider::bytesStorage())) ("word", wordParams) ("length", std::to_string(_literal.size())) ("encodedLen", std::to_string(2 * _literal.size() + 1)) .render(); } else return Whiskers(R"( let oldLen := <byteArrayLength>(sload(slot)) <cleanUpArrayEnd>(slot, oldLen, <length>) sstore(slot, add(<wordValue>, <encodedLen>)) )") ("byteArrayLength", extractByteArrayLengthFunction()) ("cleanUpArrayEnd", cleanUpDynamicByteArrayEndSlotsFunction(*TypeProvider::bytesStorage())) ("wordValue", formatAsStringOrNumber(_literal)) ("length", std::to_string(_literal.size())) ("encodedLen", std::to_string(2 * _literal.size())) .render(); }); } std::string YulUtilFunctions::revertWithError( std::string const& _signature, std::vector<Type const*> const& _parameterTypes, std::vector<ASTPointer<Expression const>> const& _errorArguments, std::string const& _posVar, std::string const& _endVar ) { solAssert((!_posVar.empty() && !_endVar.empty()) || (_posVar.empty() && _endVar.empty())); bool const needsNewVariable = !_posVar.empty() && !_endVar.empty(); bool needsAllocation = true; if (std::optional<size_t> size = staticEncodingSize(_parameterTypes)) if ( ranges::all_of(_parameterTypes, [](auto const* type) { solAssert(!dynamic_cast<InaccessibleDynamicType const*>(type)); return type && type->isValueType(); }) ) { constexpr size_t errorSelectorSize = 4; needsAllocation = *size + errorSelectorSize > CompilerUtils::generalPurposeMemoryStart; } Whiskers templ(R"({ <?needsAllocation> let <pos> := <allocateUnbounded>() <!needsAllocation> let <pos> := 0 </needsAllocation> mstore(<pos>, <hash>) let <end> := <encode>(add(<pos>, 4) <argumentVars>) revert(<pos>, sub(<end>, <pos>)) })"); templ("pos", needsNewVariable ? _posVar : "memPtr"); templ("end", needsNewVariable ? _endVar : "end"); templ("hash", formatNumber(util::selectorFromSignatureU256(_signature))); templ("needsAllocation", needsAllocation); if (needsAllocation) templ("allocateUnbounded", allocateUnboundedFunction()); std::vector<std::string> errorArgumentVars; std::vector<Type const*> errorArgumentTypes; for (ASTPointer<Expression const> const& arg: _errorArguments) { errorArgumentVars += IRVariable(*arg).stackSlots(); solAssert(arg->annotation().type); errorArgumentTypes.push_back(arg->annotation().type); } templ("argumentVars", joinHumanReadablePrefixed(errorArgumentVars)); templ("encode", ABIFunctions(m_evmVersion, m_revertStrings, m_functionCollector).tupleEncoder(errorArgumentTypes, _parameterTypes)); return templ.render(); } std::string YulUtilFunctions::requireOrAssertFunction(bool _assert, Type const* _messageType, ASTPointer<Expression const> _stringArgumentExpression) { std::string functionName = std::string(_assert ? "assert_helper" : "require_helper") + (_messageType ? ("_" + _messageType->identifier()) : ""); solAssert(!_assert || !_messageType, "Asserts can't have messages!"); return m_functionCollector.createFunction(functionName, [&]() { if (!_messageType) return Whiskers(R"( function <functionName>(condition) { if iszero(condition) { <error> } } )") ("error", _assert ? panicFunction(PanicCode::Assert) + "()" : "revert(0, 0)") ("functionName", functionName) .render(); solAssert(_stringArgumentExpression, "Require with string must have a string argument"); solAssert(_stringArgumentExpression->annotation().type); std::vector<std::string> functionParameterNames = IRVariable(*_stringArgumentExpression).stackSlots(); return Whiskers(R"( function <functionName>(condition <functionParameterNames>) { if iszero(condition) <revertWithError> } )") ("functionName", functionName) ("revertWithError", revertWithError("Error(string)", {TypeProvider::stringMemory()}, {_stringArgumentExpression})) ("functionParameterNames", joinHumanReadablePrefixed(functionParameterNames)) .render(); }); } std::string YulUtilFunctions::requireWithErrorFunction(FunctionCall const& errorConstructorCall) { ErrorDefinition const* errorDefinition = dynamic_cast<ErrorDefinition const*>(ASTNode::referencedDeclaration(errorConstructorCall.expression())); solAssert(errorDefinition); std::string const errorSignature = errorDefinition->functionType(true)->externalSignature(); // Note that in most cases we'll always generate one function per error definition, // because types in the constructor call will match the ones in the definition. The only // exception are calls with types, where each instance has its own type (e.g. literals). std::string functionName = "require_helper_t_error_" + std::to_string(errorDefinition->id()) + "_" + errorDefinition->name(); for (ASTPointer<Expression const> const& argument: errorConstructorCall.sortedArguments()) { solAssert(argument->annotation().type); functionName += ("_" + argument->annotation().type->identifier()); } std::vector<std::string> functionParameterNames; for (ASTPointer<Expression const> const& arg: errorConstructorCall.sortedArguments()) { solAssert(arg->annotation().type); if (arg->annotation().type->sizeOnStack() > 0) functionParameterNames += IRVariable(*arg).stackSlots(); } return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(condition <functionParameterNames>) { if iszero(condition) <revertWithError> } )") ("functionName", functionName) ("functionParameterNames", joinHumanReadablePrefixed(functionParameterNames)) // We're creating parameter names from the expressions passed into the constructor call, // which will result in odd names like `expr_29` that would normally be used for locals. // Note that this is the naming expected by `revertWithError()`. ("revertWithError", revertWithError(errorSignature, errorDefinition->functionType(true)->parameterTypes(), errorConstructorCall.sortedArguments())) .render(); }); } std::string YulUtilFunctions::leftAlignFunction(Type const& _type) { std::string functionName = std::string("leftAlign_") + _type.identifier(); return m_functionCollector.createFunction(functionName, [&]() { Whiskers templ(R"( function <functionName>(value) -> aligned { <body> } )"); templ("functionName", functionName); switch (_type.category()) { case Type::Category::Address: templ("body", "aligned := " + leftAlignFunction(IntegerType(160)) + "(value)"); break; case Type::Category::Integer: { IntegerType const& type = dynamic_cast<IntegerType const&>(_type); if (type.numBits() == 256) templ("body", "aligned := value"); else templ("body", "aligned := " + shiftLeftFunction(256 - type.numBits()) + "(value)"); break; } case Type::Category::RationalNumber: solAssert(false, "Left align requested for rational number."); break; case Type::Category::Bool: templ("body", "aligned := " + leftAlignFunction(IntegerType(8)) + "(value)"); break; case Type::Category::FixedPoint: solUnimplemented("Fixed point types not implemented."); break; case Type::Category::Array: case Type::Category::Struct: solAssert(false, "Left align requested for non-value type."); break; case Type::Category::FixedBytes: templ("body", "aligned := value"); break; case Type::Category::Contract: templ("body", "aligned := " + leftAlignFunction(*TypeProvider::address()) + "(value)"); break; case Type::Category::Enum: { solAssert(dynamic_cast<EnumType const&>(_type).storageBytes() == 1, ""); templ("body", "aligned := " + leftAlignFunction(IntegerType(8)) + "(value)"); break; } case Type::Category::InaccessibleDynamic: solAssert(false, "Left align requested for inaccessible dynamic type."); break; default: solAssert(false, "Left align of type " + _type.identifier() + " requested."); } return templ.render(); }); } std::string YulUtilFunctions::shiftLeftFunction(size_t _numBits) { solAssert(_numBits < 256, ""); std::string functionName = "shift_left_" + std::to_string(_numBits); return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(value) -> newValue { newValue := <?hasShifts> shl(<numBits>, value) <!hasShifts> mul(value, <multiplier>) </hasShifts> } )") ("functionName", functionName) ("numBits", std::to_string(_numBits)) ("hasShifts", m_evmVersion.hasBitwiseShifting()) ("multiplier", toCompactHexWithPrefix(u256(1) << _numBits)) .render(); }); } std::string YulUtilFunctions::shiftLeftFunctionDynamic() { std::string functionName = "shift_left_dynamic"; return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(bits, value) -> newValue { newValue := <?hasShifts> shl(bits, value) <!hasShifts> mul(value, exp(2, bits)) </hasShifts> } )") ("functionName", functionName) ("hasShifts", m_evmVersion.hasBitwiseShifting()) .render(); }); } std::string YulUtilFunctions::shiftRightFunction(size_t _numBits) { solAssert(_numBits < 256, ""); // Note that if this is extended with signed shifts, // the opcodes SAR and SDIV behave differently with regards to rounding! std::string functionName = "shift_right_" + std::to_string(_numBits) + "_unsigned"; return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(value) -> newValue { newValue := <?hasShifts> shr(<numBits>, value) <!hasShifts> div(value, <multiplier>) </hasShifts> } )") ("functionName", functionName) ("hasShifts", m_evmVersion.hasBitwiseShifting()) ("numBits", std::to_string(_numBits)) ("multiplier", toCompactHexWithPrefix(u256(1) << _numBits)) .render(); }); } std::string YulUtilFunctions::shiftRightFunctionDynamic() { std::string const functionName = "shift_right_unsigned_dynamic"; return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(bits, value) -> newValue { newValue := <?hasShifts> shr(bits, value) <!hasShifts> div(value, exp(2, bits)) </hasShifts> } )") ("functionName", functionName) ("hasShifts", m_evmVersion.hasBitwiseShifting()) .render(); }); } std::string YulUtilFunctions::shiftRightSignedFunctionDynamic() { std::string const functionName = "shift_right_signed_dynamic"; return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(bits, value) -> result { <?hasShifts> result := sar(bits, value) <!hasShifts> let divisor := exp(2, bits) let xor_mask := sub(0, slt(value, 0)) result := xor(div(xor(value, xor_mask), divisor), xor_mask) // combined version of // switch slt(value, 0) // case 0 { result := div(value, divisor) } // default { result := not(div(not(value), divisor)) } </hasShifts> } )") ("functionName", functionName) ("hasShifts", m_evmVersion.hasBitwiseShifting()) .render(); }); } std::string YulUtilFunctions::typedShiftLeftFunction(Type const& _type, Type const& _amountType) { solUnimplementedAssert(_type.category() != Type::Category::FixedPoint, "Not yet implemented - FixedPointType."); solAssert(_type.category() == Type::Category::FixedBytes || _type.category() == Type::Category::Integer, ""); solAssert(_amountType.category() == Type::Category::Integer, ""); solAssert(!dynamic_cast<IntegerType const&>(_amountType).isSigned(), ""); std::string const functionName = "shift_left_" + _type.identifier() + "_" + _amountType.identifier(); return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(value, bits) -> result { bits := <cleanAmount>(bits) result := <cleanup>(<shift>(bits, <cleanup>(value))) } )") ("functionName", functionName) ("cleanAmount", cleanupFunction(_amountType)) ("shift", shiftLeftFunctionDynamic()) ("cleanup", cleanupFunction(_type)) .render(); }); } std::string YulUtilFunctions::typedShiftRightFunction(Type const& _type, Type const& _amountType) { solUnimplementedAssert(_type.category() != Type::Category::FixedPoint, "Not yet implemented - FixedPointType."); solAssert(_type.category() == Type::Category::FixedBytes || _type.category() == Type::Category::Integer, ""); solAssert(_amountType.category() == Type::Category::Integer, ""); solAssert(!dynamic_cast<IntegerType const&>(_amountType).isSigned(), ""); IntegerType const* integerType = dynamic_cast<IntegerType const*>(&_type); bool valueSigned = integerType && integerType->isSigned(); std::string const functionName = "shift_right_" + _type.identifier() + "_" + _amountType.identifier(); return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(value, bits) -> result { bits := <cleanAmount>(bits) result := <cleanup>(<shift>(bits, <cleanup>(value))) } )") ("functionName", functionName) ("cleanAmount", cleanupFunction(_amountType)) ("shift", valueSigned ? shiftRightSignedFunctionDynamic() : shiftRightFunctionDynamic()) ("cleanup", cleanupFunction(_type)) .render(); }); } std::string YulUtilFunctions::updateByteSliceFunction(size_t _numBytes, size_t _shiftBytes) { solAssert(_numBytes <= 32, ""); solAssert(_shiftBytes <= 32, ""); size_t numBits = _numBytes * 8; size_t shiftBits = _shiftBytes * 8; std::string functionName = "update_byte_slice_" + std::to_string(_numBytes) + "_shift_" + std::to_string(_shiftBytes); return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(value, toInsert) -> result { let mask := <mask> toInsert := <shl>(toInsert) value := and(value, not(mask)) result := or(value, and(toInsert, mask)) } )") ("functionName", functionName) ("mask", formatNumber(((bigint(1) << numBits) - 1) << shiftBits)) ("shl", shiftLeftFunction(shiftBits)) .render(); }); } std::string YulUtilFunctions::updateByteSliceFunctionDynamic(size_t _numBytes) { solAssert(_numBytes <= 32, ""); size_t numBits = _numBytes * 8; std::string functionName = "update_byte_slice_dynamic" + std::to_string(_numBytes); return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(value, shiftBytes, toInsert) -> result { let shiftBits := mul(shiftBytes, 8) let mask := <shl>(shiftBits, <mask>) toInsert := <shl>(shiftBits, toInsert) value := and(value, not(mask)) result := or(value, and(toInsert, mask)) } )") ("functionName", functionName) ("mask", formatNumber((bigint(1) << numBits) - 1)) ("shl", shiftLeftFunctionDynamic()) .render(); }); } std::string YulUtilFunctions::maskBytesFunctionDynamic() { std::string functionName = "mask_bytes_dynamic"; return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(data, bytes) -> result { let mask := not(<shr>(mul(8, bytes), not(0))) result := and(data, mask) })") ("functionName", functionName) ("shr", shiftRightFunctionDynamic()) .render(); }); } std::string YulUtilFunctions::maskLowerOrderBytesFunction(size_t _bytes) { std::string functionName = "mask_lower_order_bytes_" + std::to_string(_bytes); solAssert(_bytes <= 32, ""); return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(data) -> result { result := and(data, <mask>) })") ("functionName", functionName) ("mask", formatNumber((~u256(0)) >> (256 - 8 * _bytes))) .render(); }); } std::string YulUtilFunctions::maskLowerOrderBytesFunctionDynamic() { std::string functionName = "mask_lower_order_bytes_dynamic"; return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(data, bytes) -> result { let mask := not(<shl>(mul(8, bytes), not(0))) result := and(data, mask) })") ("functionName", functionName) ("shl", shiftLeftFunctionDynamic()) .render(); }); } std::string YulUtilFunctions::roundUpFunction() { std::string functionName = "round_up_to_mul_of_32"; return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(value) -> result { result := and(add(value, 31), not(31)) } )") ("functionName", functionName) .render(); }); } std::string YulUtilFunctions::divide32CeilFunction() { return m_functionCollector.createFunction( "divide_by_32_ceil", [&](std::vector<std::string>& _args, std::vector<std::string>& _ret) { _args = {"value"}; _ret = {"result"}; return "result := div(add(value, 31), 32)"; } ); } std::string YulUtilFunctions::overflowCheckedIntAddFunction(IntegerType const& _type) { std::string functionName = "checked_add_" + _type.identifier(); return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(x, y) -> sum { x := <cleanupFunction>(x) y := <cleanupFunction>(y) sum := add(x, y) <?signed> <?256bit> // overflow, if x >= 0 and sum < y // underflow, if x < 0 and sum >= y if or( and(iszero(slt(x, 0)), slt(sum, y)), and(slt(x, 0), iszero(slt(sum, y))) ) { <panic>() } <!256bit> if or( sgt(sum, <maxValue>), slt(sum, <minValue>) ) { <panic>() } </256bit> <!signed> <?256bit> if gt(x, sum) { <panic>() } <!256bit> if gt(sum, <maxValue>) { <panic>() } </256bit> </signed> } )") ("functionName", functionName) ("signed", _type.isSigned()) ("maxValue", toCompactHexWithPrefix(u256(_type.maxValue()))) ("minValue", toCompactHexWithPrefix(u256(_type.minValue()))) ("cleanupFunction", cleanupFunction(_type)) ("panic", panicFunction(PanicCode::UnderOverflow)) ("256bit", _type.numBits() == 256) .render(); }); } std::string YulUtilFunctions::wrappingIntAddFunction(IntegerType const& _type) { std::string functionName = "wrapping_add_" + _type.identifier(); return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(x, y) -> sum { sum := <cleanupFunction>(add(x, y)) } )") ("functionName", functionName) ("cleanupFunction", cleanupFunction(_type)) .render(); }); } std::string YulUtilFunctions::overflowCheckedIntMulFunction(IntegerType const& _type) { std::string functionName = "checked_mul_" + _type.identifier(); return m_functionCollector.createFunction(functionName, [&]() { return // Multiplication by zero could be treated separately and directly return zero. Whiskers(R"( function <functionName>(x, y) -> product { x := <cleanupFunction>(x) y := <cleanupFunction>(y) let product_raw := mul(x, y) product := <cleanupFunction>(product_raw) <?signed> <?gt128bit> <?256bit> // special case if and(slt(x, 0), eq(y, <minValue>)) { <panic>() } </256bit> // overflow, if x != 0 and y != product/x if iszero( or( iszero(x), eq(y, sdiv(product, x)) ) ) { <panic>() } <!gt128bit> if iszero(eq(product, product_raw)) { <panic>() } </gt128bit> <!signed> <?gt128bit> // overflow, if x != 0 and y != product/x if iszero( or( iszero(x), eq(y, div(product, x)) ) ) { <panic>() } <!gt128bit> if iszero(eq(product, product_raw)) { <panic>() } </gt128bit> </signed> } )") ("functionName", functionName) ("signed", _type.isSigned()) ("cleanupFunction", cleanupFunction(_type)) ("panic", panicFunction(PanicCode::UnderOverflow)) ("minValue", toCompactHexWithPrefix(u256(_type.minValue()))) ("256bit", _type.numBits() == 256) ("gt128bit", _type.numBits() > 128) .render(); }); } std::string YulUtilFunctions::wrappingIntMulFunction(IntegerType const& _type) { std::string functionName = "wrapping_mul_" + _type.identifier(); return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(x, y) -> product { product := <cleanupFunction>(mul(x, y)) } )") ("functionName", functionName) ("cleanupFunction", cleanupFunction(_type)) .render(); }); } std::string YulUtilFunctions::overflowCheckedIntDivFunction(IntegerType const& _type) { std::string functionName = "checked_div_" + _type.identifier(); return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(x, y) -> r { x := <cleanupFunction>(x) y := <cleanupFunction>(y) if iszero(y) { <panicDivZero>() } <?signed> // overflow for minVal / -1 if and( eq(x, <minVal>), eq(y, sub(0, 1)) ) { <panicOverflow>() } </signed> r := <?signed>s</signed>div(x, y) } )") ("functionName", functionName) ("signed", _type.isSigned()) ("minVal", toCompactHexWithPrefix(u256(_type.minValue()))) ("cleanupFunction", cleanupFunction(_type)) ("panicDivZero", panicFunction(PanicCode::DivisionByZero)) ("panicOverflow", panicFunction(PanicCode::UnderOverflow)) .render(); }); } std::string YulUtilFunctions::wrappingIntDivFunction(IntegerType const& _type) { std::string functionName = "wrapping_div_" + _type.identifier(); return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(x, y) -> r { x := <cleanupFunction>(x) y := <cleanupFunction>(y) if iszero(y) { <error>() } r := <?signed>s</signed>div(x, y) } )") ("functionName", functionName) ("cleanupFunction", cleanupFunction(_type)) ("signed", _type.isSigned()) ("error", panicFunction(PanicCode::DivisionByZero)) .render(); }); } std::string YulUtilFunctions::intModFunction(IntegerType const& _type) { std::string functionName = "mod_" + _type.identifier(); return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(x, y) -> r { x := <cleanupFunction>(x) y := <cleanupFunction>(y) if iszero(y) { <panic>() } r := <?signed>s</signed>mod(x, y) } )") ("functionName", functionName) ("signed", _type.isSigned()) ("cleanupFunction", cleanupFunction(_type)) ("panic", panicFunction(PanicCode::DivisionByZero)) .render(); }); } std::string YulUtilFunctions::overflowCheckedIntSubFunction(IntegerType const& _type) { std::string functionName = "checked_sub_" + _type.identifier(); return m_functionCollector.createFunction(functionName, [&] { return Whiskers(R"( function <functionName>(x, y) -> diff { x := <cleanupFunction>(x) y := <cleanupFunction>(y) diff := sub(x, y) <?signed> <?256bit> // underflow, if y >= 0 and diff > x // overflow, if y < 0 and diff < x if or( and(iszero(slt(y, 0)), sgt(diff, x)), and(slt(y, 0), slt(diff, x)) ) { <panic>() } <!256bit> if or( slt(diff, <minValue>), sgt(diff, <maxValue>) ) { <panic>() } </256bit> <!signed> <?256bit> if gt(diff, x) { <panic>() } <!256bit> if gt(diff, <maxValue>) { <panic>() } </256bit> </signed> } )") ("functionName", functionName) ("signed", _type.isSigned()) ("maxValue", toCompactHexWithPrefix(u256(_type.maxValue()))) ("minValue", toCompactHexWithPrefix(u256(_type.minValue()))) ("cleanupFunction", cleanupFunction(_type)) ("panic", panicFunction(PanicCode::UnderOverflow)) ("256bit", _type.numBits() == 256) .render(); }); } std::string YulUtilFunctions::wrappingIntSubFunction(IntegerType const& _type) { std::string functionName = "wrapping_sub_" + _type.identifier(); return m_functionCollector.createFunction(functionName, [&] { return Whiskers(R"( function <functionName>(x, y) -> diff { diff := <cleanupFunction>(sub(x, y)) } )") ("functionName", functionName) ("cleanupFunction", cleanupFunction(_type)) .render(); }); } std::string YulUtilFunctions::overflowCheckedIntExpFunction( IntegerType const& _type, IntegerType const& _exponentType ) { solAssert(!_exponentType.isSigned(), ""); std::string functionName = "checked_exp_" + _type.identifier() + "_" + _exponentType.identifier(); return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(base, exponent) -> power { base := <baseCleanupFunction>(base) exponent := <exponentCleanupFunction>(exponent) <?signed> power := <exp>(base, exponent, <minValue>, <maxValue>) <!signed> power := <exp>(base, exponent, <maxValue>) </signed> } )") ("functionName", functionName) ("signed", _type.isSigned()) ("exp", _type.isSigned() ? overflowCheckedSignedExpFunction() : overflowCheckedUnsignedExpFunction()) ("maxValue", toCompactHexWithPrefix(_type.max())) ("minValue", toCompactHexWithPrefix(_type.min())) ("baseCleanupFunction", cleanupFunction(_type)) ("exponentCleanupFunction", cleanupFunction(_exponentType)) .render(); }); } std::string YulUtilFunctions::overflowCheckedIntLiteralExpFunction( RationalNumberType const& _baseType, IntegerType const& _exponentType, IntegerType const& _commonType ) { solAssert(!_exponentType.isSigned(), ""); solAssert(_baseType.isNegative() == _commonType.isSigned(), ""); solAssert(_commonType.numBits() == 256, ""); std::string functionName = "checked_exp_" + _baseType.richIdentifier() + "_" + _exponentType.identifier(); return m_functionCollector.createFunction(functionName, [&]() { // Converts a bigint number into u256 (negative numbers represented in two's complement form.) // We assume that `_v` fits in 256 bits. auto bigint2u = [&](bigint const& _v) -> u256 { if (_v < 0) return s2u(s256(_v)); return u256(_v); }; // Calculates the upperbound for exponentiation, that is, calculate `b`, such that // _base**b <= _maxValue and _base**(b + 1) > _maxValue auto findExponentUpperbound = [](bigint const _base, bigint const _maxValue) -> unsigned { // There is no overflow for these cases if (_base == 0 || _base == -1 || _base == 1) return 0; unsigned first = 0; unsigned last = 255; unsigned middle; while (first < last) { middle = (first + last) / 2; if ( // The condition on msb is a shortcut that avoids computing large powers in // arbitrary precision. boost::multiprecision::msb(_base) * middle <= boost::multiprecision::msb(_maxValue) && boost::multiprecision::pow(_base, middle) <= _maxValue ) { if (boost::multiprecision::pow(_base, middle + 1) > _maxValue) return middle; else first = middle + 1; } else last = middle; } return last; }; bigint baseValue = _baseType.isNegative() ? u2s(_baseType.literalValue(nullptr)) : _baseType.literalValue(nullptr); bool needsOverflowCheck = !((baseValue == 0) || (baseValue == -1) || (baseValue == 1)); unsigned exponentUpperbound; if (_baseType.isNegative()) { // Only checks for underflow. The only case where this can be a problem is when, for a // negative base, say `b`, and an even exponent, say `e`, `b**e = 2**255` (which is an // overflow.) But this never happens because, `255 = 3*5*17`, and therefore there is no even // number `e` such that `b**e = 2**255`. exponentUpperbound = findExponentUpperbound(abs(baseValue), abs(_commonType.minValue())); bigint power = boost::multiprecision::pow(baseValue, exponentUpperbound); bigint overflowedPower = boost::multiprecision::pow(baseValue, exponentUpperbound + 1); if (needsOverflowCheck) solAssert( (power <= _commonType.maxValue()) && (power >= _commonType.minValue()) && !((overflowedPower <= _commonType.maxValue()) && (overflowedPower >= _commonType.minValue())), "Incorrect exponent upper bound calculated." ); } else { exponentUpperbound = findExponentUpperbound(baseValue, _commonType.maxValue()); if (needsOverflowCheck) solAssert( boost::multiprecision::pow(baseValue, exponentUpperbound) <= _commonType.maxValue() && boost::multiprecision::pow(baseValue, exponentUpperbound + 1) > _commonType.maxValue(), "Incorrect exponent upper bound calculated." ); } return Whiskers(R"( function <functionName>(exponent) -> power { exponent := <exponentCleanupFunction>(exponent) <?needsOverflowCheck> if gt(exponent, <exponentUpperbound>) { <panic>() } </needsOverflowCheck> power := exp(<base>, exponent) } )") ("functionName", functionName) ("exponentCleanupFunction", cleanupFunction(_exponentType)) ("needsOverflowCheck", needsOverflowCheck) ("exponentUpperbound", std::to_string(exponentUpperbound)) ("panic", panicFunction(PanicCode::UnderOverflow)) ("base", bigint2u(baseValue).str()) .render(); }); } std::string YulUtilFunctions::overflowCheckedUnsignedExpFunction() { // Checks for the "small number specialization" below. using namespace boost::multiprecision; solAssert(pow(bigint(10), 77) < pow(bigint(2), 256), ""); solAssert(pow(bigint(11), 77) >= pow(bigint(2), 256), ""); solAssert(pow(bigint(10), 78) >= pow(bigint(2), 256), ""); solAssert(pow(bigint(306), 31) < pow(bigint(2), 256), ""); solAssert(pow(bigint(307), 31) >= pow(bigint(2), 256), ""); solAssert(pow(bigint(306), 32) >= pow(bigint(2), 256), ""); std::string functionName = "checked_exp_unsigned"; return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(base, exponent, max) -> power { // This function currently cannot be inlined because of the // "leave" statements. We have to improve the optimizer. // Note that 0**0 == 1 if iszero(exponent) { power := 1 leave } if iszero(base) { power := 0 leave } // Specializations for small bases switch base // 0 is handled above case 1 { power := 1 leave } case 2 { if gt(exponent, 255) { <panic>() } power := exp(2, exponent) if gt(power, max) { <panic>() } leave } if or( and(lt(base, 11), lt(exponent, 78)), and(lt(base, 307), lt(exponent, 32)) ) { power := exp(base, exponent) if gt(power, max) { <panic>() } leave } power, base := <expLoop>(1, base, exponent, max) if gt(power, div(max, base)) { <panic>() } power := mul(power, base) } )") ("functionName", functionName) ("panic", panicFunction(PanicCode::UnderOverflow)) ("expLoop", overflowCheckedExpLoopFunction()) .render(); }); } std::string YulUtilFunctions::overflowCheckedSignedExpFunction() { std::string functionName = "checked_exp_signed"; return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(base, exponent, min, max) -> power { // Currently, `leave` avoids this function being inlined. // We have to improve the optimizer. // Note that 0**0 == 1 switch exponent case 0 { power := 1 leave } case 1 { power := base leave } if iszero(base) { power := 0 leave } power := 1 // We pull out the first iteration because it is the only one in which // base can be negative. // Exponent is at least 2 here. // overflow check for base * base switch sgt(base, 0) case 1 { if gt(base, div(max, base)) { <panic>() } } case 0 { if slt(base, sdiv(max, base)) { <panic>() } } if and(exponent, 1) { power := base } base := mul(base, base) exponent := <shr_1>(exponent) // Below this point, base is always positive. power, base := <expLoop>(power, base, exponent, max) if and(sgt(power, 0), gt(power, div(max, base))) { <panic>() } if and(slt(power, 0), slt(power, sdiv(min, base))) { <panic>() } power := mul(power, base) } )") ("functionName", functionName) ("panic", panicFunction(PanicCode::UnderOverflow)) ("expLoop", overflowCheckedExpLoopFunction()) ("shr_1", shiftRightFunction(1)) .render(); }); } std::string YulUtilFunctions::overflowCheckedExpLoopFunction() { // We use this loop for both signed and unsigned exponentiation // because we pull out the first iteration in the signed case which // results in the base always being positive. // This function does not include the final multiplication. std::string functionName = "checked_exp_helper"; return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(_power, _base, exponent, max) -> power, base { power := _power base := _base for { } gt(exponent, 1) {} { // overflow check for base * base if gt(base, div(max, base)) { <panic>() } if and(exponent, 1) { // No checks for power := mul(power, base) needed, because the check // for base * base above is sufficient, since: // |power| <= base (proof by induction) and thus: // |power * base| <= base * base <= max <= |min| (for signed) // (this is equally true for signed and unsigned exp) power := mul(power, base) } base := mul(base, base) exponent := <shr_1>(exponent) } } )") ("functionName", functionName) ("panic", panicFunction(PanicCode::UnderOverflow)) ("shr_1", shiftRightFunction(1)) .render(); }); } std::string YulUtilFunctions::wrappingIntExpFunction( IntegerType const& _type, IntegerType const& _exponentType ) { solAssert(!_exponentType.isSigned(), ""); std::string functionName = "wrapping_exp_" + _type.identifier() + "_" + _exponentType.identifier(); return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(base, exponent) -> power { base := <baseCleanupFunction>(base) exponent := <exponentCleanupFunction>(exponent) power := <baseCleanupFunction>(exp(base, exponent)) } )") ("functionName", functionName) ("baseCleanupFunction", cleanupFunction(_type)) ("exponentCleanupFunction", cleanupFunction(_exponentType)) .render(); }); } std::string YulUtilFunctions::arrayLengthFunction(ArrayType const& _type) { std::string functionName = "array_length_" + _type.identifier(); return m_functionCollector.createFunction(functionName, [&]() { Whiskers w(R"( function <functionName>(value<?dynamic><?calldata>, len</calldata></dynamic>) -> length { <?dynamic> <?memory> length := mload(value) </memory> <?storage> length := sload(value) <?byteArray> length := <extractByteArrayLength>(length) </byteArray> </storage> <?calldata> length := len </calldata> <!dynamic> length := <length> </dynamic> } )"); w("functionName", functionName); w("dynamic", _type.isDynamicallySized()); if (!_type.isDynamicallySized()) w("length", toCompactHexWithPrefix(_type.length())); w("memory", _type.location() == DataLocation::Memory); w("storage", _type.location() == DataLocation::Storage); w("calldata", _type.location() == DataLocation::CallData); if (_type.location() == DataLocation::Storage) { w("byteArray", _type.isByteArrayOrString()); if (_type.isByteArrayOrString()) w("extractByteArrayLength", extractByteArrayLengthFunction()); } return w.render(); }); } std::string YulUtilFunctions::extractByteArrayLengthFunction() { std::string functionName = "extract_byte_array_length"; return m_functionCollector.createFunction(functionName, [&]() { Whiskers w(R"( function <functionName>(data) -> length { length := div(data, 2) let outOfPlaceEncoding := and(data, 1) if iszero(outOfPlaceEncoding) { length := and(length, 0x7f) } if eq(outOfPlaceEncoding, lt(length, 32)) { <panic>() } } )"); w("functionName", functionName); w("panic", panicFunction(PanicCode::StorageEncodingError)); return w.render(); }); } std::string YulUtilFunctions::resizeArrayFunction(ArrayType const& _type) { solAssert(_type.location() == DataLocation::Storage, ""); solUnimplementedAssert(_type.baseType()->storageBytes() <= 32); if (_type.isByteArrayOrString()) return resizeDynamicByteArrayFunction(_type); std::string functionName = "resize_array_" + _type.identifier(); return m_functionCollector.createFunction(functionName, [&]() { Whiskers templ(R"( function <functionName>(array, newLen) { if gt(newLen, <maxArrayLength>) { <panic>() } let oldLen := <fetchLength>(array) <?isDynamic> // Store new length sstore(array, newLen) </isDynamic> <?needsClearing> <cleanUpArrayEnd>(array, oldLen, newLen) </needsClearing> })"); templ("functionName", functionName); templ("maxArrayLength", (u256(1) << 64).str()); templ("panic", panicFunction(util::PanicCode::ResourceError)); templ("fetchLength", arrayLengthFunction(_type)); templ("isDynamic", _type.isDynamicallySized()); bool isMappingBase = _type.baseType()->category() == Type::Category::Mapping; templ("needsClearing", !isMappingBase); if (!isMappingBase) templ("cleanUpArrayEnd", cleanUpStorageArrayEndFunction(_type)); return templ.render(); }); } std::string YulUtilFunctions::cleanUpStorageArrayEndFunction(ArrayType const& _type) { solAssert(_type.location() == DataLocation::Storage, ""); solAssert(_type.baseType()->category() != Type::Category::Mapping, ""); solAssert(!_type.isByteArrayOrString(), ""); solUnimplementedAssert(_type.baseType()->storageBytes() <= 32); std::string functionName = "cleanup_storage_array_end_" + _type.identifier(); return m_functionCollector.createFunction(functionName, [&](std::vector<std::string>& _args, std::vector<std::string>&) { _args = {"array", "len", "startIndex"}; return Whiskers(R"( if lt(startIndex, len) { // Size was reduced, clear end of array let oldSlotCount := <convertToSize>(len) let newSlotCount := <convertToSize>(startIndex) let arrayDataStart := <dataPosition>(array) let deleteStart := add(arrayDataStart, newSlotCount) let deleteEnd := add(arrayDataStart, oldSlotCount) <?packed> // if we are dealing with packed array and offset is greater than zero // we have to partially clear last slot that is still used, so decreasing start by one let offset := mul(mod(startIndex, <itemsPerSlot>), <storageBytes>) if gt(offset, 0) { <partialClearStorageSlot>(sub(deleteStart, 1), offset) } </packed> <clearStorageRange>(deleteStart, deleteEnd) } )") ("convertToSize", arrayConvertLengthToSize(_type)) ("dataPosition", arrayDataAreaFunction(_type)) ("clearStorageRange", clearStorageRangeFunction(*_type.baseType())) ("packed", _type.baseType()->storageBytes() <= 16) ("itemsPerSlot", std::to_string(32 / _type.baseType()->storageBytes())) ("storageBytes", std::to_string(_type.baseType()->storageBytes())) ("partialClearStorageSlot", partialClearStorageSlotFunction()) .render(); }); } std::string YulUtilFunctions::resizeDynamicByteArrayFunction(ArrayType const& _type) { std::string functionName = "resize_array_" + _type.identifier(); return m_functionCollector.createFunction(functionName, [&](std::vector<std::string>& _args, std::vector<std::string>&) { _args = {"array", "newLen"}; return Whiskers(R"( let data := sload(array) let oldLen := <extractLength>(data) if gt(newLen, oldLen) { <increaseSize>(array, data, oldLen, newLen) } if lt(newLen, oldLen) { <decreaseSize>(array, data, oldLen, newLen) } )") ("extractLength", extractByteArrayLengthFunction()) ("decreaseSize", decreaseByteArraySizeFunction(_type)) ("increaseSize", increaseByteArraySizeFunction(_type)) .render(); }); } std::string YulUtilFunctions::cleanUpDynamicByteArrayEndSlotsFunction(ArrayType const& _type) { solAssert(_type.isByteArrayOrString(), ""); solAssert(_type.isDynamicallySized(), ""); std::string functionName = "clean_up_bytearray_end_slots_" + _type.identifier(); return m_functionCollector.createFunction(functionName, [&](std::vector<std::string>& _args, std::vector<std::string>&) { _args = {"array", "len", "startIndex"}; return Whiskers(R"( if gt(len, 31) { let dataArea := <dataLocation>(array) let deleteStart := add(dataArea, <div32Ceil>(startIndex)) // If we are clearing array to be short byte array, we want to clear only data starting from array data area. if lt(startIndex, 32) { deleteStart := dataArea } <clearStorageRange>(deleteStart, add(dataArea, <div32Ceil>(len))) } )") ("dataLocation", arrayDataAreaFunction(_type)) ("div32Ceil", divide32CeilFunction()) ("clearStorageRange", clearStorageRangeFunction(*_type.baseType())) .render(); }); } std::string YulUtilFunctions::decreaseByteArraySizeFunction(ArrayType const& _type) { std::string functionName = "byte_array_decrease_size_" + _type.identifier(); return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(array, data, oldLen, newLen) { switch lt(newLen, 32) case 0 { let arrayDataStart := <dataPosition>(array) let deleteStart := add(arrayDataStart, <div32Ceil>(newLen)) // we have to partially clear last slot that is still used let offset := and(newLen, 0x1f) if offset { <partialClearStorageSlot>(sub(deleteStart, 1), offset) } <clearStorageRange>(deleteStart, add(arrayDataStart, <div32Ceil>(oldLen))) sstore(array, or(mul(2, newLen), 1)) } default { switch gt(oldLen, 31) case 1 { let arrayDataStart := <dataPosition>(array) // clear whole old array, as we are transforming to short bytes array <clearStorageRange>(add(arrayDataStart, 1), add(arrayDataStart, <div32Ceil>(oldLen))) <transitLongToShort>(array, newLen) } default { sstore(array, <encodeUsedSetLen>(data, newLen)) } } })") ("functionName", functionName) ("dataPosition", arrayDataAreaFunction(_type)) ("partialClearStorageSlot", partialClearStorageSlotFunction()) ("clearStorageRange", clearStorageRangeFunction(*_type.baseType())) ("transitLongToShort", byteArrayTransitLongToShortFunction(_type)) ("div32Ceil", divide32CeilFunction()) ("encodeUsedSetLen", shortByteArrayEncodeUsedAreaSetLengthFunction()) .render(); }); } std::string YulUtilFunctions::increaseByteArraySizeFunction(ArrayType const& _type) { std::string functionName = "byte_array_increase_size_" + _type.identifier(); return m_functionCollector.createFunction(functionName, [&](std::vector<std::string>& _args, std::vector<std::string>&) { _args = {"array", "data", "oldLen", "newLen"}; return Whiskers(R"( if gt(newLen, <maxArrayLength>) { <panic>() } switch lt(oldLen, 32) case 0 { // in this case array stays unpacked, so we just set new length sstore(array, add(mul(2, newLen), 1)) } default { switch lt(newLen, 32) case 0 { // we need to copy elements to data area as we changed array from packed to unpacked data := and(not(0xff), data) sstore(<dataPosition>(array), data) sstore(array, add(mul(2, newLen), 1)) } default { // here array stays packed, we just need to increase length sstore(array, <encodeUsedSetLen>(data, newLen)) } } )") ("panic", panicFunction(PanicCode::ResourceError)) ("maxArrayLength", (u256(1) << 64).str()) ("dataPosition", arrayDataAreaFunction(_type)) ("encodeUsedSetLen", shortByteArrayEncodeUsedAreaSetLengthFunction()) .render(); }); } std::string YulUtilFunctions::byteArrayTransitLongToShortFunction(ArrayType const& _type) { std::string functionName = "transit_byte_array_long_to_short_" + _type.identifier(); return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(array, len) { // we need to copy elements from old array to new // we want to copy only elements that are part of the array after resizing let dataPos := <dataPosition>(array) let data := <extractUsedApplyLen>(sload(dataPos), len) sstore(array, data) sstore(dataPos, 0) })") ("functionName", functionName) ("dataPosition", arrayDataAreaFunction(_type)) ("extractUsedApplyLen", shortByteArrayEncodeUsedAreaSetLengthFunction()) .render(); }); } std::string YulUtilFunctions::shortByteArrayEncodeUsedAreaSetLengthFunction() { std::string functionName = "extract_used_part_and_set_length_of_short_byte_array"; return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(data, len) -> used { // we want to save only elements that are part of the array after resizing // others should be set to zero data := <maskBytes>(data, len) used := or(data, mul(2, len)) })") ("functionName", functionName) ("maskBytes", maskBytesFunctionDynamic()) .render(); }); } std::string YulUtilFunctions::longByteArrayStorageIndexAccessNoCheckFunction() { return m_functionCollector.createFunction( "long_byte_array_index_access_no_checks", [&](std::vector<std::string>& _args, std::vector<std::string>& _returnParams) { _args = {"array", "index"}; _returnParams = {"slot", "offset"}; return Whiskers(R"( offset := sub(31, mod(index, 0x20)) let dataArea := <dataAreaFunc>(array) slot := add(dataArea, div(index, 0x20)) )") ("dataAreaFunc", arrayDataAreaFunction(*TypeProvider::bytesStorage())) .render(); } ); } std::string YulUtilFunctions::storageArrayPopFunction(ArrayType const& _type) { solAssert(_type.location() == DataLocation::Storage, ""); solAssert(_type.isDynamicallySized(), ""); solUnimplementedAssert(_type.baseType()->storageBytes() <= 32, "Base type is not yet implemented."); if (_type.isByteArrayOrString()) return storageByteArrayPopFunction(_type); std::string functionName = "array_pop_" + _type.identifier(); return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(array) { let oldLen := <fetchLength>(array) if iszero(oldLen) { <panic>() } let newLen := sub(oldLen, 1) let slot, offset := <indexAccess>(array, newLen) <?+setToZero><setToZero>(slot, offset)</+setToZero> sstore(array, newLen) })") ("functionName", functionName) ("panic", panicFunction(PanicCode::EmptyArrayPop)) ("fetchLength", arrayLengthFunction(_type)) ("indexAccess", storageArrayIndexAccessFunction(_type)) ( "setToZero", _type.baseType()->category() != Type::Category::Mapping ? storageSetToZeroFunction(*_type.baseType(), VariableDeclaration::Location::Unspecified) : "" ) .render(); }); } std::string YulUtilFunctions::storageByteArrayPopFunction(ArrayType const& _type) { solAssert(_type.location() == DataLocation::Storage, ""); solAssert(_type.isDynamicallySized(), ""); solAssert(_type.isByteArrayOrString(), ""); std::string functionName = "byte_array_pop_" + _type.identifier(); return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(array) { let data := sload(array) let oldLen := <extractByteArrayLength>(data) if iszero(oldLen) { <panic>() } switch oldLen case 32 { // Here we have a special case where array transitions to shorter than 32 // So we need to copy data <transitLongToShort>(array, 31) } default { let newLen := sub(oldLen, 1) switch lt(oldLen, 32) case 1 { sstore(array, <encodeUsedSetLen>(data, newLen)) } default { let slot, offset := <indexAccessNoChecks>(array, newLen) <setToZero>(slot, offset) sstore(array, sub(data, 2)) } } })") ("functionName", functionName) ("panic", panicFunction(PanicCode::EmptyArrayPop)) ("extractByteArrayLength", extractByteArrayLengthFunction()) ("transitLongToShort", byteArrayTransitLongToShortFunction(_type)) ("encodeUsedSetLen", shortByteArrayEncodeUsedAreaSetLengthFunction()) ("indexAccessNoChecks", longByteArrayStorageIndexAccessNoCheckFunction()) ("setToZero", storageSetToZeroFunction(*_type.baseType(), VariableDeclaration::Location::Unspecified)) .render(); }); } std::string YulUtilFunctions::storageArrayPushFunction(ArrayType const& _type, Type const* _fromType) { solAssert(_type.location() == DataLocation::Storage, ""); solAssert(_type.isDynamicallySized(), ""); if (!_fromType) _fromType = _type.baseType(); else if (_fromType->isValueType()) solUnimplementedAssert(*_fromType == *_type.baseType()); std::string functionName = std::string{"array_push_from_"} + _fromType->identifier() + "_to_" + _type.identifier(); return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(array <values>) { <?isByteArrayOrString> let data := sload(array) let oldLen := <extractByteArrayLength>(data) if iszero(lt(oldLen, <maxArrayLength>)) { <panic>() } switch gt(oldLen, 31) case 0 { let value := byte(0 <values>) switch oldLen case 31 { // Here we have special case when array switches from short array to long array // We need to copy data let dataArea := <dataAreaFunction>(array) data := and(data, not(0xff)) sstore(dataArea, or(and(0xff, value), data)) // New length is 32, encoded as (32 * 2 + 1) sstore(array, 65) } default { data := add(data, 2) let shiftBits := mul(8, sub(31, oldLen)) let valueShifted := <shl>(shiftBits, and(0xff, value)) let mask := <shl>(shiftBits, 0xff) data := or(and(data, not(mask)), valueShifted) sstore(array, data) } } default { sstore(array, add(data, 2)) let slot, offset := <indexAccess>(array, oldLen) <storeValue>(slot, offset <values>) } <!isByteArrayOrString> let oldLen := sload(array) if iszero(lt(oldLen, <maxArrayLength>)) { <panic>() } sstore(array, add(oldLen, 1)) let slot, offset := <indexAccess>(array, oldLen) <storeValue>(slot, offset <values>) </isByteArrayOrString> })") ("functionName", functionName) ("values", _fromType->sizeOnStack() == 0 ? "" : ", " + suffixedVariableNameList("value", 0, _fromType->sizeOnStack())) ("panic", panicFunction(PanicCode::ResourceError)) ("extractByteArrayLength", _type.isByteArrayOrString() ? extractByteArrayLengthFunction() : "") ("dataAreaFunction", arrayDataAreaFunction(_type)) ("isByteArrayOrString", _type.isByteArrayOrString()) ("indexAccess", storageArrayIndexAccessFunction(_type)) ("storeValue", updateStorageValueFunction(*_fromType, *_type.baseType(), VariableDeclaration::Location::Unspecified)) ("maxArrayLength", (u256(1) << 64).str()) ("shl", shiftLeftFunctionDynamic()) .render(); }); } std::string YulUtilFunctions::storageArrayPushZeroFunction(ArrayType const& _type) { solAssert(_type.location() == DataLocation::Storage, ""); solAssert(_type.isDynamicallySized(), ""); solUnimplementedAssert(_type.baseType()->storageBytes() <= 32, "Base type is not yet implemented."); std::string functionName = "array_push_zero_" + _type.identifier(); return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(array) -> slot, offset { <?isBytes> let data := sload(array) let oldLen := <extractLength>(data) <increaseBytesSize>(array, data, oldLen, add(oldLen, 1)) <!isBytes> let oldLen := <fetchLength>(array) if iszero(lt(oldLen, <maxArrayLength>)) { <panic>() } sstore(array, add(oldLen, 1)) </isBytes> slot, offset := <indexAccess>(array, oldLen) })") ("functionName", functionName) ("isBytes", _type.isByteArrayOrString()) ("increaseBytesSize", _type.isByteArrayOrString() ? increaseByteArraySizeFunction(_type) : "") ("extractLength", _type.isByteArrayOrString() ? extractByteArrayLengthFunction() : "") ("panic", panicFunction(PanicCode::ResourceError)) ("fetchLength", arrayLengthFunction(_type)) ("indexAccess", storageArrayIndexAccessFunction(_type)) ("maxArrayLength", (u256(1) << 64).str()) .render(); }); } std::string YulUtilFunctions::partialClearStorageSlotFunction() { std::string functionName = "partial_clear_storage_slot"; return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(slot, offset) { let mask := <shr>(mul(8, sub(32, offset)), <ones>) sstore(slot, and(mask, sload(slot))) } )") ("functionName", functionName) ("ones", formatNumber((bigint(1) << 256) - 1)) ("shr", shiftRightFunctionDynamic()) .render(); }); } std::string YulUtilFunctions::clearStorageRangeFunction(Type const& _type) { if (_type.storageBytes() < 32) solAssert(_type.isValueType(), ""); std::string functionName = "clear_storage_range_" + _type.identifier(); return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(start, end) { for {} lt(start, end) { start := add(start, <increment>) } { <setToZero>(start, 0) } } )") ("functionName", functionName) ("setToZero", storageSetToZeroFunction(_type.storageBytes() < 32 ? *TypeProvider::uint256() : _type, VariableDeclaration::Location::Unspecified)) ("increment", _type.storageSize().str()) .render(); }); } std::string YulUtilFunctions::clearStorageArrayFunction(ArrayType const& _type) { solAssert(_type.location() == DataLocation::Storage, ""); if (_type.baseType()->storageBytes() < 32) { solAssert(_type.baseType()->isValueType(), "Invalid storage size for non-value type."); solAssert(_type.baseType()->storageSize() <= 1, "Invalid storage size for type."); } if (_type.baseType()->isValueType()) solAssert(_type.baseType()->storageSize() <= 1, "Invalid size for value type."); std::string functionName = "clear_storage_array_" + _type.identifier(); return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(slot) { <?dynamic> <resizeArray>(slot, 0) <!dynamic> <?+clearRange><clearRange>(slot, add(slot, <lenToSize>(<len>)))</+clearRange> </dynamic> } )") ("functionName", functionName) ("dynamic", _type.isDynamicallySized()) ("resizeArray", _type.isDynamicallySized() ? resizeArrayFunction(_type) : "") ( "clearRange", _type.baseType()->category() != Type::Category::Mapping ? clearStorageRangeFunction((_type.baseType()->storageBytes() < 32) ? *TypeProvider::uint256() : *_type.baseType()) : "" ) ("lenToSize", arrayConvertLengthToSize(_type)) ("len", _type.length().str()) .render(); }); } std::string YulUtilFunctions::clearStorageStructFunction(StructType const& _type) { solAssert(_type.location() == DataLocation::Storage, ""); std::string functionName = "clear_struct_storage_" + _type.identifier(); return m_functionCollector.createFunction(functionName, [&] { MemberList::MemberMap structMembers = _type.nativeMembers(nullptr); std::vector<std::map<std::string, std::string>> memberSetValues; std::set<u256> slotsCleared; for (auto const& member: structMembers) { if (member.type->category() == Type::Category::Mapping) continue; if (member.type->storageBytes() < 32) { auto const& slotDiff = _type.storageOffsetsOfMember(member.name).first; if (!slotsCleared.count(slotDiff)) { memberSetValues.emplace_back().emplace("clearMember", "sstore(add(slot, " + slotDiff.str() + "), 0)"); slotsCleared.emplace(slotDiff); } } else { auto const& [memberSlotDiff, memberStorageOffset] = _type.storageOffsetsOfMember(member.name); solAssert(memberStorageOffset == 0, ""); memberSetValues.emplace_back().emplace("clearMember", Whiskers(R"( <setZero>(add(slot, <memberSlotDiff>), <memberStorageOffset>) )") ("setZero", storageSetToZeroFunction(*member.type, VariableDeclaration::Location::Unspecified)) ("memberSlotDiff", memberSlotDiff.str()) ("memberStorageOffset", std::to_string(memberStorageOffset)) .render() ); } } return Whiskers(R"( function <functionName>(slot) { <#member> <clearMember> </member> } )") ("functionName", functionName) ("member", memberSetValues) .render(); }); } std::string YulUtilFunctions::copyArrayToStorageFunction(ArrayType const& _fromType, ArrayType const& _toType) { solAssert( (*_fromType.copyForLocation(_toType.location(), _toType.isPointer())).equals(dynamic_cast<ReferenceType const&>(_toType)), "" ); if (!_toType.isDynamicallySized()) solAssert(!_fromType.isDynamicallySized() && _fromType.length() <= _toType.length(), ""); if (_fromType.isByteArrayOrString()) return copyByteArrayToStorageFunction(_fromType, _toType); if (_toType.baseType()->isValueType()) return copyValueArrayToStorageFunction(_fromType, _toType); solAssert(_toType.storageStride() == 32); solAssert(!_fromType.baseType()->isValueType()); std::string functionName = "copy_array_to_storage_from_" + _fromType.identifier() + "_to_" + _toType.identifier(); return m_functionCollector.createFunction(functionName, [&](){ Whiskers templ(R"( function <functionName>(slot, value<?isFromDynamicCalldata>, len</isFromDynamicCalldata>) { <?fromStorage> if eq(slot, value) { leave } </fromStorage> let length := <arrayLength>(value<?isFromDynamicCalldata>, len</isFromDynamicCalldata>) <resizeArray>(slot, length) let srcPtr := <srcDataLocation>(value) let elementSlot := <dstDataLocation>(slot) for { let i := 0 } lt(i, length) {i := add(i, 1)} { <?fromCalldata> let <stackItems> := <?dynamicallyEncodedBase> <accessCalldataTail>(value, srcPtr) <!dynamicallyEncodedBase> srcPtr </dynamicallyEncodedBase> </fromCalldata> <?fromMemory> let <stackItems> := <readFromMemoryOrCalldata>(srcPtr) </fromMemory> <?fromStorage> let <stackItems> := srcPtr </fromStorage> <updateStorageValue>(elementSlot, <stackItems>) srcPtr := add(srcPtr, <srcStride>) elementSlot := add(elementSlot, <storageSize>) } } )"); if (_fromType.dataStoredIn(DataLocation::Storage)) solAssert(!_fromType.isValueType(), ""); templ("functionName", functionName); bool fromCalldata = _fromType.dataStoredIn(DataLocation::CallData); templ("isFromDynamicCalldata", _fromType.isDynamicallySized() && fromCalldata); templ("fromStorage", _fromType.dataStoredIn(DataLocation::Storage)); bool fromMemory = _fromType.dataStoredIn(DataLocation::Memory); templ("fromMemory", fromMemory); templ("fromCalldata", fromCalldata); templ("srcDataLocation", arrayDataAreaFunction(_fromType)); if (fromCalldata) { templ("dynamicallyEncodedBase", _fromType.baseType()->isDynamicallyEncoded()); if (_fromType.baseType()->isDynamicallyEncoded()) templ("accessCalldataTail", accessCalldataTailFunction(*_fromType.baseType())); } templ("resizeArray", resizeArrayFunction(_toType)); templ("arrayLength",arrayLengthFunction(_fromType)); templ("dstDataLocation", arrayDataAreaFunction(_toType)); if (fromMemory || (fromCalldata && _fromType.baseType()->isValueType())) templ("readFromMemoryOrCalldata", readFromMemoryOrCalldata(*_fromType.baseType(), fromCalldata)); templ("stackItems", suffixedVariableNameList( "stackItem_", 0, _fromType.baseType()->stackItems().size() )); templ("updateStorageValue", updateStorageValueFunction(*_fromType.baseType(), *_toType.baseType(), VariableDeclaration::Location::Unspecified, 0)); templ("srcStride", fromCalldata ? std::to_string(_fromType.calldataStride()) : fromMemory ? std::to_string(_fromType.memoryStride()) : formatNumber(_fromType.baseType()->storageSize()) ); templ("storageSize", _toType.baseType()->storageSize().str()); return templ.render(); }); } std::string YulUtilFunctions::copyByteArrayToStorageFunction(ArrayType const& _fromType, ArrayType const& _toType) { solAssert( (*_fromType.copyForLocation(_toType.location(), _toType.isPointer())).equals(dynamic_cast<ReferenceType const&>(_toType)), "" ); solAssert(_fromType.isByteArrayOrString(), ""); solAssert(_toType.isByteArrayOrString(), ""); std::string functionName = "copy_byte_array_to_storage_from_" + _fromType.identifier() + "_to_" + _toType.identifier(); return m_functionCollector.createFunction(functionName, [&](){ Whiskers templ(R"( function <functionName>(slot, src<?fromCalldata>, len</fromCalldata>) { <?fromStorage> if eq(slot, src) { leave } </fromStorage> let newLen := <arrayLength>(src<?fromCalldata>, len</fromCalldata>) // Make sure array length is sane if gt(newLen, 0xffffffffffffffff) { <panic>() } let oldLen := <byteArrayLength>(sload(slot)) // potentially truncate data <cleanUpEndArray>(slot, oldLen, newLen) let srcOffset := 0 <?fromMemory> srcOffset := 0x20 </fromMemory> switch gt(newLen, 31) case 1 { let loopEnd := and(newLen, not(0x1f)) <?fromStorage> src := <srcDataLocation>(src) </fromStorage> let dstPtr := <dstDataLocation>(slot) let i := 0 for { } lt(i, loopEnd) { i := add(i, 0x20) } { sstore(dstPtr, <read>(add(src, srcOffset))) dstPtr := add(dstPtr, 1) srcOffset := add(srcOffset, <srcIncrement>) } if lt(loopEnd, newLen) { let lastValue := <read>(add(src, srcOffset)) sstore(dstPtr, <maskBytes>(lastValue, and(newLen, 0x1f))) } sstore(slot, add(mul(newLen, 2), 1)) } default { let value := 0 if newLen { value := <read>(add(src, srcOffset)) } sstore(slot, <byteArrayCombineShort>(value, newLen)) } } )"); templ("functionName", functionName); bool fromStorage = _fromType.dataStoredIn(DataLocation::Storage); templ("fromStorage", fromStorage); bool fromCalldata = _fromType.dataStoredIn(DataLocation::CallData); templ("fromMemory", _fromType.dataStoredIn(DataLocation::Memory)); templ("fromCalldata", fromCalldata); templ("arrayLength", arrayLengthFunction(_fromType)); templ("panic", panicFunction(PanicCode::ResourceError)); templ("byteArrayLength", extractByteArrayLengthFunction()); templ("dstDataLocation", arrayDataAreaFunction(_toType)); if (fromStorage) templ("srcDataLocation", arrayDataAreaFunction(_fromType)); templ("cleanUpEndArray", cleanUpDynamicByteArrayEndSlotsFunction(_toType)); templ("srcIncrement", std::to_string(fromStorage ? 1 : 0x20)); templ("read", fromStorage ? "sload" : fromCalldata ? "calldataload" : "mload"); templ("maskBytes", maskBytesFunctionDynamic()); templ("byteArrayCombineShort", shortByteArrayEncodeUsedAreaSetLengthFunction()); return templ.render(); }); } std::string YulUtilFunctions::copyValueArrayToStorageFunction(ArrayType const& _fromType, ArrayType const& _toType) { solAssert(_fromType.baseType()->isValueType(), ""); solAssert(_toType.baseType()->isValueType(), ""); solAssert(_fromType.baseType()->isImplicitlyConvertibleTo(*_toType.baseType()), ""); solAssert(!_fromType.isByteArrayOrString(), ""); solAssert(!_toType.isByteArrayOrString(), ""); solAssert(_toType.dataStoredIn(DataLocation::Storage), ""); solAssert(_fromType.storageStride() <= _toType.storageStride(), ""); solAssert(_toType.storageStride() <= 32, ""); std::string functionName = "copy_array_to_storage_from_" + _fromType.identifier() + "_to_" + _toType.identifier(); return m_functionCollector.createFunction(functionName, [&](){ Whiskers templ(R"( function <functionName>(dst, src<?isFromDynamicCalldata>, len</isFromDynamicCalldata>) { <?isFromStorage> if eq(dst, src) { leave } </isFromStorage> let length := <arrayLength>(src<?isFromDynamicCalldata>, len</isFromDynamicCalldata>) // Make sure array length is sane if gt(length, 0xffffffffffffffff) { <panic>() } <resizeArray>(dst, length) let srcPtr := <srcDataLocation>(src) let dstSlot := <dstDataLocation>(dst) let fullSlots := div(length, <itemsPerSlot>) <?isFromStorage> let srcSlotValue := sload(srcPtr) let srcItemIndexInSlot := 0 </isFromStorage> for { let i := 0 } lt(i, fullSlots) { i := add(i, 1) } { let dstSlotValue := 0 <?sameTypeFromStorage> dstSlotValue := <maskFull>(srcSlotValue) <updateSrcPtr> <!sameTypeFromStorage> <?multipleItemsPerSlotDst>for { let j := 0 } lt(j, <itemsPerSlot>) { j := add(j, 1) } </multipleItemsPerSlotDst> { <?isFromStorage> let <stackItems> := <convert>( <extractFromSlot>(srcSlotValue, mul(<srcStride>, srcItemIndexInSlot)) ) <!isFromStorage> let <stackItems> := <readFromMemoryOrCalldata>(srcPtr) </isFromStorage> let itemValue := <prepareStore>(<stackItems>) dstSlotValue := <?multipleItemsPerSlotDst> <updateByteSlice>(dstSlotValue, mul(<dstStride>, j), itemValue) <!multipleItemsPerSlotDst> itemValue </multipleItemsPerSlotDst> <updateSrcPtr> } </sameTypeFromStorage> sstore(add(dstSlot, i), dstSlotValue) } <?multipleItemsPerSlotDst> let spill := sub(length, mul(fullSlots, <itemsPerSlot>)) if gt(spill, 0) { let dstSlotValue := 0 <?sameTypeFromStorage> dstSlotValue := <maskBytes>(srcSlotValue, mul(spill, <srcStride>)) <updateSrcPtr> <!sameTypeFromStorage> for { let j := 0 } lt(j, spill) { j := add(j, 1) } { <?isFromStorage> let <stackItems> := <convert>( <extractFromSlot>(srcSlotValue, mul(<srcStride>, srcItemIndexInSlot)) ) <!isFromStorage> let <stackItems> := <readFromMemoryOrCalldata>(srcPtr) </isFromStorage> let itemValue := <prepareStore>(<stackItems>) dstSlotValue := <updateByteSlice>(dstSlotValue, mul(<dstStride>, j), itemValue) <updateSrcPtr> } </sameTypeFromStorage> sstore(add(dstSlot, fullSlots), dstSlotValue) } </multipleItemsPerSlotDst> } )"); if (_fromType.dataStoredIn(DataLocation::Storage)) solAssert(!_fromType.isValueType(), ""); bool fromCalldata = _fromType.dataStoredIn(DataLocation::CallData); bool fromStorage = _fromType.dataStoredIn(DataLocation::Storage); templ("functionName", functionName); templ("resizeArray", resizeArrayFunction(_toType)); templ("arrayLength", arrayLengthFunction(_fromType)); templ("panic", panicFunction(PanicCode::ResourceError)); templ("isFromDynamicCalldata", _fromType.isDynamicallySized() && fromCalldata); templ("isFromStorage", fromStorage); templ("readFromMemoryOrCalldata", readFromMemoryOrCalldata(*_fromType.baseType(), fromCalldata)); templ("srcDataLocation", arrayDataAreaFunction(_fromType)); templ("dstDataLocation", arrayDataAreaFunction(_toType)); templ("srcStride", std::to_string(_fromType.storageStride())); templ("stackItems", suffixedVariableNameList( "stackItem_", 0, _fromType.baseType()->stackItems().size() )); unsigned itemsPerSlot = 32 / _toType.storageStride(); templ("itemsPerSlot", std::to_string(itemsPerSlot)); templ("multipleItemsPerSlotDst", itemsPerSlot > 1); bool sameTypeFromStorage = fromStorage && (*_fromType.baseType() == *_toType.baseType()); if (auto functionType = dynamic_cast<FunctionType const*>(_fromType.baseType())) { solAssert(functionType->equalExcludingStateMutability( dynamic_cast<FunctionType const&>(*_toType.baseType()) )); sameTypeFromStorage = fromStorage; } templ("sameTypeFromStorage", sameTypeFromStorage); if (sameTypeFromStorage) { templ("maskFull", maskLowerOrderBytesFunction(itemsPerSlot * _toType.storageStride())); templ("maskBytes", maskLowerOrderBytesFunctionDynamic()); } else { templ("dstStride", std::to_string(_toType.storageStride())); templ("extractFromSlot", extractFromStorageValueDynamic(*_fromType.baseType())); templ("updateByteSlice", updateByteSliceFunctionDynamic(_toType.storageStride())); templ("convert", conversionFunction(*_fromType.baseType(), *_toType.baseType())); templ("prepareStore", prepareStoreFunction(*_toType.baseType())); } if (fromStorage) templ("updateSrcPtr", Whiskers(R"( <?srcReadMultiPerSlot> srcItemIndexInSlot := add(srcItemIndexInSlot, 1) if eq(srcItemIndexInSlot, <srcItemsPerSlot>) { // here we are done with this slot, we need to read next one srcPtr := add(srcPtr, 1) srcSlotValue := sload(srcPtr) srcItemIndexInSlot := 0 } <!srcReadMultiPerSlot> srcPtr := add(srcPtr, 1) srcSlotValue := sload(srcPtr) </srcReadMultiPerSlot> )") ("srcReadMultiPerSlot", !sameTypeFromStorage && _fromType.storageStride() <= 16) ("srcItemsPerSlot", std::to_string(32 / _fromType.storageStride())) .render() ); else templ("updateSrcPtr", Whiskers(R"( srcPtr := add(srcPtr, <srcStride>) )") ("srcStride", fromCalldata ? std::to_string(_fromType.calldataStride()) : std::to_string(_fromType.memoryStride())) .render() ); return templ.render(); }); } std::string YulUtilFunctions::arrayConvertLengthToSize(ArrayType const& _type) { std::string functionName = "array_convert_length_to_size_" + _type.identifier(); return m_functionCollector.createFunction(functionName, [&]() { Type const& baseType = *_type.baseType(); switch (_type.location()) { case DataLocation::Storage: { unsigned const baseStorageBytes = baseType.storageBytes(); solAssert(baseStorageBytes > 0, ""); solAssert(32 / baseStorageBytes > 0, ""); return Whiskers(R"( function <functionName>(length) -> size { size := length <?multiSlot> size := <mul>(<storageSize>, length) <!multiSlot> // Number of slots rounded up size := div(add(length, sub(<itemsPerSlot>, 1)), <itemsPerSlot>) </multiSlot> })") ("functionName", functionName) ("multiSlot", baseType.storageSize() > 1) ("itemsPerSlot", std::to_string(32 / baseStorageBytes)) ("storageSize", baseType.storageSize().str()) ("mul", overflowCheckedIntMulFunction(*TypeProvider::uint256())) .render(); } case DataLocation::CallData: // fallthrough case DataLocation::Memory: return Whiskers(R"( function <functionName>(length) -> size { <?byteArray> size := length <!byteArray> size := <mul>(length, <stride>) </byteArray> })") ("functionName", functionName) ("stride", std::to_string(_type.location() == DataLocation::Memory ? _type.memoryStride() : _type.calldataStride())) ("byteArray", _type.isByteArrayOrString()) ("mul", overflowCheckedIntMulFunction(*TypeProvider::uint256())) .render(); default: solAssert(false, ""); } }); } std::string YulUtilFunctions::arrayAllocationSizeFunction(ArrayType const& _type) { solAssert(_type.dataStoredIn(DataLocation::Memory), ""); std::string functionName = "array_allocation_size_" + _type.identifier(); return m_functionCollector.createFunction(functionName, [&]() { Whiskers w(R"( function <functionName>(length) -> size { // Make sure we can allocate memory without overflow if gt(length, 0xffffffffffffffff) { <panic>() } <?byteArray> size := <roundUp>(length) <!byteArray> size := mul(length, 0x20) </byteArray> <?dynamic> // add length slot size := add(size, 0x20) </dynamic> } )"); w("functionName", functionName); w("panic", panicFunction(PanicCode::ResourceError)); w("byteArray", _type.isByteArrayOrString()); w("roundUp", roundUpFunction()); w("dynamic", _type.isDynamicallySized()); return w.render(); }); } std::string YulUtilFunctions::arrayDataAreaFunction(ArrayType const& _type) { std::string functionName = "array_dataslot_" + _type.identifier(); return m_functionCollector.createFunction(functionName, [&]() { // No special processing for calldata arrays, because they are stored as // offset of the data area and length on the stack, so the offset already // points to the data area. // This might change, if calldata arrays are stored in a single // stack slot at some point. return Whiskers(R"( function <functionName>(ptr) -> data { data := ptr <?dynamic> <?memory> data := add(ptr, 0x20) </memory> <?storage> mstore(0, ptr) data := keccak256(0, 0x20) </storage> </dynamic> } )") ("functionName", functionName) ("dynamic", _type.isDynamicallySized()) ("memory", _type.location() == DataLocation::Memory) ("storage", _type.location() == DataLocation::Storage) .render(); }); } std::string YulUtilFunctions::storageArrayIndexAccessFunction(ArrayType const& _type) { std::string functionName = "storage_array_index_access_" + _type.identifier(); return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(array, index) -> slot, offset { let arrayLength := <arrayLen>(array) if iszero(lt(index, arrayLength)) { <panic>() } <?multipleItemsPerSlot> <?isBytesArray> switch lt(arrayLength, 0x20) case 0 { slot, offset := <indexAccessNoChecks>(array, index) } default { offset := sub(31, mod(index, 0x20)) slot := array } <!isBytesArray> let dataArea := <dataAreaFunc>(array) slot := add(dataArea, div(index, <itemsPerSlot>)) offset := mul(mod(index, <itemsPerSlot>), <storageBytes>) </isBytesArray> <!multipleItemsPerSlot> let dataArea := <dataAreaFunc>(array) slot := add(dataArea, mul(index, <storageSize>)) offset := 0 </multipleItemsPerSlot> } )") ("functionName", functionName) ("panic", panicFunction(PanicCode::ArrayOutOfBounds)) ("arrayLen", arrayLengthFunction(_type)) ("dataAreaFunc", arrayDataAreaFunction(_type)) ("indexAccessNoChecks", longByteArrayStorageIndexAccessNoCheckFunction()) ("multipleItemsPerSlot", _type.baseType()->storageBytes() <= 16) ("isBytesArray", _type.isByteArrayOrString()) ("storageSize", _type.baseType()->storageSize().str()) ("storageBytes", toString(_type.baseType()->storageBytes())) ("itemsPerSlot", std::to_string(32 / _type.baseType()->storageBytes())) .render(); }); } std::string YulUtilFunctions::memoryArrayIndexAccessFunction(ArrayType const& _type) { std::string functionName = "memory_array_index_access_" + _type.identifier(); return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(baseRef, index) -> addr { if iszero(lt(index, <arrayLen>(baseRef))) { <panic>() } let offset := mul(index, <stride>) <?dynamicallySized> offset := add(offset, 32) </dynamicallySized> addr := add(baseRef, offset) } )") ("functionName", functionName) ("panic", panicFunction(PanicCode::ArrayOutOfBounds)) ("arrayLen", arrayLengthFunction(_type)) ("stride", std::to_string(_type.memoryStride())) ("dynamicallySized", _type.isDynamicallySized()) .render(); }); } std::string YulUtilFunctions::calldataArrayIndexAccessFunction(ArrayType const& _type) { solAssert(_type.dataStoredIn(DataLocation::CallData), ""); std::string functionName = "calldata_array_index_access_" + _type.identifier(); return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(base_ref<?dynamicallySized>, length</dynamicallySized>, index) -> addr<?dynamicallySizedBase>, len</dynamicallySizedBase> { if iszero(lt(index, <?dynamicallySized>length<!dynamicallySized><arrayLen></dynamicallySized>)) { <panic>() } addr := add(base_ref, mul(index, <stride>)) <?dynamicallyEncodedBase> addr<?dynamicallySizedBase>, len</dynamicallySizedBase> := <accessCalldataTail>(base_ref, addr) </dynamicallyEncodedBase> } )") ("functionName", functionName) ("panic", panicFunction(PanicCode::ArrayOutOfBounds)) ("stride", std::to_string(_type.calldataStride())) ("dynamicallySized", _type.isDynamicallySized()) ("dynamicallyEncodedBase", _type.baseType()->isDynamicallyEncoded()) ("dynamicallySizedBase", _type.baseType()->isDynamicallySized()) ("arrayLen", toCompactHexWithPrefix(_type.length())) ("accessCalldataTail", _type.baseType()->isDynamicallyEncoded() ? accessCalldataTailFunction(*_type.baseType()): "") .render(); }); } std::string YulUtilFunctions::calldataArrayIndexRangeAccess(ArrayType const& _type) { solAssert(_type.dataStoredIn(DataLocation::CallData), ""); solAssert(_type.isDynamicallySized(), ""); std::string functionName = "calldata_array_index_range_access_" + _type.identifier(); return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(offset, length, startIndex, endIndex) -> offsetOut, lengthOut { if gt(startIndex, endIndex) { <revertSliceStartAfterEnd>() } if gt(endIndex, length) { <revertSliceGreaterThanLength>() } offsetOut := add(offset, mul(startIndex, <stride>)) lengthOut := sub(endIndex, startIndex) } )") ("functionName", functionName) ("stride", std::to_string(_type.calldataStride())) ("revertSliceStartAfterEnd", revertReasonIfDebugFunction("Slice starts after end")) ("revertSliceGreaterThanLength", revertReasonIfDebugFunction("Slice is greater than length")) .render(); }); } std::string YulUtilFunctions::accessCalldataTailFunction(Type const& _type) { solAssert(_type.isDynamicallyEncoded(), ""); solAssert(_type.dataStoredIn(DataLocation::CallData), ""); std::string functionName = "access_calldata_tail_" + _type.identifier(); return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(base_ref, ptr_to_tail) -> addr<?dynamicallySized>, length</dynamicallySized> { let rel_offset_of_tail := calldataload(ptr_to_tail) if iszero(slt(rel_offset_of_tail, sub(sub(calldatasize(), base_ref), sub(<neededLength>, 1)))) { <invalidCalldataTailOffset>() } addr := add(base_ref, rel_offset_of_tail) <?dynamicallySized> length := calldataload(addr) if gt(length, 0xffffffffffffffff) { <invalidCalldataTailLength>() } addr := add(addr, 32) if sgt(addr, sub(calldatasize(), mul(length, <calldataStride>))) { <shortCalldataTail>() } </dynamicallySized> } )") ("functionName", functionName) ("dynamicallySized", _type.isDynamicallySized()) ("neededLength", toCompactHexWithPrefix(_type.calldataEncodedTailSize())) ("calldataStride", toCompactHexWithPrefix(_type.isDynamicallySized() ? dynamic_cast<ArrayType const&>(_type).calldataStride() : 0)) ("invalidCalldataTailOffset", revertReasonIfDebugFunction("Invalid calldata tail offset")) ("invalidCalldataTailLength", revertReasonIfDebugFunction("Invalid calldata tail length")) ("shortCalldataTail", revertReasonIfDebugFunction("Calldata tail too short")) .render(); }); } std::string YulUtilFunctions::nextArrayElementFunction(ArrayType const& _type) { solAssert(!_type.isByteArrayOrString(), ""); if (_type.dataStoredIn(DataLocation::Storage)) solAssert(_type.baseType()->storageBytes() > 16, ""); std::string functionName = "array_nextElement_" + _type.identifier(); return m_functionCollector.createFunction(functionName, [&]() { Whiskers templ(R"( function <functionName>(ptr) -> next { next := add(ptr, <advance>) } )"); templ("functionName", functionName); switch (_type.location()) { case DataLocation::Memory: templ("advance", "0x20"); break; case DataLocation::Storage: { u256 size = _type.baseType()->storageSize(); solAssert(size >= 1, ""); templ("advance", toCompactHexWithPrefix(size)); break; } case DataLocation::Transient: solUnimplemented("Transient data location is only supported for value types."); break; case DataLocation::CallData: { u256 size = _type.calldataStride(); solAssert(size >= 32 && size % 32 == 0, ""); templ("advance", toCompactHexWithPrefix(size)); break; } } return templ.render(); }); } std::string YulUtilFunctions::copyArrayFromStorageToMemoryFunction(ArrayType const& _from, ArrayType const& _to) { solAssert(_from.dataStoredIn(DataLocation::Storage), ""); solAssert(_to.dataStoredIn(DataLocation::Memory), ""); solAssert(_from.isDynamicallySized() == _to.isDynamicallySized(), ""); if (!_from.isDynamicallySized()) solAssert(_from.length() == _to.length(), ""); std::string functionName = "copy_array_from_storage_to_memory_" + _from.identifier(); return m_functionCollector.createFunction(functionName, [&]() { if (_from.baseType()->isValueType()) { solAssert(*_from.baseType() == *_to.baseType(), ""); ABIFunctions abi(m_evmVersion, m_revertStrings, m_functionCollector); return Whiskers(R"( function <functionName>(slot) -> memPtr { memPtr := <allocateUnbounded>() let end := <encode>(slot, memPtr) <finalizeAllocation>(memPtr, sub(end, memPtr)) } )") ("functionName", functionName) ("allocateUnbounded", allocateUnboundedFunction()) ( "encode", abi.abiEncodeAndReturnUpdatedPosFunction(_from, _to, ABIFunctions::EncodingOptions{}) ) ("finalizeAllocation", finalizeAllocationFunction()) .render(); } else { solAssert(_to.memoryStride() == 32, ""); solAssert(_to.baseType()->dataStoredIn(DataLocation::Memory), ""); solAssert(_from.baseType()->dataStoredIn(DataLocation::Storage), ""); solAssert(!_from.isByteArrayOrString(), ""); solAssert(*_to.withLocation(DataLocation::Storage, _from.isPointer()) == _from, ""); return Whiskers(R"( function <functionName>(slot) -> memPtr { let length := <lengthFunction>(slot) memPtr := <allocateArray>(length) let mpos := memPtr <?dynamic>mpos := add(mpos, 0x20)</dynamic> let spos := <arrayDataArea>(slot) for { let i := 0 } lt(i, length) { i := add(i, 1) } { mstore(mpos, <convert>(spos)) mpos := add(mpos, 0x20) spos := add(spos, <baseStorageSize>) } } )") ("functionName", functionName) ("lengthFunction", arrayLengthFunction(_from)) ("allocateArray", allocateMemoryArrayFunction(_to)) ("arrayDataArea", arrayDataAreaFunction(_from)) ("dynamic", _to.isDynamicallySized()) ("convert", conversionFunction(*_from.baseType(), *_to.baseType())) ("baseStorageSize", _from.baseType()->storageSize().str()) .render(); } }); } std::string YulUtilFunctions::bytesOrStringConcatFunction( std::vector<Type const*> const& _argumentTypes, FunctionType::Kind _functionTypeKind ) { solAssert(_functionTypeKind == FunctionType::Kind::BytesConcat || _functionTypeKind == FunctionType::Kind::StringConcat); std::string functionName = (_functionTypeKind == FunctionType::Kind::StringConcat) ? "string_concat" : "bytes_concat"; size_t totalParams = 0; std::vector<Type const*> targetTypes; for (Type const* argumentType: _argumentTypes) { if (_functionTypeKind == FunctionType::Kind::StringConcat) solAssert(argumentType->isImplicitlyConvertibleTo(*TypeProvider::stringMemory())); else if (_functionTypeKind == FunctionType::Kind::BytesConcat) solAssert( argumentType->isImplicitlyConvertibleTo(*TypeProvider::bytesMemory()) || argumentType->isImplicitlyConvertibleTo(*TypeProvider::fixedBytes(32)) ); if (argumentType->category() == Type::Category::FixedBytes) targetTypes.emplace_back(argumentType); else if ( auto const* literalType = dynamic_cast<StringLiteralType const*>(argumentType); literalType && !literalType->value().empty() && literalType->value().size() <= 32 ) targetTypes.emplace_back(TypeProvider::fixedBytes(static_cast<unsigned>(literalType->value().size()))); else { solAssert(!dynamic_cast<RationalNumberType const*>(argumentType)); targetTypes.emplace_back( _functionTypeKind == FunctionType::Kind::StringConcat ? TypeProvider::stringMemory() : TypeProvider::bytesMemory() ); } totalParams += argumentType->sizeOnStack(); functionName += "_" + argumentType->identifier(); } return m_functionCollector.createFunction(functionName, [&]() { Whiskers templ(R"( function <functionName>(<parameters>) -> outPtr { outPtr := <allocateUnbounded>() let dataStart := add(outPtr, 0x20) let dataEnd := <encodePacked>(dataStart<?+parameters>, <parameters></+parameters>) mstore(outPtr, sub(dataEnd, dataStart)) <finalizeAllocation>(outPtr, sub(dataEnd, outPtr)) } )"); templ("functionName", functionName); templ("parameters", suffixedVariableNameList("param_", 0, totalParams)); templ("allocateUnbounded", allocateUnboundedFunction()); templ("finalizeAllocation", finalizeAllocationFunction()); templ( "encodePacked", ABIFunctions{m_evmVersion, m_revertStrings, m_functionCollector}.tupleEncoderPacked( _argumentTypes, targetTypes ) ); return templ.render(); }); } std::string YulUtilFunctions::mappingIndexAccessFunction(MappingType const& _mappingType, Type const& _keyType) { std::string functionName = "mapping_index_access_" + _mappingType.identifier() + "_of_" + _keyType.identifier(); return m_functionCollector.createFunction(functionName, [&]() { if (_mappingType.keyType()->isDynamicallySized()) return Whiskers(R"( function <functionName>(slot <?+key>,</+key> <key>) -> dataSlot { dataSlot := <hash>(<key> <?+key>,</+key> slot) } )") ("functionName", functionName) ("key", suffixedVariableNameList("key_", 0, _keyType.sizeOnStack())) ("hash", packedHashFunction( {&_keyType, TypeProvider::uint256()}, {_mappingType.keyType(), TypeProvider::uint256()} )) .render(); else { solAssert(CompilerUtils::freeMemoryPointer >= 0x40, ""); solAssert(!_mappingType.keyType()->isDynamicallyEncoded(), ""); solAssert(_mappingType.keyType()->calldataEncodedSize(false) <= 0x20, ""); Whiskers templ(R"( function <functionName>(slot <key>) -> dataSlot { mstore(0, <convertedKey>) mstore(0x20, slot) dataSlot := keccak256(0, 0x40) } )"); templ("functionName", functionName); templ("key", _keyType.sizeOnStack() == 1 ? ", key" : ""); if (_keyType.sizeOnStack() == 0) templ("convertedKey", conversionFunction(_keyType, *_mappingType.keyType()) + "()"); else templ("convertedKey", conversionFunction(_keyType, *_mappingType.keyType()) + "(key)"); return templ.render(); } }); } std::string YulUtilFunctions::readFromStorage( Type const& _type, size_t _offset, bool _splitFunctionTypes, VariableDeclaration::Location _location ) { if (_type.isValueType()) return readFromStorageValueType(_type, _offset, _splitFunctionTypes, _location); else { solAssert(_location != VariableDeclaration::Location::Transient); solAssert(_offset == 0, ""); return readFromStorageReferenceType(_type); } } std::string YulUtilFunctions::readFromStorageDynamic( Type const& _type, bool _splitFunctionTypes, VariableDeclaration::Location _location ) { if (_type.isValueType()) return readFromStorageValueType(_type, {}, _splitFunctionTypes, _location); solAssert(_location != VariableDeclaration::Location::Transient); std::string functionName = "read_from_storage__dynamic_" + std::string(_splitFunctionTypes ? "split_" : "") + _type.identifier(); return m_functionCollector.createFunction(functionName, [&] { return Whiskers(R"( function <functionName>(slot, offset) -> value { if gt(offset, 0) { <panic>() } value := <readFromStorage>(slot) } )") ("functionName", functionName) ("panic", panicFunction(util::PanicCode::Generic)) ("readFromStorage", readFromStorageReferenceType(_type)) .render(); }); } std::string YulUtilFunctions::readFromStorageValueType( Type const& _type, std::optional<size_t> _offset, bool _splitFunctionTypes, VariableDeclaration::Location _location ) { solAssert(_type.isValueType(), ""); solAssert( _location == VariableDeclaration::Location::Transient || _location == VariableDeclaration::Location::Unspecified, "Variable location can only be transient or plain storage" ); std::string functionName = "read_from_" + (_location == VariableDeclaration::Location::Transient ? "transient_"s : "") + "storage_" + std::string(_splitFunctionTypes ? "split_" : "") + ( _offset.has_value() ? "offset_" + std::to_string(*_offset) : "dynamic" ) + "_" + _type.identifier(); return m_functionCollector.createFunction(functionName, [&] { Whiskers templ(R"( function <functionName>(slot<?dynamic>, offset</dynamic>) -> <?split>addr, selector<!split>value</split> { <?split>let</split> value := <extract>(<loadOpcode>(slot)<?dynamic>, offset</dynamic>) <?split> addr, selector := <splitFunction>(value) </split> } )"); templ("functionName", functionName); templ("dynamic", !_offset.has_value()); templ("loadOpcode", _location == VariableDeclaration::Location::Transient ? "tload" : "sload"); if (_offset.has_value()) templ("extract", extractFromStorageValue(_type, *_offset)); else templ("extract", extractFromStorageValueDynamic(_type)); auto const* funType = dynamic_cast<FunctionType const*>(&_type); bool split = _splitFunctionTypes && funType && funType->kind() == FunctionType::Kind::External; templ("split", split); if (split) templ("splitFunction", splitExternalFunctionIdFunction()); return templ.render(); }); } std::string YulUtilFunctions::readFromStorageReferenceType(Type const& _type) { if (auto const* arrayType = dynamic_cast<ArrayType const*>(&_type)) { solAssert(arrayType->dataStoredIn(DataLocation::Memory), ""); return copyArrayFromStorageToMemoryFunction( dynamic_cast<ArrayType const&>(*arrayType->copyForLocation(DataLocation::Storage, false)), *arrayType ); } solAssert(_type.category() == Type::Category::Struct, ""); std::string functionName = "read_from_storage_reference_type_" + _type.identifier(); auto const& structType = dynamic_cast<StructType const&>(_type); solAssert(structType.location() == DataLocation::Memory, ""); MemberList::MemberMap structMembers = structType.nativeMembers(nullptr); std::vector<std::map<std::string, std::string>> memberSetValues(structMembers.size()); for (size_t i = 0; i < structMembers.size(); ++i) { auto const& [memberSlotDiff, memberStorageOffset] = structType.storageOffsetsOfMember(structMembers[i].name); solAssert(structMembers[i].type->isValueType() || memberStorageOffset == 0, ""); memberSetValues[i]["setMember"] = Whiskers(R"( { let <memberValues> := <readFromStorage>(add(slot, <memberSlotDiff>)) <writeToMemory>(add(value, <memberMemoryOffset>), <memberValues>) } )") ("memberValues", suffixedVariableNameList("memberValue_", 0, structMembers[i].type->stackItems().size())) ("memberMemoryOffset", structType.memoryOffsetOfMember(structMembers[i].name).str()) ("memberSlotDiff", memberSlotDiff.str()) ("readFromStorage", readFromStorage(*structMembers[i].type, memberStorageOffset, true, VariableDeclaration::Location::Unspecified)) ("writeToMemory", writeToMemoryFunction(*structMembers[i].type)) .render(); } return m_functionCollector.createFunction(functionName, [&] { return Whiskers(R"( function <functionName>(slot) -> value { value := <allocStruct>() <#member> <setMember> </member> } )") ("functionName", functionName) ("allocStruct", allocateMemoryStructFunction(structType)) ("member", memberSetValues) .render(); }); } std::string YulUtilFunctions::readFromMemory(Type const& _type) { return readFromMemoryOrCalldata(_type, false); } std::string YulUtilFunctions::readFromCalldata(Type const& _type) { return readFromMemoryOrCalldata(_type, true); } std::string YulUtilFunctions::updateStorageValueFunction( Type const& _fromType, Type const& _toType, VariableDeclaration::Location _location, std::optional<unsigned> const& _offset ) { solAssert( _location == VariableDeclaration::Location::Transient || _location == VariableDeclaration::Location::Unspecified, "Variable location can only be transient or plain storage" ); std::string const functionName = "update_" + (_location == VariableDeclaration::Location::Transient ? "transient_"s : "") + "storage_value_" + (_offset.has_value() ? ("offset_" + std::to_string(*_offset)) + "_" : "") + _fromType.identifier() + "_to_" + _toType.identifier(); return m_functionCollector.createFunction(functionName, [&] { if (_toType.isValueType()) { solAssert(_fromType.isImplicitlyConvertibleTo(_toType), ""); solAssert(_toType.storageBytes() <= 32, "Invalid storage bytes size."); solAssert(_toType.storageBytes() > 0, "Invalid storage bytes size."); return Whiskers(R"( function <functionName>(slot, <offset><fromValues>) { let <toValues> := <convert>(<fromValues>) <storeOpcode>(slot, <update>(<loadOpcode>(slot), <offset><prepare>(<toValues>))) } )") ("functionName", functionName) ("update", _offset.has_value() ? updateByteSliceFunction(_toType.storageBytes(), *_offset) : updateByteSliceFunctionDynamic(_toType.storageBytes()) ) ("offset", _offset.has_value() ? "" : "offset, ") ("convert", conversionFunction(_fromType, _toType)) ("fromValues", suffixedVariableNameList("value_", 0, _fromType.sizeOnStack())) ("toValues", suffixedVariableNameList("convertedValue_", 0, _toType.sizeOnStack())) ("storeOpcode", _location == VariableDeclaration::Location::Transient ? "tstore" : "sstore") ("loadOpcode", _location == VariableDeclaration::Location::Transient ? "tload" : "sload") ("prepare", prepareStoreFunction(_toType)) .render(); } solAssert(_location != VariableDeclaration::Location::Transient); auto const* toReferenceType = dynamic_cast<ReferenceType const*>(&_toType); auto const* fromReferenceType = dynamic_cast<ReferenceType const*>(&_fromType); solAssert(toReferenceType, ""); if (!fromReferenceType) { solAssert(_fromType.category() == Type::Category::StringLiteral, ""); solAssert(toReferenceType->category() == Type::Category::Array, ""); auto const& toArrayType = dynamic_cast<ArrayType const&>(*toReferenceType); solAssert(toArrayType.isByteArrayOrString(), ""); return Whiskers(R"( function <functionName>(slot<?dynamicOffset>, offset</dynamicOffset>) { <?dynamicOffset>if offset { <panic>() }</dynamicOffset> <copyToStorage>(slot) } )") ("functionName", functionName) ("dynamicOffset", !_offset.has_value()) ("panic", panicFunction(PanicCode::Generic)) ("copyToStorage", copyLiteralToStorageFunction(dynamic_cast<StringLiteralType const&>(_fromType).value())) .render(); } solAssert((*toReferenceType->copyForLocation( fromReferenceType->location(), fromReferenceType->isPointer() ).get()).equals(*fromReferenceType), ""); if (fromReferenceType->category() == Type::Category::ArraySlice) solAssert(toReferenceType->category() == Type::Category::Array, ""); else solAssert(toReferenceType->category() == fromReferenceType->category(), ""); solAssert(_offset.value_or(0) == 0, ""); Whiskers templ(R"( function <functionName>(slot, <?dynamicOffset>offset, </dynamicOffset><value>) { <?dynamicOffset>if offset { <panic>() }</dynamicOffset> <copyToStorage>(slot, <value>) } )"); templ("functionName", functionName); templ("dynamicOffset", !_offset.has_value()); templ("panic", panicFunction(PanicCode::Generic)); templ("value", suffixedVariableNameList("value_", 0, _fromType.sizeOnStack())); if (_fromType.category() == Type::Category::Array) templ("copyToStorage", copyArrayToStorageFunction( dynamic_cast<ArrayType const&>(_fromType), dynamic_cast<ArrayType const&>(_toType) )); else if (_fromType.category() == Type::Category::ArraySlice) { solAssert( _fromType.dataStoredIn(DataLocation::CallData), "Currently only calldata array slices are supported!" ); templ("copyToStorage", copyArrayToStorageFunction( dynamic_cast<ArraySliceType const&>(_fromType).arrayType(), dynamic_cast<ArrayType const&>(_toType) )); } else templ("copyToStorage", copyStructToStorageFunction( dynamic_cast<StructType const&>(_fromType), dynamic_cast<StructType const&>(_toType) )); return templ.render(); }); } std::string YulUtilFunctions::writeToMemoryFunction(Type const& _type) { std::string const functionName = "write_to_memory_" + _type.identifier(); return m_functionCollector.createFunction(functionName, [&] { solAssert(!dynamic_cast<StringLiteralType const*>(&_type), ""); if (auto ref = dynamic_cast<ReferenceType const*>(&_type)) { solAssert( ref->location() == DataLocation::Memory, "Can only update types with location memory." ); return Whiskers(R"( function <functionName>(memPtr, value) { mstore(memPtr, value) } )") ("functionName", functionName) .render(); } else if ( _type.category() == Type::Category::Function && dynamic_cast<FunctionType const&>(_type).kind() == FunctionType::Kind::External ) { return Whiskers(R"( function <functionName>(memPtr, addr, selector) { mstore(memPtr, <combine>(addr, selector)) } )") ("functionName", functionName) ("combine", combineExternalFunctionIdFunction()) .render(); } else if (_type.isValueType()) { return Whiskers(R"( function <functionName>(memPtr, value) { mstore(memPtr, <cleanup>(value)) } )") ("functionName", functionName) ("cleanup", cleanupFunction(_type)) .render(); } else // Should never happen { solAssert( false, "Memory store of type " + _type.toString(true) + " not allowed." ); } }); } std::string YulUtilFunctions::extractFromStorageValueDynamic(Type const& _type) { std::string functionName = "extract_from_storage_value_dynamic" + _type.identifier(); return m_functionCollector.createFunction(functionName, [&] { return Whiskers(R"( function <functionName>(slot_value, offset) -> value { value := <cleanupStorage>(<shr>(mul(offset, 8), slot_value)) } )") ("functionName", functionName) ("shr", shiftRightFunctionDynamic()) ("cleanupStorage", cleanupFromStorageFunction(_type)) .render(); }); } std::string YulUtilFunctions::extractFromStorageValue(Type const& _type, size_t _offset) { std::string functionName = "extract_from_storage_value_offset_" + std::to_string(_offset) + "_" + _type.identifier(); return m_functionCollector.createFunction(functionName, [&] { return Whiskers(R"( function <functionName>(slot_value) -> value { value := <cleanupStorage>(<shr>(slot_value)) } )") ("functionName", functionName) ("shr", shiftRightFunction(_offset * 8)) ("cleanupStorage", cleanupFromStorageFunction(_type)) .render(); }); } std::string YulUtilFunctions::cleanupFromStorageFunction(Type const& _type) { solAssert(_type.isValueType(), ""); std::string functionName = std::string("cleanup_from_storage_") + _type.identifier(); return m_functionCollector.createFunction(functionName, [&] { Whiskers templ(R"( function <functionName>(value) -> cleaned { cleaned := <cleaned> } )"); templ("functionName", functionName); Type const* encodingType = &_type; if (_type.category() == Type::Category::UserDefinedValueType) encodingType = _type.encodingType(); unsigned storageBytes = encodingType->storageBytes(); if (IntegerType const* intType = dynamic_cast<IntegerType const*>(encodingType)) if (intType->isSigned() && storageBytes != 32) { templ("cleaned", "signextend(" + std::to_string(storageBytes - 1) + ", value)"); return templ.render(); } if (storageBytes == 32) templ("cleaned", "value"); else if (encodingType->leftAligned()) templ("cleaned", shiftLeftFunction(256 - 8 * storageBytes) + "(value)"); else templ("cleaned", "and(value, " + toCompactHexWithPrefix((u256(1) << (8 * storageBytes)) - 1) + ")"); return templ.render(); }); } std::string YulUtilFunctions::prepareStoreFunction(Type const& _type) { std::string functionName = "prepare_store_" + _type.identifier(); return m_functionCollector.createFunction(functionName, [&]() { solAssert(_type.isValueType(), ""); auto const* funType = dynamic_cast<FunctionType const*>(&_type); if (funType && funType->kind() == FunctionType::Kind::External) { Whiskers templ(R"( function <functionName>(addr, selector) -> ret { ret := <prepareBytes>(<combine>(addr, selector)) } )"); templ("functionName", functionName); templ("prepareBytes", prepareStoreFunction(*TypeProvider::fixedBytes(24))); templ("combine", combineExternalFunctionIdFunction()); return templ.render(); } else { solAssert(_type.sizeOnStack() == 1, ""); Whiskers templ(R"( function <functionName>(value) -> ret { ret := <actualPrepare> } )"); templ("functionName", functionName); if (_type.leftAligned()) templ("actualPrepare", shiftRightFunction(256 - 8 * _type.storageBytes()) + "(value)"); else templ("actualPrepare", "value"); return templ.render(); } }); } std::string YulUtilFunctions::allocationFunction() { std::string functionName = "allocate_memory"; return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(size) -> memPtr { memPtr := <allocateUnbounded>() <finalizeAllocation>(memPtr, size) } )") ("functionName", functionName) ("allocateUnbounded", allocateUnboundedFunction()) ("finalizeAllocation", finalizeAllocationFunction()) .render(); }); } std::string YulUtilFunctions::allocateUnboundedFunction() { std::string functionName = "allocate_unbounded"; return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>() -> memPtr { memPtr := mload(<freeMemoryPointer>) } )") ("freeMemoryPointer", std::to_string(CompilerUtils::freeMemoryPointer)) ("functionName", functionName) .render(); }); } std::string YulUtilFunctions::finalizeAllocationFunction() { std::string functionName = "finalize_allocation"; return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(memPtr, size) { let newFreePtr := add(memPtr, <roundUp>(size)) // protect against overflow if or(gt(newFreePtr, 0xffffffffffffffff), lt(newFreePtr, memPtr)) { <panic>() } mstore(<freeMemoryPointer>, newFreePtr) } )") ("functionName", functionName) ("freeMemoryPointer", std::to_string(CompilerUtils::freeMemoryPointer)) ("roundUp", roundUpFunction()) ("panic", panicFunction(PanicCode::ResourceError)) .render(); }); } std::string YulUtilFunctions::zeroMemoryArrayFunction(ArrayType const& _type) { if (_type.baseType()->hasSimpleZeroValueInMemory()) return zeroMemoryFunction(*_type.baseType()); return zeroComplexMemoryArrayFunction(_type); } std::string YulUtilFunctions::zeroMemoryFunction(Type const& _type) { solAssert(_type.hasSimpleZeroValueInMemory(), ""); std::string functionName = "zero_memory_chunk_" + _type.identifier(); return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(dataStart, dataSizeInBytes) { calldatacopy(dataStart, calldatasize(), dataSizeInBytes) } )") ("functionName", functionName) .render(); }); } std::string YulUtilFunctions::zeroComplexMemoryArrayFunction(ArrayType const& _type) { solAssert(!_type.baseType()->hasSimpleZeroValueInMemory(), ""); std::string functionName = "zero_complex_memory_array_" + _type.identifier(); return m_functionCollector.createFunction(functionName, [&]() { solAssert(_type.memoryStride() == 32, ""); return Whiskers(R"( function <functionName>(dataStart, dataSizeInBytes) { for {let i := 0} lt(i, dataSizeInBytes) { i := add(i, <stride>) } { mstore(add(dataStart, i), <zeroValue>()) } } )") ("functionName", functionName) ("stride", std::to_string(_type.memoryStride())) ("zeroValue", zeroValueFunction(*_type.baseType(), false)) .render(); }); } std::string YulUtilFunctions::allocateMemoryArrayFunction(ArrayType const& _type) { std::string functionName = "allocate_memory_array_" + _type.identifier(); return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(length) -> memPtr { let allocSize := <allocSize>(length) memPtr := <alloc>(allocSize) <?dynamic> mstore(memPtr, length) </dynamic> } )") ("functionName", functionName) ("alloc", allocationFunction()) ("allocSize", arrayAllocationSizeFunction(_type)) ("dynamic", _type.isDynamicallySized()) .render(); }); } std::string YulUtilFunctions::allocateAndInitializeMemoryArrayFunction(ArrayType const& _type) { std::string functionName = "allocate_and_zero_memory_array_" + _type.identifier(); return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(length) -> memPtr { memPtr := <allocArray>(length) let dataStart := memPtr let dataSize := <allocSize>(length) <?dynamic> dataStart := add(dataStart, 32) dataSize := sub(dataSize, 32) </dynamic> <zeroArrayFunction>(dataStart, dataSize) } )") ("functionName", functionName) ("allocArray", allocateMemoryArrayFunction(_type)) ("allocSize", arrayAllocationSizeFunction(_type)) ("zeroArrayFunction", zeroMemoryArrayFunction(_type)) ("dynamic", _type.isDynamicallySized()) .render(); }); } std::string YulUtilFunctions::allocateMemoryStructFunction(StructType const& _type) { std::string functionName = "allocate_memory_struct_" + _type.identifier(); return m_functionCollector.createFunction(functionName, [&]() { Whiskers templ(R"( function <functionName>() -> memPtr { memPtr := <alloc>(<allocSize>) } )"); templ("functionName", functionName); templ("alloc", allocationFunction()); templ("allocSize", _type.memoryDataSize().str()); return templ.render(); }); } std::string YulUtilFunctions::allocateAndInitializeMemoryStructFunction(StructType const& _type) { std::string functionName = "allocate_and_zero_memory_struct_" + _type.identifier(); return m_functionCollector.createFunction(functionName, [&]() { Whiskers templ(R"( function <functionName>() -> memPtr { memPtr := <allocStruct>() let offset := memPtr <#member> mstore(offset, <zeroValue>()) offset := add(offset, 32) </member> } )"); templ("functionName", functionName); templ("allocStruct", allocateMemoryStructFunction(_type)); TypePointers const& members = _type.memoryMemberTypes(); std::vector<std::map<std::string, std::string>> memberParams(members.size()); for (size_t i = 0; i < members.size(); ++i) { solAssert(members[i]->memoryHeadSize() == 32, ""); memberParams[i]["zeroValue"] = zeroValueFunction( *TypeProvider::withLocationIfReference(DataLocation::Memory, members[i]), false ); } templ("member", memberParams); return templ.render(); }); } std::string YulUtilFunctions::conversionFunction(Type const& _from, Type const& _to) { if (_from.category() == Type::Category::UserDefinedValueType) { solAssert(_from == _to || _to == dynamic_cast<UserDefinedValueType const&>(_from).underlyingType(), ""); return conversionFunction(dynamic_cast<UserDefinedValueType const&>(_from).underlyingType(), _to); } if (_to.category() == Type::Category::UserDefinedValueType) { solAssert(_from == _to || _from.isImplicitlyConvertibleTo(dynamic_cast<UserDefinedValueType const&>(_to).underlyingType()), ""); return conversionFunction(_from, dynamic_cast<UserDefinedValueType const&>(_to).underlyingType()); } if (_from.category() == Type::Category::Function) { solAssert(_to.category() == Type::Category::Function, ""); FunctionType const& fromType = dynamic_cast<FunctionType const&>(_from); FunctionType const& targetType = dynamic_cast<FunctionType const&>(_to); solAssert( fromType.isImplicitlyConvertibleTo(targetType) && fromType.sizeOnStack() == targetType.sizeOnStack() && (fromType.kind() == FunctionType::Kind::Internal || fromType.kind() == FunctionType::Kind::External) && fromType.kind() == targetType.kind(), "Invalid function type conversion requested." ); std::string const functionName = "convert_" + _from.identifier() + "_to_" + _to.identifier(); return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(<?external>addr, </external>functionId) -> <?external>outAddr, </external>outFunctionId { <?external>outAddr := addr</external> outFunctionId := functionId } )") ("functionName", functionName) ("external", fromType.kind() == FunctionType::Kind::External) .render(); }); } else if (_from.category() == Type::Category::ArraySlice) { auto const& fromType = dynamic_cast<ArraySliceType const&>(_from); if (_to.category() == Type::Category::FixedBytes) { solAssert(fromType.arrayType().isByteArray(), "Array types other than bytes not convertible to bytesNN."); return bytesToFixedBytesConversionFunction(fromType.arrayType(), dynamic_cast<FixedBytesType const &>(_to)); } solAssert(_to.category() == Type::Category::Array); auto const& targetType = dynamic_cast<ArrayType const&>(_to); solAssert( fromType.arrayType().isImplicitlyConvertibleTo(targetType) || (fromType.arrayType().isByteArrayOrString() && targetType.isByteArrayOrString()) ); solAssert( fromType.arrayType().dataStoredIn(DataLocation::CallData) && fromType.arrayType().isDynamicallySized() && !fromType.arrayType().baseType()->isDynamicallyEncoded() ); if (!targetType.dataStoredIn(DataLocation::CallData)) return arrayConversionFunction(fromType.arrayType(), targetType); std::string const functionName = "convert_" + _from.identifier() + "_to_" + _to.identifier(); return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(offset, length) -> outOffset, outLength { outOffset := offset outLength := length } )") ("functionName", functionName) .render(); }); } else if (_from.category() == Type::Category::Array) { auto const& fromArrayType = dynamic_cast<ArrayType const&>(_from); if (_to.category() == Type::Category::FixedBytes) { solAssert(fromArrayType.isByteArray(), "Array types other than bytes not convertible to bytesNN."); return bytesToFixedBytesConversionFunction(fromArrayType, dynamic_cast<FixedBytesType const &>(_to)); } solAssert(_to.category() == Type::Category::Array, ""); return arrayConversionFunction(fromArrayType, dynamic_cast<ArrayType const&>(_to)); } if (_from.sizeOnStack() != 1 || _to.sizeOnStack() != 1) return conversionFunctionSpecial(_from, _to); std::string functionName = "convert_" + _from.identifier() + "_to_" + _to.identifier(); return m_functionCollector.createFunction(functionName, [&]() { Whiskers templ(R"( function <functionName>(value) -> converted { <body> } )"); templ("functionName", functionName); std::string body; auto toCategory = _to.category(); auto fromCategory = _from.category(); switch (fromCategory) { case Type::Category::Address: case Type::Category::Contract: body = Whiskers("converted := <convert>(value)") ("convert", conversionFunction(IntegerType(160), _to)) .render(); break; case Type::Category::Integer: case Type::Category::RationalNumber: { solAssert(_from.mobileType(), ""); if (RationalNumberType const* rational = dynamic_cast<RationalNumberType const*>(&_from)) if (rational->isFractional()) solAssert(toCategory == Type::Category::FixedPoint, ""); if (toCategory == Type::Category::Address || toCategory == Type::Category::Contract) body = Whiskers("converted := <convert>(value)") ("convert", conversionFunction(_from, IntegerType(160))) .render(); else { Whiskers bodyTemplate("converted := <cleanOutput>(<convert>(<cleanInput>(value)))"); bodyTemplate("cleanInput", cleanupFunction(_from)); bodyTemplate("cleanOutput", cleanupFunction(_to)); std::string convert; solAssert(_to.category() != Type::Category::UserDefinedValueType, ""); if (auto const* toFixedBytes = dynamic_cast<FixedBytesType const*>(&_to)) convert = shiftLeftFunction(256 - toFixedBytes->numBytes() * 8); else if (dynamic_cast<FixedPointType const*>(&_to)) solUnimplemented(""); else if (dynamic_cast<IntegerType const*>(&_to)) { solUnimplementedAssert(fromCategory != Type::Category::FixedPoint); convert = identityFunction(); } else if (toCategory == Type::Category::Enum) { solAssert(fromCategory != Type::Category::FixedPoint, ""); convert = identityFunction(); } else solAssert(false, ""); solAssert(!convert.empty(), ""); bodyTemplate("convert", convert); body = bodyTemplate.render(); } break; } case Type::Category::Bool: { solAssert(_from == _to, "Invalid conversion for bool."); body = Whiskers("converted := <clean>(value)") ("clean", cleanupFunction(_from)) .render(); break; } case Type::Category::FixedPoint: solUnimplemented("Fixed point types not implemented."); break; case Type::Category::Struct: { solAssert(toCategory == Type::Category::Struct, ""); auto const& fromStructType = dynamic_cast<StructType const &>(_from); auto const& toStructType = dynamic_cast<StructType const &>(_to); solAssert(fromStructType.structDefinition() == toStructType.structDefinition(), ""); if (fromStructType.location() == toStructType.location() && toStructType.isPointer()) body = "converted := value"; else { solUnimplementedAssert(toStructType.location() == DataLocation::Memory); solUnimplementedAssert(fromStructType.location() != DataLocation::Memory); if (fromStructType.location() == DataLocation::CallData) body = Whiskers(R"( converted := <abiDecode>(value, calldatasize()) )") ( "abiDecode", ABIFunctions(m_evmVersion, m_revertStrings, m_functionCollector).abiDecodingFunctionStruct( toStructType, false ) ).render(); else { solAssert(fromStructType.location() == DataLocation::Storage, ""); body = Whiskers(R"( converted := <readFromStorage>(value) )") ("readFromStorage", readFromStorage(toStructType, 0, true, VariableDeclaration::Location::Unspecified)) .render(); } } break; } case Type::Category::FixedBytes: { FixedBytesType const& from = dynamic_cast<FixedBytesType const&>(_from); if (toCategory == Type::Category::Integer) body = Whiskers("converted := <convert>(<shift>(value))") ("shift", shiftRightFunction(256 - from.numBytes() * 8)) ("convert", conversionFunction(IntegerType(from.numBytes() * 8), _to)) .render(); else if (toCategory == Type::Category::Address) body = Whiskers("converted := <convert>(value)") ("convert", conversionFunction(_from, IntegerType(160))) .render(); else { solAssert(toCategory == Type::Category::FixedBytes, "Invalid type conversion requested."); FixedBytesType const& to = dynamic_cast<FixedBytesType const&>(_to); body = Whiskers("converted := <clean>(value)") ("clean", cleanupFunction((to.numBytes() <= from.numBytes()) ? to : from)) .render(); } break; } case Type::Category::Function: { solAssert(false, "Conversion should not be called for function types."); break; } case Type::Category::Enum: { solAssert(toCategory == Type::Category::Integer || _from == _to, ""); EnumType const& enumType = dynamic_cast<decltype(enumType)>(_from); body = Whiskers("converted := <clean>(value)") ("clean", cleanupFunction(enumType)) .render(); break; } case Type::Category::Tuple: { solUnimplemented("Tuple conversion not implemented."); break; } case Type::Category::TypeType: { TypeType const& typeType = dynamic_cast<decltype(typeType)>(_from); if ( auto const* contractType = dynamic_cast<ContractType const*>(typeType.actualType()); contractType->contractDefinition().isLibrary() && _to == *TypeProvider::address() ) body = "converted := value"; else solAssert(false, "Invalid conversion from " + _from.canonicalName() + " to " + _to.canonicalName()); break; } case Type::Category::Mapping: { solAssert(_from == _to, ""); body = "converted := value"; break; } default: solAssert(false, "Invalid conversion from " + _from.canonicalName() + " to " + _to.canonicalName()); } solAssert(!body.empty(), _from.canonicalName() + " to " + _to.canonicalName()); templ("body", body); return templ.render(); }); } std::string YulUtilFunctions::bytesToFixedBytesConversionFunction(ArrayType const& _from, FixedBytesType const& _to) { solAssert(_from.isByteArray(), ""); solAssert(_from.isDynamicallySized(), ""); std::string functionName = "convert_bytes_to_fixedbytes_from_" + _from.identifier() + "_to_" + _to.identifier(); return m_functionCollector.createFunction(functionName, [&](auto& _args, auto& _returnParams) { _args = { "array" }; bool fromCalldata = _from.dataStoredIn(DataLocation::CallData); if (fromCalldata) _args.emplace_back("len"); _returnParams = {"value"}; Whiskers templ(R"( let length := <arrayLen>(array<?fromCalldata>, len</fromCalldata>) let dataArea := array <?fromMemory> dataArea := <dataArea>(array) </fromMemory> <?fromStorage> if gt(length, 31) { dataArea := <dataArea>(array) } </fromStorage> <?fromCalldata> value := <cleanup>(calldataload(dataArea)) <!fromCalldata> value := <extractValue>(dataArea) </fromCalldata> if lt(length, <fixedBytesLen>) { value := and( value, <shl>( mul(8, sub(<fixedBytesLen>, length)), <mask> ) ) } )"); templ("fromCalldata", fromCalldata); templ("arrayLen", arrayLengthFunction(_from)); templ("fixedBytesLen", std::to_string(_to.numBytes())); templ("fromMemory", _from.dataStoredIn(DataLocation::Memory)); templ("fromStorage", _from.dataStoredIn(DataLocation::Storage)); templ("dataArea", arrayDataAreaFunction(_from)); if (fromCalldata) templ("cleanup", cleanupFunction(_to)); else templ( "extractValue", _from.dataStoredIn(DataLocation::Storage) ? readFromStorage(_to, 32 - _to.numBytes(), false, VariableDeclaration::Location::Unspecified) : readFromMemory(_to) ); templ("shl", shiftLeftFunctionDynamic()); templ("mask", formatNumber(~((u256(1) << (256 - _to.numBytes() * 8)) - 1))); return templ.render(); }); } std::string YulUtilFunctions::copyStructToStorageFunction(StructType const& _from, StructType const& _to) { solAssert(_to.dataStoredIn(DataLocation::Storage), ""); solAssert(_from.structDefinition() == _to.structDefinition(), ""); std::string functionName = "copy_struct_to_storage_from_" + _from.identifier() + "_to_" + _to.identifier(); return m_functionCollector.createFunction(functionName, [&](auto& _arguments, auto&) { _arguments = {"slot", "value"}; Whiskers templ(R"( <?fromStorage> if iszero(eq(slot, value)) { </fromStorage> <#member> { <updateMemberCall> } </member> <?fromStorage> } </fromStorage> )"); templ("fromStorage", _from.dataStoredIn(DataLocation::Storage)); MemberList::MemberMap structMembers = _from.nativeMembers(nullptr); MemberList::MemberMap toStructMembers = _to.nativeMembers(nullptr); std::vector<std::map<std::string, std::string>> memberParams(structMembers.size()); for (size_t i = 0; i < structMembers.size(); ++i) { Type const& memberType = *structMembers[i].type; solAssert(memberType.memoryHeadSize() == 32, ""); auto const&[slotDiff, offset] = _to.storageOffsetsOfMember(structMembers[i].name); Whiskers t(R"( let memberSlot := add(slot, <memberStorageSlotDiff>) let memberSrcPtr := add(value, <memberOffset>) <?fromCalldata> let <memberValues> := <?dynamicallyEncodedMember> <accessCalldataTail>(value, memberSrcPtr) <!dynamicallyEncodedMember> memberSrcPtr </dynamicallyEncodedMember> <?isValueType> <memberValues> := <read>(<memberValues>) </isValueType> </fromCalldata> <?fromMemory> let <memberValues> := <read>(memberSrcPtr) </fromMemory> <?fromStorage> let <memberValues> := <?isValueType> <read>(memberSrcPtr) <!isValueType> memberSrcPtr </isValueType> </fromStorage> <updateStorageValue>(memberSlot, <memberValues>) )"); bool fromCalldata = _from.location() == DataLocation::CallData; t("fromCalldata", fromCalldata); bool fromMemory = _from.location() == DataLocation::Memory; t("fromMemory", fromMemory); bool fromStorage = _from.location() == DataLocation::Storage; t("fromStorage", fromStorage); t("isValueType", memberType.isValueType()); t("memberValues", suffixedVariableNameList("memberValue_", 0, memberType.stackItems().size())); t("memberStorageSlotDiff", slotDiff.str()); if (fromCalldata) { t("memberOffset", std::to_string(_from.calldataOffsetOfMember(structMembers[i].name))); t("dynamicallyEncodedMember", memberType.isDynamicallyEncoded()); if (memberType.isDynamicallyEncoded()) t("accessCalldataTail", accessCalldataTailFunction(memberType)); if (memberType.isValueType()) t("read", readFromCalldata(memberType)); } else if (fromMemory) { t("memberOffset", _from.memoryOffsetOfMember(structMembers[i].name).str()); t("read", readFromMemory(memberType)); } else if (fromStorage) { auto const& [srcSlotOffset, srcOffset] = _from.storageOffsetsOfMember(structMembers[i].name); t("memberOffset", formatNumber(srcSlotOffset)); if (memberType.isValueType()) t("read", readFromStorageValueType(memberType, srcOffset, true, VariableDeclaration::Location::Unspecified)); else solAssert(srcOffset == 0, ""); } t("updateStorageValue", updateStorageValueFunction( memberType, *toStructMembers[i].type, VariableDeclaration::Location::Unspecified, std::optional<unsigned>{offset} )); memberParams[i]["updateMemberCall"] = t.render(); } templ("member", memberParams); return templ.render(); }); } std::string YulUtilFunctions::arrayConversionFunction(ArrayType const& _from, ArrayType const& _to) { if (_to.dataStoredIn(DataLocation::CallData)) solAssert( _from.dataStoredIn(DataLocation::CallData) && _from.isByteArrayOrString() && _to.isByteArrayOrString(), "" ); // Other cases are done explicitly in LValue::storeValue, and only possible by assignment. if (_to.location() == DataLocation::Storage) solAssert( (_to.isPointer() || (_from.isByteArrayOrString() && _to.isByteArrayOrString())) && _from.location() == DataLocation::Storage, "Invalid conversion to storage type." ); std::string functionName = "convert_array_" + _from.identifier() + "_to_" + _to.identifier(); return m_functionCollector.createFunction(functionName, [&]() { Whiskers templ(R"( function <functionName>(value<?fromCalldataDynamic>, length</fromCalldataDynamic>) -> converted <?toCalldataDynamic>, outLength</toCalldataDynamic> { <body> <?toCalldataDynamic> outLength := <length> </toCalldataDynamic> } )"); templ("functionName", functionName); templ("fromCalldataDynamic", _from.dataStoredIn(DataLocation::CallData) && _from.isDynamicallySized()); templ("toCalldataDynamic", _to.dataStoredIn(DataLocation::CallData) && _to.isDynamicallySized()); templ("length", _from.isDynamicallySized() ? "length" : _from.length().str()); if ( _from == _to || (_from.dataStoredIn(DataLocation::Memory) && _to.dataStoredIn(DataLocation::Memory)) || (_from.dataStoredIn(DataLocation::CallData) && _to.dataStoredIn(DataLocation::CallData)) || _to.dataStoredIn(DataLocation::Storage) ) templ("body", "converted := value"); else if (_to.dataStoredIn(DataLocation::Memory)) templ( "body", Whiskers(R"( // Copy the array to a free position in memory converted := <?fromStorage> <arrayStorageToMem>(value) </fromStorage> <?fromCalldata> <abiDecode>(value, <length>, calldatasize()) </fromCalldata> )") ("fromStorage", _from.dataStoredIn(DataLocation::Storage)) ("fromCalldata", _from.dataStoredIn(DataLocation::CallData)) ("length", _from.isDynamicallySized() ? "length" : _from.length().str()) ( "abiDecode", _from.dataStoredIn(DataLocation::CallData) ? ABIFunctions( m_evmVersion, m_revertStrings, m_functionCollector ).abiDecodingFunctionArrayAvailableLength(_to, false) : "" ) ( "arrayStorageToMem", _from.dataStoredIn(DataLocation::Storage) ? copyArrayFromStorageToMemoryFunction(_from, _to) : "" ) .render() ); else solAssert(false, ""); return templ.render(); }); } std::string YulUtilFunctions::cleanupFunction(Type const& _type) { if (auto userDefinedValueType = dynamic_cast<UserDefinedValueType const*>(&_type)) return cleanupFunction(userDefinedValueType->underlyingType()); std::string functionName = std::string("cleanup_") + _type.identifier(); return m_functionCollector.createFunction(functionName, [&]() { Whiskers templ(R"( function <functionName>(value) -> cleaned { <body> } )"); templ("functionName", functionName); switch (_type.category()) { case Type::Category::Address: templ("body", "cleaned := " + cleanupFunction(IntegerType(160)) + "(value)"); break; case Type::Category::Integer: { IntegerType const& type = dynamic_cast<IntegerType const&>(_type); if (type.numBits() == 256) templ("body", "cleaned := value"); else if (type.isSigned()) templ("body", "cleaned := signextend(" + std::to_string(type.numBits() / 8 - 1) + ", value)"); else templ("body", "cleaned := and(value, " + toCompactHexWithPrefix((u256(1) << type.numBits()) - 1) + ")"); break; } case Type::Category::RationalNumber: templ("body", "cleaned := value"); break; case Type::Category::Bool: templ("body", "cleaned := iszero(iszero(value))"); break; case Type::Category::FixedPoint: solUnimplemented("Fixed point types not implemented."); break; case Type::Category::Function: switch (dynamic_cast<FunctionType const&>(_type).kind()) { case FunctionType::Kind::External: templ("body", "cleaned := " + cleanupFunction(FixedBytesType(24)) + "(value)"); break; case FunctionType::Kind::Internal: templ("body", "cleaned := value"); break; default: solAssert(false, ""); break; } break; case Type::Category::Array: case Type::Category::Struct: case Type::Category::Mapping: solAssert(_type.dataStoredIn(DataLocation::Storage), "Cleanup requested for non-storage reference type."); templ("body", "cleaned := value"); break; case Type::Category::FixedBytes: { FixedBytesType const& type = dynamic_cast<FixedBytesType const&>(_type); if (type.numBytes() == 32) templ("body", "cleaned := value"); else if (type.numBytes() == 0) // This is disallowed in the type system. solAssert(false, ""); else { size_t numBits = type.numBytes() * 8; u256 mask = ((u256(1) << numBits) - 1) << (256 - numBits); templ("body", "cleaned := and(value, " + toCompactHexWithPrefix(mask) + ")"); } break; } case Type::Category::Contract: { AddressType addressType(dynamic_cast<ContractType const&>(_type).isPayable() ? StateMutability::Payable : StateMutability::NonPayable ); templ("body", "cleaned := " + cleanupFunction(addressType) + "(value)"); break; } case Type::Category::Enum: { // Out of range enums cannot be truncated unambiguously and therefore it should be an error. templ("body", "cleaned := value " + validatorFunction(_type, false) + "(value)"); break; } case Type::Category::InaccessibleDynamic: templ("body", "cleaned := 0"); break; default: solAssert(false, "Cleanup of type " + _type.identifier() + " requested."); } return templ.render(); }); } std::string YulUtilFunctions::validatorFunction(Type const& _type, bool _revertOnFailure) { std::string functionName = std::string("validator_") + (_revertOnFailure ? "revert_" : "assert_") + _type.identifier(); return m_functionCollector.createFunction(functionName, [&]() { Whiskers templ(R"( function <functionName>(value) { if iszero(<condition>) { <failure> } } )"); templ("functionName", functionName); PanicCode panicCode = PanicCode::Generic; switch (_type.category()) { case Type::Category::Address: case Type::Category::Integer: case Type::Category::RationalNumber: case Type::Category::Bool: case Type::Category::FixedPoint: case Type::Category::Function: case Type::Category::Array: case Type::Category::Struct: case Type::Category::Mapping: case Type::Category::FixedBytes: case Type::Category::Contract: case Type::Category::UserDefinedValueType: { templ("condition", "eq(value, " + cleanupFunction(_type) + "(value))"); break; } case Type::Category::Enum: { size_t members = dynamic_cast<EnumType const&>(_type).numberOfMembers(); solAssert(members > 0, "empty enum should have caused a parser error."); panicCode = PanicCode::EnumConversionError; templ("condition", "lt(value, " + std::to_string(members) + ")"); break; } case Type::Category::InaccessibleDynamic: templ("condition", "1"); break; default: solAssert(false, "Validation of type " + _type.identifier() + " requested."); } if (_revertOnFailure) templ("failure", "revert(0, 0)"); else templ("failure", panicFunction(panicCode) + "()"); return templ.render(); }); } std::string YulUtilFunctions::packedHashFunction( std::vector<Type const*> const& _givenTypes, std::vector<Type const*> const& _targetTypes ) { std::string functionName = std::string("packed_hashed_"); for (auto const& t: _givenTypes) functionName += t->identifier() + "_"; functionName += "_to_"; for (auto const& t: _targetTypes) functionName += t->identifier() + "_"; size_t sizeOnStack = 0; for (Type const* t: _givenTypes) sizeOnStack += t->sizeOnStack(); return m_functionCollector.createFunction(functionName, [&]() { Whiskers templ(R"( function <functionName>(<variables>) -> hash { let pos := <allocateUnbounded>() let end := <packedEncode>(pos <comma> <variables>) hash := keccak256(pos, sub(end, pos)) } )"); templ("functionName", functionName); templ("variables", suffixedVariableNameList("var_", 1, 1 + sizeOnStack)); templ("comma", sizeOnStack > 0 ? "," : ""); templ("allocateUnbounded", allocateUnboundedFunction()); templ("packedEncode", ABIFunctions(m_evmVersion, m_revertStrings, m_functionCollector).tupleEncoderPacked(_givenTypes, _targetTypes)); return templ.render(); }); } std::string YulUtilFunctions::forwardingRevertFunction() { bool forward = m_evmVersion.supportsReturndata(); std::string functionName = "revert_forward_" + std::to_string(forward); return m_functionCollector.createFunction(functionName, [&]() { if (forward) return Whiskers(R"( function <functionName>() { let pos := <allocateUnbounded>() returndatacopy(pos, 0, returndatasize()) revert(pos, returndatasize()) } )") ("functionName", functionName) ("allocateUnbounded", allocateUnboundedFunction()) .render(); else return Whiskers(R"( function <functionName>() { revert(0, 0) } )") ("functionName", functionName) .render(); }); } std::string YulUtilFunctions::decrementCheckedFunction(Type const& _type) { solAssert(_type.category() == Type::Category::Integer, ""); IntegerType const& type = dynamic_cast<IntegerType const&>(_type); std::string const functionName = "decrement_" + _type.identifier(); return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(value) -> ret { value := <cleanupFunction>(value) if eq(value, <minval>) { <panic>() } ret := sub(value, 1) } )") ("functionName", functionName) ("panic", panicFunction(PanicCode::UnderOverflow)) ("minval", toCompactHexWithPrefix(type.min())) ("cleanupFunction", cleanupFunction(_type)) .render(); }); } std::string YulUtilFunctions::decrementWrappingFunction(Type const& _type) { solAssert(_type.category() == Type::Category::Integer, ""); IntegerType const& type = dynamic_cast<IntegerType const&>(_type); std::string const functionName = "decrement_wrapping_" + _type.identifier(); return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(value) -> ret { ret := <cleanupFunction>(sub(value, 1)) } )") ("functionName", functionName) ("cleanupFunction", cleanupFunction(type)) .render(); }); } std::string YulUtilFunctions::incrementCheckedFunction(Type const& _type) { solAssert(_type.category() == Type::Category::Integer, ""); IntegerType const& type = dynamic_cast<IntegerType const&>(_type); std::string const functionName = "increment_" + _type.identifier(); return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(value) -> ret { value := <cleanupFunction>(value) if eq(value, <maxval>) { <panic>() } ret := add(value, 1) } )") ("functionName", functionName) ("maxval", toCompactHexWithPrefix(type.max())) ("panic", panicFunction(PanicCode::UnderOverflow)) ("cleanupFunction", cleanupFunction(_type)) .render(); }); } std::string YulUtilFunctions::incrementWrappingFunction(Type const& _type) { solAssert(_type.category() == Type::Category::Integer, ""); IntegerType const& type = dynamic_cast<IntegerType const&>(_type); std::string const functionName = "increment_wrapping_" + _type.identifier(); return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(value) -> ret { ret := <cleanupFunction>(add(value, 1)) } )") ("functionName", functionName) ("cleanupFunction", cleanupFunction(type)) .render(); }); } std::string YulUtilFunctions::negateNumberCheckedFunction(Type const& _type) { solAssert(_type.category() == Type::Category::Integer, ""); IntegerType const& type = dynamic_cast<IntegerType const&>(_type); solAssert(type.isSigned(), "Expected signed type!"); std::string const functionName = "negate_" + _type.identifier(); return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(value) -> ret { value := <cleanupFunction>(value) if eq(value, <minval>) { <panic>() } ret := sub(0, value) } )") ("functionName", functionName) ("minval", toCompactHexWithPrefix(type.min())) ("cleanupFunction", cleanupFunction(_type)) ("panic", panicFunction(PanicCode::UnderOverflow)) .render(); }); } std::string YulUtilFunctions::negateNumberWrappingFunction(Type const& _type) { solAssert(_type.category() == Type::Category::Integer, ""); IntegerType const& type = dynamic_cast<IntegerType const&>(_type); solAssert(type.isSigned(), "Expected signed type!"); std::string const functionName = "negate_wrapping_" + _type.identifier(); return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>(value) -> ret { ret := <cleanupFunction>(sub(0, value)) } )") ("functionName", functionName) ("cleanupFunction", cleanupFunction(type)) .render(); }); } std::string YulUtilFunctions::zeroValueFunction(Type const& _type, bool _splitFunctionTypes) { solAssert(_type.category() != Type::Category::Mapping, ""); std::string const functionName = "zero_value_for_" + std::string(_splitFunctionTypes ? "split_" : "") + _type.identifier(); return m_functionCollector.createFunction(functionName, [&]() { FunctionType const* fType = dynamic_cast<FunctionType const*>(&_type); if (fType && fType->kind() == FunctionType::Kind::External && _splitFunctionTypes) return Whiskers(R"( function <functionName>() -> retAddress, retFunction { retAddress := 0 retFunction := 0 } )") ("functionName", functionName) .render(); if (_type.dataStoredIn(DataLocation::CallData)) { solAssert( _type.category() == Type::Category::Struct || _type.category() == Type::Category::Array, ""); Whiskers templ(R"( function <functionName>() -> offset<?hasLength>, length</hasLength> { offset := calldatasize() <?hasLength> length := 0 </hasLength> } )"); templ("functionName", functionName); templ("hasLength", _type.category() == Type::Category::Array && dynamic_cast<ArrayType const&>(_type).isDynamicallySized() ); return templ.render(); } Whiskers templ(R"( function <functionName>() -> ret { ret := <zeroValue> } )"); templ("functionName", functionName); if (_type.isValueType()) { solAssert(( _type.hasSimpleZeroValueInMemory() || (fType && (fType->kind() == FunctionType::Kind::Internal || fType->kind() == FunctionType::Kind::External)) ), ""); templ("zeroValue", "0"); } else { solAssert(_type.dataStoredIn(DataLocation::Memory), ""); if (auto const* arrayType = dynamic_cast<ArrayType const*>(&_type)) { if (_type.isDynamicallySized()) templ("zeroValue", std::to_string(CompilerUtils::zeroPointer)); else templ("zeroValue", allocateAndInitializeMemoryArrayFunction(*arrayType) + "(" + std::to_string(unsigned(arrayType->length())) + ")"); } else if (auto const* structType = dynamic_cast<StructType const*>(&_type)) templ("zeroValue", allocateAndInitializeMemoryStructFunction(*structType) + "()"); else solUnimplemented(""); } return templ.render(); }); } std::string YulUtilFunctions::storageSetToZeroFunction(Type const& _type, VariableDeclaration::Location _location) { std::string const functionName = "storage_set_to_zero_" + _type.identifier(); return m_functionCollector.createFunction(functionName, [&]() { if (_type.isValueType()) return Whiskers(R"( function <functionName>(slot, offset) { let <values> := <zeroValue>() <store>(slot, offset, <values>) } )") ("functionName", functionName) ("store", updateStorageValueFunction(_type, _type, _location)) ("values", suffixedVariableNameList("zero_", 0, _type.sizeOnStack())) ("zeroValue", zeroValueFunction(_type)) .render(); else if (_type.category() == Type::Category::Array) return Whiskers(R"( function <functionName>(slot, offset) { if iszero(eq(offset, 0)) { <panic>() } <clearArray>(slot) } )") ("functionName", functionName) ("clearArray", clearStorageArrayFunction(dynamic_cast<ArrayType const&>(_type))) ("panic", panicFunction(PanicCode::Generic)) .render(); else if (_type.category() == Type::Category::Struct) return Whiskers(R"( function <functionName>(slot, offset) { if iszero(eq(offset, 0)) { <panic>() } <clearStruct>(slot) } )") ("functionName", functionName) ("clearStruct", clearStorageStructFunction(dynamic_cast<StructType const&>(_type))) ("panic", panicFunction(PanicCode::Generic)) .render(); else solUnimplemented("setToZero for type " + _type.identifier() + " not yet implemented!"); }); } std::string YulUtilFunctions::conversionFunctionSpecial(Type const& _from, Type const& _to) { std::string functionName = "convert_" + _from.identifier() + "_to_" + _to.identifier(); return m_functionCollector.createFunction(functionName, [&]() { if ( auto fromTuple = dynamic_cast<TupleType const*>(&_from), toTuple = dynamic_cast<TupleType const*>(&_to); fromTuple && toTuple && fromTuple->components().size() == toTuple->components().size() ) { size_t sourceStackSize = 0; size_t destStackSize = 0; std::string conversions; for (size_t i = 0; i < fromTuple->components().size(); ++i) { auto fromComponent = fromTuple->components()[i]; auto toComponent = toTuple->components()[i]; solAssert(fromComponent, ""); if (toComponent) { conversions += suffixedVariableNameList("converted", destStackSize, destStackSize + toComponent->sizeOnStack()) + (toComponent->sizeOnStack() > 0 ? " := " : "") + conversionFunction(*fromComponent, *toComponent) + "(" + suffixedVariableNameList("value", sourceStackSize, sourceStackSize + fromComponent->sizeOnStack()) + ")\n"; destStackSize += toComponent->sizeOnStack(); } sourceStackSize += fromComponent->sizeOnStack(); } return Whiskers(R"( function <functionName>(<values>) <arrow> <converted> { <conversions> } )") ("functionName", functionName) ("values", suffixedVariableNameList("value", 0, sourceStackSize)) ("arrow", destStackSize > 0 ? "->" : "") ("converted", suffixedVariableNameList("converted", 0, destStackSize)) ("conversions", conversions) .render(); } solUnimplementedAssert( _from.category() == Type::Category::StringLiteral, "Type conversion " + _from.toString() + " -> " + _to.toString() + " not yet implemented." ); std::string const& data = dynamic_cast<StringLiteralType const&>(_from).value(); if (_to.category() == Type::Category::FixedBytes) { unsigned const numBytes = dynamic_cast<FixedBytesType const&>(_to).numBytes(); solAssert(data.size() <= 32, ""); Whiskers templ(R"( function <functionName>() -> converted { converted := <data> } )"); templ("functionName", functionName); templ("data", formatNumber( h256::Arith(h256(data, h256::AlignLeft)) & (~(u256(-1) >> (8 * numBytes))) )); return templ.render(); } else if (_to.category() == Type::Category::Array) { solAssert(dynamic_cast<ArrayType const&>(_to).isByteArrayOrString(), ""); Whiskers templ(R"( function <functionName>() -> converted { converted := <copyLiteralToMemory>() } )"); templ("functionName", functionName); templ("copyLiteralToMemory", copyLiteralToMemoryFunction(data)); return templ.render(); } else solAssert( false, "Invalid conversion from std::string literal to " + _to.toString() + " requested." ); }); } std::string YulUtilFunctions::readFromMemoryOrCalldata(Type const& _type, bool _fromCalldata) { std::string functionName = std::string("read_from_") + (_fromCalldata ? "calldata" : "memory") + _type.identifier(); // TODO use ABI functions for handling calldata if (_fromCalldata) solAssert(!_type.isDynamicallyEncoded(), ""); return m_functionCollector.createFunction(functionName, [&] { if (auto refType = dynamic_cast<ReferenceType const*>(&_type)) { solAssert(refType->sizeOnStack() == 1, ""); solAssert(!_fromCalldata, ""); return Whiskers(R"( function <functionName>(memPtr) -> value { value := mload(memPtr) } )") ("functionName", functionName) .render(); } solAssert(_type.isValueType(), ""); Whiskers templ(R"( function <functionName>(ptr) -> <returnVariables> { <?fromCalldata> let value := calldataload(ptr) <validate>(value) <!fromCalldata> let value := <cleanup>(mload(ptr)) </fromCalldata> <returnVariables> := <?externalFunction> <splitFunction>(value) <!externalFunction> value </externalFunction> } )"); templ("functionName", functionName); templ("fromCalldata", _fromCalldata); if (_fromCalldata) templ("validate", validatorFunction(_type, true)); auto const* funType = dynamic_cast<FunctionType const*>(&_type); if (funType && funType->kind() == FunctionType::Kind::External) { templ("externalFunction", true); templ("splitFunction", splitExternalFunctionIdFunction()); templ("returnVariables", "addr, selector"); } else { templ("externalFunction", false); templ("returnVariables", "returnValue"); } // Byte array elements generally need cleanup. // Other types are cleaned as well to account for dirty memory e.g. due to inline assembly. templ("cleanup", cleanupFunction(_type)); return templ.render(); }); } std::string YulUtilFunctions::revertReasonIfDebugFunction(std::string const& _message) { std::string functionName = "revert_error_" + util::toHex(util::keccak256(_message).asBytes()); return m_functionCollector.createFunction(functionName, [&](auto&, auto&) -> std::string { return revertReasonIfDebugBody(m_revertStrings, allocateUnboundedFunction() + "()", _message); }); } std::string YulUtilFunctions::revertReasonIfDebugBody( RevertStrings _revertStrings, std::string const& _allocation, std::string const& _message ) { if (_revertStrings < RevertStrings::Debug || _message.empty()) return "revert(0, 0)"; Whiskers templ(R"( let start := <allocate> let pos := start mstore(pos, <sig>) pos := add(pos, 4) mstore(pos, 0x20) pos := add(pos, 0x20) mstore(pos, <length>) pos := add(pos, 0x20) <#word> mstore(add(pos, <offset>), <wordValue>) </word> revert(start, <overallLength>) )"); templ("allocate", _allocation); templ("sig", util::selectorFromSignatureU256("Error(string)").str()); templ("length", std::to_string(_message.length())); size_t words = (_message.length() + 31) / 32; std::vector<std::map<std::string, std::string>> wordParams(words); for (size_t i = 0; i < words; ++i) { wordParams[i]["offset"] = std::to_string(i * 32); wordParams[i]["wordValue"] = formatAsStringOrNumber(_message.substr(32 * i, 32)); } templ("word", wordParams); templ("overallLength", std::to_string(4 + 0x20 + 0x20 + words * 32)); return templ.render(); } std::string YulUtilFunctions::panicFunction(util::PanicCode _code) { std::string functionName = "panic_error_" + toCompactHexWithPrefix(uint64_t(_code)); return m_functionCollector.createFunction(functionName, [&]() { return Whiskers(R"( function <functionName>() { mstore(0, <selector>) mstore(4, <code>) revert(0, 0x24) } )") ("functionName", functionName) ("selector", util::selectorFromSignatureU256("Panic(uint256)").str()) ("code", toCompactHexWithPrefix(static_cast<unsigned>(_code))) .render(); }); } std::string YulUtilFunctions::returnDataSelectorFunction() { std::string const functionName = "return_data_selector"; solAssert(m_evmVersion.supportsReturndata(), ""); return m_functionCollector.createFunction(functionName, [&]() { return util::Whiskers(R"( function <functionName>() -> sig { if gt(returndatasize(), 3) { returndatacopy(0, 0, 4) sig := <shr224>(mload(0)) } } )") ("functionName", functionName) ("shr224", shiftRightFunction(224)) .render(); }); } std::string YulUtilFunctions::tryDecodeErrorMessageFunction() { std::string const functionName = "try_decode_error_message"; solAssert(m_evmVersion.supportsReturndata(), ""); return m_functionCollector.createFunction(functionName, [&]() { return util::Whiskers(R"( function <functionName>() -> ret { if lt(returndatasize(), 0x44) { leave } let data := <allocateUnbounded>() returndatacopy(data, 4, sub(returndatasize(), 4)) let offset := mload(data) if or( gt(offset, 0xffffffffffffffff), gt(add(offset, 0x24), returndatasize()) ) { leave } let msg := add(data, offset) let length := mload(msg) if gt(length, 0xffffffffffffffff) { leave } let end := add(add(msg, 0x20), length) if gt(end, add(data, sub(returndatasize(), 4))) { leave } <finalizeAllocation>(data, add(offset, add(0x20, length))) ret := msg } )") ("functionName", functionName) ("allocateUnbounded", allocateUnboundedFunction()) ("finalizeAllocation", finalizeAllocationFunction()) .render(); }); } std::string YulUtilFunctions::tryDecodePanicDataFunction() { std::string const functionName = "try_decode_panic_data"; solAssert(m_evmVersion.supportsReturndata(), ""); return m_functionCollector.createFunction(functionName, [&]() { return util::Whiskers(R"( function <functionName>() -> success, data { if gt(returndatasize(), 0x23) { returndatacopy(0, 4, 0x20) success := 1 data := mload(0) } } )") ("functionName", functionName) .render(); }); } std::string YulUtilFunctions::extractReturndataFunction() { std::string const functionName = "extract_returndata"; return m_functionCollector.createFunction(functionName, [&]() { return util::Whiskers(R"( function <functionName>() -> data { <?supportsReturndata> switch returndatasize() case 0 { data := <emptyArray>() } default { data := <allocateArray>(returndatasize()) returndatacopy(add(data, 0x20), 0, returndatasize()) } <!supportsReturndata> data := <emptyArray>() </supportsReturndata> } )") ("functionName", functionName) ("supportsReturndata", m_evmVersion.supportsReturndata()) ("allocateArray", allocateMemoryArrayFunction(*TypeProvider::bytesMemory())) ("emptyArray", zeroValueFunction(*TypeProvider::bytesMemory())) .render(); }); } std::string YulUtilFunctions::copyConstructorArgumentsToMemoryFunction( ContractDefinition const& _contract, std::string const& _creationObjectName ) { std::string functionName = "copy_arguments_for_constructor_" + toString(_contract.constructor()->id()) + "_object_" + _contract.name() + "_" + toString(_contract.id()); return m_functionCollector.createFunction(functionName, [&]() { std::string returnParams = suffixedVariableNameList("ret_param_",0, CompilerUtils::sizeOnStack(_contract.constructor()->parameters())); ABIFunctions abiFunctions(m_evmVersion, m_revertStrings, m_functionCollector); return util::Whiskers(R"( function <functionName>() -> <retParams> { let programSize := datasize("<object>") let argSize := sub(codesize(), programSize) let memoryDataOffset := <allocate>(argSize) codecopy(memoryDataOffset, programSize, argSize) <retParams> := <abiDecode>(memoryDataOffset, add(memoryDataOffset, argSize)) } )") ("functionName", functionName) ("retParams", returnParams) ("object", _creationObjectName) ("allocate", allocationFunction()) ("abiDecode", abiFunctions.tupleDecoder(FunctionType(*_contract.constructor()).parameterTypes(), true)) .render(); }); } std::string YulUtilFunctions::externalCodeFunction() { std::string functionName = "external_code_at"; return m_functionCollector.createFunction(functionName, [&]() { return util::Whiskers(R"( function <functionName>(addr) -> mpos { let length := extcodesize(addr) mpos := <allocateArray>(length) extcodecopy(addr, add(mpos, 0x20), 0, length) } )") ("functionName", functionName) ("allocateArray", allocateMemoryArrayFunction(*TypeProvider::bytesMemory())) .render(); }); } std::string YulUtilFunctions::externalFunctionPointersEqualFunction() { std::string const functionName = "externalFunctionPointersEqualFunction"; return m_functionCollector.createFunction(functionName, [&]() { return util::Whiskers(R"( function <functionName>( leftAddress, leftSelector, rightAddress, rightSelector ) -> result { result := and( eq( <addressCleanUpFunction>(leftAddress), <addressCleanUpFunction>(rightAddress) ), eq( <selectorCleanUpFunction>(leftSelector), <selectorCleanUpFunction>(rightSelector) ) ) } )") ("functionName", functionName) ("addressCleanUpFunction", cleanupFunction(*TypeProvider::address())) ("selectorCleanUpFunction", cleanupFunction(*TypeProvider::uint(32))) .render(); }); }
159,535
C++
.cpp
4,419
32.320661
154
0.693117
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
true
false
3,189
Common.cpp
ethereum_solidity/libsolidity/codegen/ir/Common.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libsolidity/ast/TypeProvider.h> #include <libsolidity/codegen/ir/Common.h> #include <libsolidity/codegen/ir/IRGenerationContext.h> #include <libsolutil/CommonIO.h> #include <libyul/AsmPrinter.h> using namespace solidity::langutil; using namespace solidity::frontend; using namespace solidity::util; using namespace solidity::yul; namespace solidity::frontend { YulArity YulArity::fromType(FunctionType const& _functionType) { return YulArity{ TupleType(_functionType.parameterTypesIncludingSelf()).sizeOnStack(), TupleType(_functionType.returnParameterTypes()).sizeOnStack() }; } std::string IRNames::externalFunctionABIWrapper(Declaration const& _functionOrVarDecl) { if (auto const* function = dynamic_cast<FunctionDefinition const*>(&_functionOrVarDecl)) solAssert(!function->isConstructor()); return "external_fun_" + _functionOrVarDecl.name() + "_" + std::to_string(_functionOrVarDecl.id()); } std::string IRNames::function(FunctionDefinition const& _function) { if (_function.isConstructor()) return constructor(*_function.annotation().contract); return "fun_" + _function.name() + "_" + std::to_string(_function.id()); } std::string IRNames::function(VariableDeclaration const& _varDecl) { return "getter_fun_" + _varDecl.name() + "_" + std::to_string(_varDecl.id()); } std::string IRNames::modifierInvocation(ModifierInvocation const& _modifierInvocation) { // This uses the ID of the modifier invocation because it has to be unique // for each invocation. solAssert(!_modifierInvocation.name().path().empty(), ""); std::string const& modifierName = _modifierInvocation.name().path().back(); solAssert(!modifierName.empty(), ""); return "modifier_" + modifierName + "_" + std::to_string(_modifierInvocation.id()); } std::string IRNames::functionWithModifierInner(FunctionDefinition const& _function) { return "fun_" + _function.name() + "_" + std::to_string(_function.id()) + "_inner"; } std::string IRNames::creationObject(ContractDefinition const& _contract) { return _contract.name() + "_" + toString(_contract.id()); } std::string IRNames::deployedObject(ContractDefinition const& _contract) { return _contract.name() + "_" + toString(_contract.id()) + "_deployed"; } std::string IRNames::internalDispatch(YulArity const& _arity) { return "dispatch_internal" "_in_" + std::to_string(_arity.in) + "_out_" + std::to_string(_arity.out); } std::string IRNames::constructor(ContractDefinition const& _contract) { return "constructor_" + _contract.name() + "_" + std::to_string(_contract.id()); } std::string IRNames::libraryAddressImmutable() { return "library_deploy_address"; } std::string IRNames::constantValueFunction(VariableDeclaration const& _constant) { solAssert(_constant.isConstant(), ""); return "constant_" + _constant.name() + "_" + std::to_string(_constant.id()); } std::string IRNames::localVariable(VariableDeclaration const& _declaration) { return "var_" + _declaration.name() + '_' + std::to_string(_declaration.id()); } std::string IRNames::localVariable(Expression const& _expression) { return "expr_" + std::to_string(_expression.id()); } std::string IRNames::trySuccessConditionVariable(Expression const& _expression) { auto annotation = dynamic_cast<FunctionCallAnnotation const*>(&_expression.annotation()); solAssert(annotation, ""); solAssert(annotation->tryCall, "Parameter must be a FunctionCall with tryCall-annotation set."); return "trySuccessCondition_" + std::to_string(_expression.id()); } std::string IRNames::tupleComponent(size_t _i) { return "component_" + std::to_string(_i + 1); } std::string IRNames::zeroValue(Type const& _type, std::string const& _variableName) { return "zero_" + _type.identifier() + _variableName; } std::string dispenseLocationComment(langutil::SourceLocation const& _location, IRGenerationContext& _context) { solAssert(_location.sourceName, ""); _context.markSourceUsed(*_location.sourceName); std::string debugInfo = AsmPrinter::formatSourceLocation( _location, _context.sourceIndices(), _context.debugInfoSelection(), _context.soliditySourceProvider() ); return debugInfo.empty() ? "" : "/// " + debugInfo; } std::string dispenseLocationComment(ASTNode const& _node, IRGenerationContext& _context) { return dispenseLocationComment(_node.location(), _context); } }
5,020
C++
.cpp
128
37.445313
109
0.757563
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
3,191
IRGenerator.cpp
ethereum_solidity/libsolidity/codegen/ir/IRGenerator.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 /** * @author Alex Beregszaszi * @date 2017 * Component that translates Solidity code into Yul. */ #include <libsolidity/codegen/ir/Common.h> #include <libsolidity/codegen/ir/IRGenerator.h> #include <libsolidity/codegen/ir/IRGeneratorForStatements.h> #include <libsolidity/ast/AST.h> #include <libsolidity/ast/ASTVisitor.h> #include <libsolidity/codegen/ABIFunctions.h> #include <libsolidity/codegen/CompilerUtils.h> #include <libyul/Object.h> #include <libyul/Utilities.h> #include <libsolutil/Algorithms.h> #include <libsolutil/CommonData.h> #include <libsolutil/StringUtils.h> #include <libsolutil/Whiskers.h> #include <libsolutil/JSON.h> #include <range/v3/algorithm/all_of.hpp> #include <sstream> #include <variant> using namespace solidity; using namespace solidity::frontend; using namespace solidity::langutil; using namespace solidity::util; using namespace std::string_literals; namespace { void verifyCallGraph( std::set<CallableDeclaration const*, ASTNode::CompareByID> const& _expectedCallables, std::set<FunctionDefinition const*> _generatedFunctions ) { for (auto const& expectedCallable: _expectedCallables) if (auto const* expectedFunction = dynamic_cast<FunctionDefinition const*>(expectedCallable)) { solAssert( _generatedFunctions.count(expectedFunction) == 1 || expectedFunction->isConstructor(), "No code generated for function " + expectedFunction->name() + " even though it is not a constructor." ); _generatedFunctions.erase(expectedFunction); } solAssert( _generatedFunctions.size() == 0, "Of the generated functions " + toString(_generatedFunctions.size()) + " are not in the call graph." ); } std::set<CallableDeclaration const*, ASTNode::CompareByID> collectReachableCallables( CallGraph const& _graph ) { std::set<CallableDeclaration const*, ASTNode::CompareByID> reachableCallables; for (CallGraph::Node const& reachableNode: _graph.edges | ranges::views::keys) if (std::holds_alternative<CallableDeclaration const*>(reachableNode)) reachableCallables.emplace(std::get<CallableDeclaration const*>(reachableNode)); return reachableCallables; } } std::string IRGenerator::run( ContractDefinition const& _contract, bytes const& _cborMetadata, std::map<ContractDefinition const*, std::string_view const> const& _otherYulSources ) { return yul::reindent(generate(_contract, _cborMetadata, _otherYulSources)); } std::string IRGenerator::generate( ContractDefinition const& _contract, bytes const& _cborMetadata, std::map<ContractDefinition const*, std::string_view const> const& _otherYulSources ) { auto subObjectSources = [&_otherYulSources](UniqueVector<ContractDefinition const*> const& _subObjects) -> std::string { std::string subObjectsSources; for (ContractDefinition const* subObject: _subObjects) subObjectsSources += _otherYulSources.at(subObject); return subObjectsSources; }; auto formatUseSrcMap = [](IRGenerationContext const& _context) -> std::string { return joinHumanReadable( ranges::views::transform(_context.usedSourceNames(), [_context](std::string const& _sourceName) { return std::to_string(_context.sourceIndices().at(_sourceName)) + ":" + escapeAndQuoteString(_sourceName); }), ", " ); }; Whiskers t(R"( /// @use-src <useSrcMapCreation> object "<CreationObject>" { code { <sourceLocationCommentCreation> <memoryInitCreation> <callValueCheck> <?library> <!library> <?constructorHasParams> let <constructorParams> := <copyConstructorArguments>() </constructorHasParams> <constructor>(<constructorParams>) </library> <deploy> <functions> } /// @use-src <useSrcMapDeployed> object "<DeployedObject>" { code { <sourceLocationCommentDeployed> <memoryInitDeployed> <?library> <?eof> let called_via_delegatecall := iszero(eq(auxdataloadn(<library_address_immutable_offset>), address())) <!eof> let called_via_delegatecall := iszero(eq(loadimmutable("<library_address>"), address())) </eof> </library> <dispatch> <deployedFunctions> } <deployedSubObjects> data "<metadataName>" hex"<cborMetadata>" } <subObjects> } )"); resetContext(_contract, ExecutionContext::Creation); auto const eof = m_context.eofVersion().has_value(); if (eof && _contract.isLibrary()) m_context.registerLibraryAddressImmutable(); for (VariableDeclaration const* var: ContractType(_contract).immutableVariables()) m_context.registerImmutableVariable(*var); t("CreationObject", IRNames::creationObject(_contract)); t("sourceLocationCommentCreation", dispenseLocationComment(_contract)); t("library", _contract.isLibrary()); FunctionDefinition const* constructor = _contract.constructor(); t("callValueCheck", !constructor || !constructor->isPayable() ? callValueCheck() : ""); std::vector<std::string> constructorParams; if (constructor && !constructor->parameters().empty()) { for (size_t i = 0; i < CompilerUtils::sizeOnStack(constructor->parameters()); ++i) constructorParams.emplace_back(m_context.newYulVariable()); t( "copyConstructorArguments", m_utils.copyConstructorArgumentsToMemoryFunction(_contract, IRNames::creationObject(_contract)) ); } t("constructorParams", joinHumanReadable(constructorParams)); t("constructorHasParams", !constructorParams.empty()); t("constructor", IRNames::constructor(_contract)); t("deploy", deployCode(_contract)); generateConstructors(_contract); std::set<FunctionDefinition const*> creationFunctionList = generateQueuedFunctions(); InternalDispatchMap internalDispatchMap = generateInternalDispatchFunctions(_contract); t("functions", m_context.functionCollector().requestedFunctions()); t("subObjects", subObjectSources(m_context.subObjectsCreated())); // This has to be called only after all other code generation for the creation object is complete. bool creationInvolvesMemoryUnsafeAssembly = m_context.memoryUnsafeInlineAssemblySeen(); t("memoryInitCreation", memoryInit(!creationInvolvesMemoryUnsafeAssembly)); t("useSrcMapCreation", formatUseSrcMap(m_context)); resetContext(_contract, ExecutionContext::Deployed); // NOTE: Function pointers can be passed from creation code via storage variables. We need to // get all the functions they could point to into the dispatch functions even if they're never // referenced by name in the deployed code. m_context.initializeInternalDispatch(std::move(internalDispatchMap)); // Do not register immutables to avoid assignment. t("DeployedObject", IRNames::deployedObject(_contract)); t("sourceLocationCommentDeployed", dispenseLocationComment(_contract)); t("eof", eof); if (_contract.isLibrary()) { if (!eof) t("library_address", IRNames::libraryAddressImmutable()); else t("library_address_immutable_offset", std::to_string(m_context.libraryAddressImmutableOffsetRelative())); } t("dispatch", dispatchRoutine(_contract)); std::set<FunctionDefinition const*> deployedFunctionList = generateQueuedFunctions(); generateInternalDispatchFunctions(_contract); t("deployedFunctions", m_context.functionCollector().requestedFunctions()); t("deployedSubObjects", subObjectSources(m_context.subObjectsCreated())); t("metadataName", yul::Object::metadataName()); t("cborMetadata", util::toHex(_cborMetadata)); t("useSrcMapDeployed", formatUseSrcMap(m_context)); // This has to be called only after all other code generation for the deployed object is complete. bool deployedInvolvesMemoryUnsafeAssembly = m_context.memoryUnsafeInlineAssemblySeen(); t("memoryInitDeployed", memoryInit(!deployedInvolvesMemoryUnsafeAssembly)); solAssert(_contract.annotation().creationCallGraph->get() != nullptr, ""); solAssert(_contract.annotation().deployedCallGraph->get() != nullptr, ""); verifyCallGraph(collectReachableCallables(**_contract.annotation().creationCallGraph), std::move(creationFunctionList)); verifyCallGraph(collectReachableCallables(**_contract.annotation().deployedCallGraph), std::move(deployedFunctionList)); return t.render(); } std::string IRGenerator::generate(Block const& _block) { IRGeneratorForStatements generator(m_context, m_utils, m_optimiserSettings); generator.generate(_block); return generator.code(); } std::set<FunctionDefinition const*> IRGenerator::generateQueuedFunctions() { std::set<FunctionDefinition const*> functions; while (!m_context.functionGenerationQueueEmpty()) { FunctionDefinition const& functionDefinition = *m_context.dequeueFunctionForCodeGeneration(); functions.emplace(&functionDefinition); // NOTE: generateFunction() may modify function generation queue generateFunction(functionDefinition); } return functions; } InternalDispatchMap IRGenerator::generateInternalDispatchFunctions(ContractDefinition const& _contract) { solAssert( m_context.functionGenerationQueueEmpty(), "At this point all the enqueued functions should have been generated. " "Otherwise the dispatch may be incomplete." ); InternalDispatchMap internalDispatchMap = m_context.consumeInternalDispatchMap(); for (YulArity const& arity: internalDispatchMap | ranges::views::keys) { std::string funName = IRNames::internalDispatch(arity); m_context.functionCollector().createFunction(funName, [&]() { Whiskers templ(R"( <sourceLocationComment> function <functionName>(fun<?+in>, <in></+in>) <?+out>-> <out></+out> { switch fun <#cases> case <funID> { <?+out> <out> :=</+out> <name>(<in>) } </cases> default { <panic>() } } <sourceLocationComment> )"); templ("sourceLocationComment", dispenseLocationComment(_contract)); templ("functionName", funName); templ("panic", m_utils.panicFunction(PanicCode::InvalidInternalFunction)); templ("in", suffixedVariableNameList("in_", 0, arity.in)); templ("out", suffixedVariableNameList("out_", 0, arity.out)); std::vector<std::map<std::string, std::string>> cases; std::set<int64_t> caseValues; for (FunctionDefinition const* function: internalDispatchMap.at(arity)) { solAssert(function, ""); solAssert( YulArity::fromType(*TypeProvider::function(*function, FunctionType::Kind::Internal)) == arity, "A single dispatch function can only handle functions of one arity" ); solAssert(!function->isConstructor(), ""); // 0 is reserved for uninitialized function pointers solAssert(function->id() != 0, "Unexpected function ID: 0"); solAssert(caseValues.count(function->id()) == 0, "Duplicate function ID"); solAssert(m_context.functionCollector().contains(IRNames::function(*function)), ""); cases.emplace_back(std::map<std::string, std::string>{ {"funID", std::to_string(m_context.mostDerivedContract().annotation().internalFunctionIDs.at(function))}, {"name", IRNames::function(*function)} }); caseValues.insert(function->id()); } templ("cases", std::move(cases)); return templ.render(); }); } solAssert(m_context.internalDispatchClean(), ""); solAssert( m_context.functionGenerationQueueEmpty(), "Internal dispatch generation must not add new functions to generation queue because they won't be proeessed." ); return internalDispatchMap; } std::string IRGenerator::generateFunction(FunctionDefinition const& _function) { std::string functionName = IRNames::function(_function); return m_context.functionCollector().createFunction(functionName, [&]() { m_context.resetLocalVariables(); Whiskers t(R"( <astIDComment><sourceLocationComment> function <functionName>(<params>)<?+retParams> -> <retParams></+retParams> { <retInit> <body> } <contractSourceLocationComment> )"); if (m_context.debugInfoSelection().astID) t("astIDComment", "/// @ast-id " + std::to_string(_function.id()) + "\n"); else t("astIDComment", ""); t("sourceLocationComment", dispenseLocationComment(_function)); t( "contractSourceLocationComment", dispenseLocationComment(m_context.mostDerivedContract()) ); t("functionName", functionName); std::vector<std::string> params; for (auto const& varDecl: _function.parameters()) params += m_context.addLocalVariable(*varDecl).stackSlots(); t("params", joinHumanReadable(params)); std::vector<std::string> retParams; std::string retInit; for (auto const& varDecl: _function.returnParameters()) { retParams += m_context.addLocalVariable(*varDecl).stackSlots(); retInit += generateInitialAssignment(*varDecl); } t("retParams", joinHumanReadable(retParams)); t("retInit", retInit); if (_function.modifiers().empty()) t("body", generate(_function.body())); else { for (size_t i = 0; i < _function.modifiers().size(); ++i) { ModifierInvocation const& modifier = *_function.modifiers().at(i); std::string next = i + 1 < _function.modifiers().size() ? IRNames::modifierInvocation(*_function.modifiers().at(i + 1)) : IRNames::functionWithModifierInner(_function); generateModifier(modifier, _function, next); } t("body", (retParams.empty() ? std::string{} : joinHumanReadable(retParams) + " := ") + IRNames::modifierInvocation(*_function.modifiers().at(0)) + "(" + joinHumanReadable(retParams + params) + ")" ); // Now generate the actual inner function. generateFunctionWithModifierInner(_function); } return t.render(); }); } std::string IRGenerator::generateModifier( ModifierInvocation const& _modifierInvocation, FunctionDefinition const& _function, std::string const& _nextFunction ) { std::string functionName = IRNames::modifierInvocation(_modifierInvocation); return m_context.functionCollector().createFunction(functionName, [&]() { m_context.resetLocalVariables(); Whiskers t(R"( <astIDComment><sourceLocationComment> function <functionName>(<params>)<?+retParams> -> <retParams></+retParams> { <assignRetParams> <evalArgs> <body> } <contractSourceLocationComment> )"); t("functionName", functionName); std::vector<std::string> retParamsIn; for (auto const& varDecl: _function.returnParameters()) retParamsIn += m_context.addLocalVariable(*varDecl).stackSlots(); std::vector<std::string> params = retParamsIn; for (auto const& varDecl: _function.parameters()) params += m_context.addLocalVariable(*varDecl).stackSlots(); t("params", joinHumanReadable(params)); std::vector<std::string> retParams; std::string assignRetParams; for (size_t i = 0; i < retParamsIn.size(); ++i) { retParams.emplace_back(m_context.newYulVariable()); assignRetParams += retParams.at(i) + " := " + retParamsIn.at(i) + "\n"; } t("retParams", joinHumanReadable(retParams)); t("assignRetParams", assignRetParams); ModifierDefinition const* modifier = dynamic_cast<ModifierDefinition const*>( _modifierInvocation.name().annotation().referencedDeclaration ); solAssert(modifier, ""); if (m_context.debugInfoSelection().astID) t("astIDComment", "/// @ast-id " + std::to_string(modifier->id()) + "\n"); else t("astIDComment", ""); t("sourceLocationComment", dispenseLocationComment(*modifier)); t( "contractSourceLocationComment", dispenseLocationComment(m_context.mostDerivedContract()) ); switch (*_modifierInvocation.name().annotation().requiredLookup) { case VirtualLookup::Virtual: modifier = &modifier->resolveVirtual(m_context.mostDerivedContract()); solAssert(modifier, ""); break; case VirtualLookup::Static: break; case VirtualLookup::Super: solAssert(false, ""); } solAssert( modifier->parameters().empty() == (!_modifierInvocation.arguments() || _modifierInvocation.arguments()->empty()), "" ); IRGeneratorForStatements expressionEvaluator(m_context, m_utils, m_optimiserSettings); if (_modifierInvocation.arguments()) for (size_t i = 0; i < _modifierInvocation.arguments()->size(); i++) { IRVariable argument = expressionEvaluator.evaluateExpression( *_modifierInvocation.arguments()->at(i), *modifier->parameters()[i]->annotation().type ); expressionEvaluator.define( m_context.addLocalVariable(*modifier->parameters()[i]), argument ); } t("evalArgs", expressionEvaluator.code()); IRGeneratorForStatements generator(m_context, m_utils, m_optimiserSettings, [&]() { std::string ret = joinHumanReadable(retParams); return (ret.empty() ? "" : ret + " := ") + _nextFunction + "(" + joinHumanReadable(params) + ")\n"; }); generator.generate(modifier->body()); t("body", generator.code()); return t.render(); }); } std::string IRGenerator::generateFunctionWithModifierInner(FunctionDefinition const& _function) { std::string functionName = IRNames::functionWithModifierInner(_function); return m_context.functionCollector().createFunction(functionName, [&]() { m_context.resetLocalVariables(); Whiskers t(R"( <sourceLocationComment> function <functionName>(<params>)<?+retParams> -> <retParams></+retParams> { <assignRetParams> <body> } <contractSourceLocationComment> )"); t("sourceLocationComment", dispenseLocationComment(_function)); t( "contractSourceLocationComment", dispenseLocationComment(m_context.mostDerivedContract()) ); t("functionName", functionName); std::vector<std::string> retParams; std::vector<std::string> retParamsIn; for (auto const& varDecl: _function.returnParameters()) retParams += m_context.addLocalVariable(*varDecl).stackSlots(); std::string assignRetParams; for (size_t i = 0; i < retParams.size(); ++i) { retParamsIn.emplace_back(m_context.newYulVariable()); assignRetParams += retParams.at(i) + " := " + retParamsIn.at(i) + "\n"; } std::vector<std::string> params = retParamsIn; for (auto const& varDecl: _function.parameters()) params += m_context.addLocalVariable(*varDecl).stackSlots(); t("params", joinHumanReadable(params)); t("retParams", joinHumanReadable(retParams)); t("assignRetParams", assignRetParams); t("body", generate(_function.body())); return t.render(); }); } std::string IRGenerator::generateGetter(VariableDeclaration const& _varDecl) { std::string functionName = IRNames::function(_varDecl); return m_context.functionCollector().createFunction(functionName, [&]() { Type const* type = _varDecl.annotation().type; solAssert(_varDecl.isStateVariable(), ""); FunctionType accessorType(_varDecl); TypePointers paramTypes = accessorType.parameterTypes(); if (_varDecl.immutable()) { solAssert(paramTypes.empty(), ""); solUnimplementedAssert(type->sizeOnStack() == 1); auto t = Whiskers(R"( <astIDComment><sourceLocationComment> function <functionName>() -> rval { <?eof> rval := auxdataloadn(<immutableOffset>) <!eof> rval := loadimmutable("<id>") </eof> } <contractSourceLocationComment> )"); t( "astIDComment", m_context.debugInfoSelection().astID ? "/// @ast-id " + std::to_string(_varDecl.id()) + "\n" : "" ); t("sourceLocationComment", dispenseLocationComment(_varDecl)); t( "contractSourceLocationComment", dispenseLocationComment(m_context.mostDerivedContract()) ); t("functionName", functionName); auto const eof = m_context.eofVersion().has_value(); t("eof", eof); if (!eof) t("id", std::to_string(_varDecl.id())); else t("immutableOffset", std::to_string(m_context.immutableMemoryOffsetRelative(_varDecl))); return t.render(); } else if (_varDecl.isConstant()) { solAssert(paramTypes.empty(), ""); return Whiskers(R"( <astIDComment><sourceLocationComment> function <functionName>() -> <ret> { <ret> := <constantValueFunction>() } <contractSourceLocationComment> )") ( "astIDComment", m_context.debugInfoSelection().astID ? "/// @ast-id " + std::to_string(_varDecl.id()) + "\n" : "" ) ("sourceLocationComment", dispenseLocationComment(_varDecl)) ( "contractSourceLocationComment", dispenseLocationComment(m_context.mostDerivedContract()) ) ("functionName", functionName) ("constantValueFunction", IRGeneratorForStatements(m_context, m_utils, m_optimiserSettings).constantValueFunction(_varDecl)) ("ret", suffixedVariableNameList("ret_", 0, _varDecl.type()->sizeOnStack())) .render(); } std::string code; auto const& location = m_context.storageLocationOfStateVariable(_varDecl); code += Whiskers(R"( let slot := <slot> let offset := <offset> )") ("slot", location.first.str()) ("offset", std::to_string(location.second)) .render(); if (!paramTypes.empty()) solAssert( location.second == 0, "If there are parameters, we are dealing with structs or mappings and thus should have offset zero." ); // The code of an accessor is of the form `x[a][b][c]` (it is slightly more complicated // if the final type is a struct). // In each iteration of the loop below, we consume one parameter, perform an // index access, reassign the yul variable `slot` and move @a currentType further "down". // The initial value of @a currentType is only used if we skip the loop completely. Type const* currentType = _varDecl.annotation().type; std::vector<std::string> parameters; std::vector<std::string> returnVariables; for (size_t i = 0; i < paramTypes.size(); ++i) { MappingType const* mappingType = dynamic_cast<MappingType const*>(currentType); ArrayType const* arrayType = dynamic_cast<ArrayType const*>(currentType); solAssert(mappingType || arrayType, ""); std::vector<std::string> keys = IRVariable("key_" + std::to_string(i), mappingType ? *mappingType->keyType() : *TypeProvider::uint256() ).stackSlots(); parameters += keys; Whiskers templ(R"( <?array> if iszero(lt(<keys>, <length>(slot))) { revert(0, 0) } </array> slot<?array>, offset</array> := <indexAccess>(slot<?+keys>, <keys></+keys>) )"); templ( "indexAccess", mappingType ? m_utils.mappingIndexAccessFunction(*mappingType, *mappingType->keyType()) : m_utils.storageArrayIndexAccessFunction(*arrayType) ) ("array", arrayType != nullptr) ("keys", joinHumanReadable(keys)); if (arrayType) templ("length", m_utils.arrayLengthFunction(*arrayType)); code += templ.render(); currentType = mappingType ? mappingType->valueType() : arrayType->baseType(); } auto returnTypes = accessorType.returnParameterTypes(); solAssert(returnTypes.size() >= 1, ""); if (StructType const* structType = dynamic_cast<StructType const*>(currentType)) { solAssert(location.second == 0, ""); auto const& names = accessorType.returnParameterNames(); for (size_t i = 0; i < names.size(); ++i) { if (returnTypes[i]->category() == Type::Category::Mapping) continue; if ( auto const* arrayType = dynamic_cast<ArrayType const*>(returnTypes[i]); arrayType && !arrayType->isByteArrayOrString() ) continue; std::pair<u256, unsigned> const& offsets = structType->storageOffsetsOfMember(names[i]); std::vector<std::string> retVars = IRVariable("ret_" + std::to_string(returnVariables.size()), *returnTypes[i]).stackSlots(); returnVariables += retVars; code += Whiskers(R"( <ret> := <readStorage>(add(slot, <slotOffset>)) )") ("ret", joinHumanReadable(retVars)) ("readStorage", m_utils.readFromStorage(*returnTypes[i], offsets.second, true, _varDecl.referenceLocation())) ("slotOffset", offsets.first.str()) .render(); } } else { solAssert(returnTypes.size() == 1, ""); auto const* arrayType = dynamic_cast<ArrayType const*>(returnTypes.front()); if (arrayType) solAssert(arrayType->isByteArrayOrString(), ""); std::vector<std::string> retVars = IRVariable("ret", *returnTypes.front()).stackSlots(); returnVariables += retVars; code += Whiskers(R"( <ret> := <readStorage>(slot, offset) )") ("ret", joinHumanReadable(retVars)) ("readStorage", m_utils.readFromStorageDynamic(*returnTypes.front(), true, _varDecl.referenceLocation())) .render(); } return Whiskers(R"( <astIDComment><sourceLocationComment> function <functionName>(<params>) -> <retVariables> { <code> } <contractSourceLocationComment> )") ("functionName", functionName) ("params", joinHumanReadable(parameters)) ("retVariables", joinHumanReadable(returnVariables)) ("code", std::move(code)) ( "astIDComment", m_context.debugInfoSelection().astID ? "/// @ast-id " + std::to_string(_varDecl.id()) + "\n" : "" ) ("sourceLocationComment", dispenseLocationComment(_varDecl)) ( "contractSourceLocationComment", dispenseLocationComment(m_context.mostDerivedContract()) ) .render(); }); } std::string IRGenerator::generateExternalFunction(ContractDefinition const& _contract, FunctionType const& _functionType) { std::string functionName = IRNames::externalFunctionABIWrapper(_functionType.declaration()); return m_context.functionCollector().createFunction(functionName, [&](std::vector<std::string>&, std::vector<std::string>&) -> std::string { Whiskers t(R"X( <callValueCheck> <?+params>let <params> := </+params> <abiDecode>(4, calldatasize()) <?+retParams>let <retParams> := </+retParams> <function>(<params>) let memPos := <allocateUnbounded>() let memEnd := <abiEncode>(memPos <?+retParams>,</+retParams> <retParams>) return(memPos, sub(memEnd, memPos)) )X"); t("callValueCheck", (_functionType.isPayable() || _contract.isLibrary()) ? "" : callValueCheck()); unsigned paramVars = std::make_shared<TupleType>(_functionType.parameterTypes())->sizeOnStack(); unsigned retVars = std::make_shared<TupleType>(_functionType.returnParameterTypes())->sizeOnStack(); ABIFunctions abiFunctions(m_evmVersion, m_context.revertStrings(), m_context.functionCollector()); t("abiDecode", abiFunctions.tupleDecoder(_functionType.parameterTypes())); t("params", suffixedVariableNameList("param_", 0, paramVars)); t("retParams", suffixedVariableNameList("ret_", 0, retVars)); if (FunctionDefinition const* funDef = dynamic_cast<FunctionDefinition const*>(&_functionType.declaration())) { solAssert(!funDef->isConstructor()); t("function", m_context.enqueueFunctionForCodeGeneration(*funDef)); } else if (VariableDeclaration const* varDecl = dynamic_cast<VariableDeclaration const*>(&_functionType.declaration())) t("function", generateGetter(*varDecl)); else solAssert(false, "Unexpected declaration for function!"); t("allocateUnbounded", m_utils.allocateUnboundedFunction()); t("abiEncode", abiFunctions.tupleEncoder(_functionType.returnParameterTypes(), _functionType.returnParameterTypes(), _contract.isLibrary())); return t.render(); }); } std::string IRGenerator::generateInitialAssignment(VariableDeclaration const& _varDecl) { IRGeneratorForStatements generator(m_context, m_utils, m_optimiserSettings); generator.initializeLocalVar(_varDecl); return generator.code(); } std::pair<std::string, std::map<ContractDefinition const*, std::vector<std::string>>> IRGenerator::evaluateConstructorArguments( ContractDefinition const& _contract ) { struct InheritanceOrder { bool operator()(ContractDefinition const* _c1, ContractDefinition const* _c2) const { solAssert(util::contains(linearizedBaseContracts, _c1) && util::contains(linearizedBaseContracts, _c2), ""); auto it1 = find(linearizedBaseContracts.begin(), linearizedBaseContracts.end(), _c1); auto it2 = find(linearizedBaseContracts.begin(), linearizedBaseContracts.end(), _c2); return it1 < it2; } std::vector<ContractDefinition const*> const& linearizedBaseContracts; } inheritanceOrder{_contract.annotation().linearizedBaseContracts}; std::map<ContractDefinition const*, std::vector<std::string>> constructorParams; std::map<ContractDefinition const*, std::vector<ASTPointer<Expression>>const *, InheritanceOrder> baseConstructorArguments(inheritanceOrder); for (ASTPointer<InheritanceSpecifier> const& base: _contract.baseContracts()) if (FunctionDefinition const* baseConstructor = dynamic_cast<ContractDefinition const*>( base->name().annotation().referencedDeclaration )->constructor(); baseConstructor && base->arguments()) solAssert(baseConstructorArguments.emplace( dynamic_cast<ContractDefinition const*>(baseConstructor->scope()), base->arguments() ).second, ""); if (FunctionDefinition const* constructor = _contract.constructor()) for (ASTPointer<ModifierInvocation> const& modifier: constructor->modifiers()) if (auto const* baseContract = dynamic_cast<ContractDefinition const*>( modifier->name().annotation().referencedDeclaration )) if ( FunctionDefinition const* baseConstructor = baseContract->constructor(); baseConstructor && modifier->arguments() ) solAssert(baseConstructorArguments.emplace( dynamic_cast<ContractDefinition const*>(baseConstructor->scope()), modifier->arguments() ).second, ""); IRGeneratorForStatements generator{m_context, m_utils, m_optimiserSettings}; for (auto&& [baseContract, arguments]: baseConstructorArguments) { solAssert(baseContract && arguments, ""); if (baseContract->constructor() && !arguments->empty()) { std::vector<std::string> params; for (size_t i = 0; i < arguments->size(); ++i) params += generator.evaluateExpression( *(arguments->at(i)), *(baseContract->constructor()->parameters()[i]->type()) ).stackSlots(); constructorParams[baseContract] = std::move(params); } } return {generator.code(), constructorParams}; } std::string IRGenerator::initStateVariables(ContractDefinition const& _contract) { IRGeneratorForStatements generator{m_context, m_utils, m_optimiserSettings}; for (VariableDeclaration const* variable: _contract.stateVariables()) { if (!variable->isConstant()) generator.initializeStateVar(*variable); } return generator.code(); } void IRGenerator::generateConstructors(ContractDefinition const& _contract) { auto listAllParams = [&](std::map<ContractDefinition const*, std::vector<std::string>> const& baseParams) -> std::vector<std::string> { std::vector<std::string> params; for (ContractDefinition const* contract: _contract.annotation().linearizedBaseContracts) if (baseParams.count(contract)) params += baseParams.at(contract); return params; }; std::map<ContractDefinition const*, std::vector<std::string>> baseConstructorParams; for (size_t i = 0; i < _contract.annotation().linearizedBaseContracts.size(); ++i) { ContractDefinition const* contract = _contract.annotation().linearizedBaseContracts[i]; baseConstructorParams.erase(contract); m_context.resetLocalVariables(); m_context.functionCollector().createFunction(IRNames::constructor(*contract), [&]() { Whiskers t(R"( <astIDComment><sourceLocationComment> function <functionName>(<params><comma><baseParams>) { <evalBaseArguments> <sourceLocationComment> <?hasNextConstructor> <nextConstructor>(<nextParams>) </hasNextConstructor> <initStateVariables> <userDefinedConstructorBody> } <contractSourceLocationComment> )"); std::vector<std::string> params; if (contract->constructor()) for (ASTPointer<VariableDeclaration> const& varDecl: contract->constructor()->parameters()) params += m_context.addLocalVariable(*varDecl).stackSlots(); if (m_context.debugInfoSelection().astID && contract->constructor()) t("astIDComment", "/// @ast-id " + std::to_string(contract->constructor()->id()) + "\n"); else t("astIDComment", ""); t("sourceLocationComment", dispenseLocationComment( contract->constructor() ? dynamic_cast<ASTNode const&>(*contract->constructor()) : dynamic_cast<ASTNode const&>(*contract) )); t( "contractSourceLocationComment", dispenseLocationComment(m_context.mostDerivedContract()) ); t("params", joinHumanReadable(params)); std::vector<std::string> baseParams = listAllParams(baseConstructorParams); t("baseParams", joinHumanReadable(baseParams)); t("comma", !params.empty() && !baseParams.empty() ? ", " : ""); t("functionName", IRNames::constructor(*contract)); std::pair<std::string, std::map<ContractDefinition const*, std::vector<std::string>>> evaluatedArgs = evaluateConstructorArguments(*contract); baseConstructorParams.insert(evaluatedArgs.second.begin(), evaluatedArgs.second.end()); t("evalBaseArguments", evaluatedArgs.first); if (i < _contract.annotation().linearizedBaseContracts.size() - 1) { t("hasNextConstructor", true); ContractDefinition const* nextContract = _contract.annotation().linearizedBaseContracts[i + 1]; t("nextConstructor", IRNames::constructor(*nextContract)); t("nextParams", joinHumanReadable(listAllParams(baseConstructorParams))); } else t("hasNextConstructor", false); t("initStateVariables", initStateVariables(*contract)); std::string body; if (FunctionDefinition const* constructor = contract->constructor()) { std::vector<ModifierInvocation*> realModifiers; for (auto const& modifierInvocation: constructor->modifiers()) // Filter out the base constructor calls if (dynamic_cast<ModifierDefinition const*>(modifierInvocation->name().annotation().referencedDeclaration)) realModifiers.emplace_back(modifierInvocation.get()); if (realModifiers.empty()) body = generate(constructor->body()); else { for (size_t i = 0; i < realModifiers.size(); ++i) { ModifierInvocation const& modifier = *realModifiers.at(i); std::string next = i + 1 < realModifiers.size() ? IRNames::modifierInvocation(*realModifiers.at(i + 1)) : IRNames::functionWithModifierInner(*constructor); generateModifier(modifier, *constructor, next); } body = IRNames::modifierInvocation(*realModifiers.at(0)) + "(" + joinHumanReadable(params) + ")"; // Now generate the actual inner function. generateFunctionWithModifierInner(*constructor); } } t("userDefinedConstructorBody", std::move(body)); return t.render(); }); } } std::string IRGenerator::deployCode(ContractDefinition const& _contract) { Whiskers t(R"X( <?eof> <?library> mstore(<libraryAddressImmutableOffset>, address()) </library> returncontract("<object>", <auxDataStart>, <auxDataSize>) <!eof> let <codeOffset> := <allocateUnbounded>() codecopy(<codeOffset>, dataoffset("<object>"), datasize("<object>")) <#immutables> setimmutable(<codeOffset>, "<immutableName>", <value>) </immutables> return(<codeOffset>, datasize("<object>")) </eof> )X"); auto const eof = m_context.eofVersion().has_value(); t("eof", eof); t("allocateUnbounded", m_utils.allocateUnboundedFunction()); t("codeOffset", m_context.newYulVariable()); t("object", IRNames::deployedObject(_contract)); std::vector<std::map<std::string, std::string>> immutables; if (_contract.isLibrary()) { solAssert(ContractType(_contract).immutableVariables().empty(), ""); if (!eof) immutables.emplace_back(std::map<std::string, std::string>{ {"immutableName"s, IRNames::libraryAddressImmutable()}, {"value"s, "address()"} }); else t("libraryAddressImmutableOffset", std::to_string(m_context.libraryAddressImmutableOffset())); } else { for (VariableDeclaration const* immutable: ContractType(_contract).immutableVariables()) { solUnimplementedAssert(immutable->type()->isValueType()); solUnimplementedAssert(immutable->type()->sizeOnStack() == 1); if (!eof) immutables.emplace_back(std::map<std::string, std::string>{ {"immutableName"s, std::to_string(immutable->id())}, {"value"s, "mload(" + std::to_string(m_context.immutableMemoryOffset(*immutable)) + ")"} }); } } if (eof) { t("auxDataStart", std::to_string(CompilerUtils::generalPurposeMemoryStart)); solAssert(m_context.reservedMemorySize() <= 0xFFFF, "Reserved memory size exceeded maximum allowed EOF data section size."); t("auxDataSize", std::to_string(m_context.reservedMemorySize())); } else t("immutables", std::move(immutables)); return t.render(); } std::string IRGenerator::callValueCheck() { return "if callvalue() { " + m_utils.revertReasonIfDebugFunction("Ether sent to non-payable function") + "() }"; } std::string IRGenerator::dispatchRoutine(ContractDefinition const& _contract) { Whiskers t(R"X( <?+cases>if iszero(lt(calldatasize(), 4)) { let selector := <shr224>(calldataload(0)) switch selector <#cases> case <functionSelector> { // <functionName> <delegatecallCheck> <externalFunction>() } </cases> default {} }</+cases> <?+receiveEther>if iszero(calldatasize()) { <receiveEther> }</+receiveEther> <fallback> )X"); t("shr224", m_utils.shiftRightFunction(224)); std::vector<std::map<std::string, std::string>> functions; for (auto const& function: _contract.interfaceFunctions()) { functions.emplace_back(); std::map<std::string, std::string>& templ = functions.back(); templ["functionSelector"] = "0x" + function.first.hex(); FunctionTypePointer const& type = function.second; templ["functionName"] = type->externalSignature(); std::string delegatecallCheck; if (_contract.isLibrary()) { solAssert(!type->isPayable(), ""); if (type->stateMutability() > StateMutability::View) // If the function is not a view function and is called without DELEGATECALL, // we revert. delegatecallCheck = "if iszero(called_via_delegatecall) { " + m_utils.revertReasonIfDebugFunction("Non-view function of library called without DELEGATECALL") + "() }"; } templ["delegatecallCheck"] = delegatecallCheck; templ["externalFunction"] = generateExternalFunction(_contract, *type); } t("cases", functions); FunctionDefinition const* etherReceiver = _contract.receiveFunction(); if (etherReceiver) { solAssert(!_contract.isLibrary(), ""); t("receiveEther", m_context.enqueueFunctionForCodeGeneration(*etherReceiver) + "() stop()"); } else t("receiveEther", ""); if (FunctionDefinition const* fallback = _contract.fallbackFunction()) { solAssert(!_contract.isLibrary(), ""); std::string fallbackCode; if (!fallback->isPayable()) fallbackCode += callValueCheck() + "\n"; if (fallback->parameters().empty()) fallbackCode += m_context.enqueueFunctionForCodeGeneration(*fallback) + "() stop()"; else { solAssert(fallback->parameters().size() == 1 && fallback->returnParameters().size() == 1, ""); fallbackCode += "let retval := " + m_context.enqueueFunctionForCodeGeneration(*fallback) + "(0, calldatasize())\n"; fallbackCode += "return(add(retval, 0x20), mload(retval))\n"; } t("fallback", fallbackCode); } else t("fallback", ( etherReceiver ? m_utils.revertReasonIfDebugFunction("Unknown signature and no fallback defined") : m_utils.revertReasonIfDebugFunction("Contract does not have fallback nor receive functions") ) + "()"); return t.render(); } std::string IRGenerator::memoryInit(bool _useMemoryGuard) { // This function should be called at the beginning of the EVM call frame // and thus can assume all memory to be zero, including the contents of // the "zero memory area" (the position CompilerUtils::zeroPointer points to). return Whiskers{ _useMemoryGuard ? "mstore(<memPtr>, memoryguard(<freeMemoryStart>))" : "mstore(<memPtr>, <freeMemoryStart>)" } ("memPtr", std::to_string(CompilerUtils::freeMemoryPointer)) ( "freeMemoryStart", std::to_string(CompilerUtils::generalPurposeMemoryStart + m_context.reservedMemory()) ).render(); } void IRGenerator::resetContext(ContractDefinition const& _contract, ExecutionContext _context) { solAssert( m_context.functionGenerationQueueEmpty(), "Reset function generation queue while it still had functions." ); solAssert( m_context.functionCollector().requestedFunctions().empty(), "Reset context while it still had functions." ); solAssert( m_context.internalDispatchClean(), "Reset internal dispatch map without consuming it." ); IRGenerationContext newContext( m_evmVersion, m_eofVersion, _context, m_context.revertStrings(), m_context.sourceIndices(), m_context.debugInfoSelection(), m_context.soliditySourceProvider() ); m_context = std::move(newContext); m_context.setMostDerivedContract(_contract); for (auto const location: {DataLocation::Storage, DataLocation::Transient}) for (auto const& var: ContractType(_contract).stateVariables(location)) m_context.addStateVariable(*std::get<0>(var), std::get<1>(var), std::get<2>(var)); } std::string IRGenerator::dispenseLocationComment(ASTNode const& _node) { return ::dispenseLocationComment(_node, m_context); }
41,566
C++
.cpp
1,054
35.942125
145
0.729356
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
3,192
IRGeneratorForStatements.cpp
ethereum_solidity/libsolidity/codegen/ir/IRGeneratorForStatements.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 /** * Component that translates Solidity code into Yul at statement level and below. */ #include <libsolidity/codegen/ir/IRGeneratorForStatements.h> #include <libsolidity/codegen/ABIFunctions.h> #include <libsolidity/codegen/ir/IRGenerationContext.h> #include <libsolidity/codegen/ir/IRLValue.h> #include <libsolidity/codegen/ir/IRVariable.h> #include <libsolidity/codegen/YulUtilFunctions.h> #include <libsolidity/codegen/ABIFunctions.h> #include <libsolidity/codegen/CompilerUtils.h> #include <libsolidity/codegen/ReturnInfo.h> #include <libsolidity/ast/TypeProvider.h> #include <libsolidity/ast/ASTUtils.h> #include <libevmasm/GasMeter.h> #include <libyul/AsmPrinter.h> #include <libyul/AST.h> #include <libyul/Dialect.h> #include <libyul/Utilities.h> #include <libyul/optimiser/ASTCopier.h> #include <liblangutil/Exceptions.h> #include <libsolutil/Whiskers.h> #include <libsolutil/StringUtils.h> #include <libsolutil/Keccak256.h> #include <libsolutil/FunctionSelector.h> #include <libsolutil/Visitor.h> #include <range/v3/algorithm/all_of.hpp> #include <range/v3/view/transform.hpp> using namespace solidity; using namespace solidity::util; using namespace solidity::frontend; using namespace std::string_literals; namespace { struct CopyTranslate: public yul::ASTCopier { using ExternalRefsMap = std::map<yul::Identifier const*, InlineAssemblyAnnotation::ExternalIdentifierInfo>; CopyTranslate(yul::Dialect const& _dialect, IRGenerationContext& _context, ExternalRefsMap const& _references): m_dialect(_dialect), m_context(_context), m_references(_references) {} using ASTCopier::operator(); yul::Expression operator()(yul::Identifier const& _identifier) override { // The operator() function is only called in lvalue context. In rvalue context, // only translate(yul::Identifier) is called. if (m_references.count(&_identifier)) return translateReference(_identifier); else return ASTCopier::operator()(_identifier); } yul::YulName translateIdentifier(yul::YulName _name) override { // Strictly, the dialect used by inline assembly (m_dialect) could be different // from the Yul dialect we are compiling to. So we are assuming here that the builtin // functions are identical. This should not be a problem for now since everything // is EVM anyway. if (m_dialect.findBuiltin(_name.str())) return _name; else return yul::YulName{"usr$" + _name.str()}; } yul::Identifier translate(yul::Identifier const& _identifier) override { if (!m_references.count(&_identifier)) return ASTCopier::translate(_identifier); yul::Expression translated = translateReference(_identifier); solAssert(std::holds_alternative<yul::Identifier>(translated)); return std::get<yul::Identifier>(std::move(translated)); } private: /// Translates a reference to a local variable, potentially including /// a suffix. Might return a literal, which causes this to be invalid in /// lvalue-context. yul::Expression translateReference(yul::Identifier const& _identifier) { auto const& reference = m_references.at(&_identifier); auto const varDecl = dynamic_cast<VariableDeclaration const*>(reference.declaration); solUnimplementedAssert(varDecl); std::string const& suffix = reference.suffix; std::string value; if (suffix.empty() && varDecl->isLocalVariable()) { auto const& var = m_context.localVariable(*varDecl); solAssert(var.type().sizeOnStack() == 1); value = var.commaSeparatedList(); } else if (varDecl->isConstant()) { VariableDeclaration const* variable = rootConstVariableDeclaration(*varDecl); solAssert(variable); if (variable->value()->annotation().type->category() == Type::Category::RationalNumber) { u256 intValue = dynamic_cast<RationalNumberType const&>(*variable->value()->annotation().type).literalValue(nullptr); if (auto const* bytesType = dynamic_cast<FixedBytesType const*>(variable->type())) intValue <<= 256 - 8 * bytesType->numBytes(); else solAssert(variable->type()->category() == Type::Category::Integer); value = intValue.str(); } else if (auto const* literal = dynamic_cast<Literal const*>(variable->value().get())) { Type const* type = literal->annotation().type; switch (type->category()) { case Type::Category::Bool: case Type::Category::Address: solAssert(type->category() == variable->annotation().type->category()); value = toCompactHexWithPrefix(type->literalValue(literal)); break; case Type::Category::StringLiteral: { auto const& stringLiteral = dynamic_cast<StringLiteralType const&>(*type); solAssert(variable->type()->category() == Type::Category::FixedBytes); unsigned const numBytes = dynamic_cast<FixedBytesType const&>(*variable->type()).numBytes(); solAssert(stringLiteral.value().size() <= numBytes); value = formatNumber(u256(h256(stringLiteral.value(), h256::AlignLeft))); break; } default: solAssert(false); } } else solAssert(false, "Invalid constant in inline assembly."); } else if (varDecl->isStateVariable()) { if (suffix == "slot") value = m_context.storageLocationOfStateVariable(*varDecl).first.str(); else if (suffix == "offset") value = std::to_string(m_context.storageLocationOfStateVariable(*varDecl).second); else solAssert(false); } else if (varDecl->type()->dataStoredIn(DataLocation::Storage)) { solAssert(suffix == "slot" || suffix == "offset"); solAssert(varDecl->isLocalVariable()); solAssert(!varDecl->type()->isValueType()); if (suffix == "slot") value = IRVariable{*varDecl}.part("slot").name(); else { solAssert(!IRVariable{*varDecl}.hasPart("offset")); value = "0"s; } } else if (varDecl->type()->dataStoredIn(DataLocation::CallData)) { solAssert(suffix == "offset" || suffix == "length"); value = IRVariable{*varDecl}.part(suffix).name(); } else if ( auto const* functionType = dynamic_cast<FunctionType const*>(varDecl->type()); functionType && functionType->kind() == FunctionType::Kind::External ) { solAssert(suffix == "selector" || suffix == "address"); solAssert(varDecl->type()->sizeOnStack() == 2); if (suffix == "selector") value = IRVariable{*varDecl}.part("functionSelector").name(); else value = IRVariable{*varDecl}.part("address").name(); } else solAssert(false); if (isDigit(value.front())) return yul::Literal{_identifier.debugData, yul::LiteralKind::Number, yul::valueOfNumberLiteral(value)}; else return yul::Identifier{_identifier.debugData, yul::YulName{value}}; } yul::Dialect const& m_dialect; IRGenerationContext& m_context; ExternalRefsMap const& m_references; }; } std::string IRGeneratorForStatementsBase::code() const { return m_code.str(); } std::ostringstream& IRGeneratorForStatementsBase::appendCode(bool _addLocationComment) { if ( _addLocationComment && m_currentLocation.isValid() && m_lastLocation != m_currentLocation ) m_code << dispenseLocationComment(m_currentLocation, m_context) << "\n"; m_lastLocation = m_currentLocation; return m_code; } void IRGeneratorForStatementsBase::setLocation(ASTNode const& _node) { m_currentLocation = _node.location(); } std::string IRGeneratorForStatements::code() const { solAssert(!m_currentLValue, "LValue not reset!"); return IRGeneratorForStatementsBase::code(); } void IRGeneratorForStatements::generate(Block const& _block) { try { _block.accept(*this); } catch (langutil::UnimplementedFeatureError const& _error) { if (!boost::get_error_info<langutil::errinfo_sourceLocation>(_error)) _error << langutil::errinfo_sourceLocation(m_currentLocation); BOOST_THROW_EXCEPTION(_error); } } void IRGeneratorForStatements::initializeStateVar(VariableDeclaration const& _varDecl) { try { setLocation(_varDecl); solAssert(_varDecl.immutable() || m_context.isStateVariable(_varDecl), "Must be immutable or a state variable."); solAssert(!_varDecl.isConstant()); if (!_varDecl.value()) return; solAssert(_varDecl.referenceLocation() != VariableDeclaration::Location::Transient, "Transient storage state variables cannot be initialized in place."); _varDecl.value()->accept(*this); writeToLValue( _varDecl.immutable() ? IRLValue{*_varDecl.annotation().type, IRLValue::Immutable{&_varDecl}} : IRLValue{*_varDecl.annotation().type, IRLValue::Storage{ toCompactHexWithPrefix(m_context.storageLocationOfStateVariable(_varDecl).first), m_context.storageLocationOfStateVariable(_varDecl).second }}, *_varDecl.value() ); } catch (langutil::UnimplementedFeatureError const& _error) { if (!boost::get_error_info<langutil::errinfo_sourceLocation>(_error)) _error << langutil::errinfo_sourceLocation(m_currentLocation); BOOST_THROW_EXCEPTION(_error); } } void IRGeneratorForStatements::initializeLocalVar(VariableDeclaration const& _varDecl) { try { setLocation(_varDecl); solAssert(m_context.isLocalVariable(_varDecl), "Must be a local variable."); auto const* type = _varDecl.type(); if (dynamic_cast<MappingType const*>(type)) return; else if (auto const* refType = dynamic_cast<ReferenceType const*>(type)) if (refType->dataStoredIn(DataLocation::Storage) && refType->isPointer()) return; IRVariable zero = zeroValue(*type); assign(m_context.localVariable(_varDecl), zero); } catch (langutil::UnimplementedFeatureError const& _error) { if (!boost::get_error_info<langutil::errinfo_sourceLocation>(_error)) _error << langutil::errinfo_sourceLocation(m_currentLocation); BOOST_THROW_EXCEPTION(_error); } } IRVariable IRGeneratorForStatements::evaluateExpression(Expression const& _expression, Type const& _targetType) { try { setLocation(_expression); _expression.accept(*this); setLocation(_expression); IRVariable variable{m_context.newYulVariable(), _targetType}; define(variable, _expression); return variable; } catch (langutil::UnimplementedFeatureError const& _error) { if (!boost::get_error_info<langutil::errinfo_sourceLocation>(_error)) _error << langutil::errinfo_sourceLocation(m_currentLocation); BOOST_THROW_EXCEPTION(_error); } } std::string IRGeneratorForStatements::constantValueFunction(VariableDeclaration const& _constant) { try { std::string functionName = IRNames::constantValueFunction(_constant); return m_context.functionCollector().createFunction(functionName, [&] { Whiskers templ(R"( <sourceLocationComment> function <functionName>() -> <ret> { <code> <ret> := <value> } )"); templ("sourceLocationComment", dispenseLocationComment(_constant, m_context)); templ("functionName", functionName); IRGeneratorForStatements generator(m_context, m_utils, m_optimiserSettings); solAssert(_constant.value()); Type const& constantType = *_constant.type(); templ("value", generator.evaluateExpression(*_constant.value(), constantType).commaSeparatedList()); templ("code", generator.code()); templ("ret", IRVariable("ret", constantType).commaSeparatedList()); return templ.render(); }); } catch (langutil::UnimplementedFeatureError const& _error) { if (!boost::get_error_info<langutil::errinfo_sourceLocation>(_error)) _error << langutil::errinfo_sourceLocation(m_currentLocation); BOOST_THROW_EXCEPTION(_error); } } void IRGeneratorForStatements::endVisit(VariableDeclarationStatement const& _varDeclStatement) { setLocation(_varDeclStatement); if (Expression const* expression = _varDeclStatement.initialValue()) { if (_varDeclStatement.declarations().size() > 1) { auto const* tupleType = dynamic_cast<TupleType const*>(expression->annotation().type); solAssert(tupleType, "Expected expression of tuple type."); solAssert(_varDeclStatement.declarations().size() == tupleType->components().size(), "Invalid number of tuple components."); for (size_t i = 0; i < _varDeclStatement.declarations().size(); ++i) if (auto const& decl = _varDeclStatement.declarations()[i]) { solAssert(tupleType->components()[i]); define(m_context.addLocalVariable(*decl), IRVariable(*expression).tupleComponent(i)); } } else { VariableDeclaration const& varDecl = *_varDeclStatement.declarations().front(); define(m_context.addLocalVariable(varDecl), *expression); } } else for (auto const& decl: _varDeclStatement.declarations()) if (decl) { declare(m_context.addLocalVariable(*decl)); initializeLocalVar(*decl); } } bool IRGeneratorForStatements::visit(Conditional const& _conditional) { _conditional.condition().accept(*this); setLocation(_conditional); std::string condition = expressionAsType(_conditional.condition(), *TypeProvider::boolean()); declare(_conditional); appendCode() << "switch " << condition << "\n" "case 0 {\n"; _conditional.falseExpression().accept(*this); setLocation(_conditional); assign(_conditional, _conditional.falseExpression()); appendCode() << "}\n" "default {\n"; _conditional.trueExpression().accept(*this); setLocation(_conditional); assign(_conditional, _conditional.trueExpression()); appendCode() << "}\n"; return false; } bool IRGeneratorForStatements::visit(Assignment const& _assignment) { _assignment.rightHandSide().accept(*this); setLocation(_assignment); Token assignmentOperator = _assignment.assignmentOperator(); Token binaryOperator = assignmentOperator == Token::Assign ? assignmentOperator : TokenTraits::AssignmentToBinaryOp(assignmentOperator); if (TokenTraits::isShiftOp(binaryOperator)) solAssert(type(_assignment.rightHandSide()).mobileType()); IRVariable value = type(_assignment.leftHandSide()).isValueType() ? convert( _assignment.rightHandSide(), TokenTraits::isShiftOp(binaryOperator) ? *type(_assignment.rightHandSide()).mobileType() : type(_assignment) ) : _assignment.rightHandSide(); _assignment.leftHandSide().accept(*this); solAssert(!!m_currentLValue, "LValue not retrieved."); setLocation(_assignment); if (assignmentOperator != Token::Assign) { solAssert(type(_assignment.leftHandSide()).isValueType(), "Compound operators only available for value types."); solAssert(binaryOperator != Token::Exp); solAssert(type(_assignment) == type(_assignment.leftHandSide())); IRVariable leftIntermediate = readFromLValue(*m_currentLValue); solAssert(type(_assignment) == leftIntermediate.type()); define(_assignment) << ( TokenTraits::isShiftOp(binaryOperator) ? shiftOperation(binaryOperator, leftIntermediate, value) : binaryOperation(binaryOperator, type(_assignment), leftIntermediate.name(), value.name()) ) << "\n"; writeToLValue(*m_currentLValue, IRVariable(_assignment)); } else { writeToLValue(*m_currentLValue, value); if (dynamic_cast<ReferenceType const*>(&m_currentLValue->type)) define(_assignment, readFromLValue(*m_currentLValue)); else if (*_assignment.annotation().type != *TypeProvider::emptyTuple()) define(_assignment, value); } m_currentLValue.reset(); return false; } bool IRGeneratorForStatements::visit(TupleExpression const& _tuple) { setLocation(_tuple); if (_tuple.isInlineArray()) { auto const& arrayType = dynamic_cast<ArrayType const&>(*_tuple.annotation().type); solAssert(!arrayType.isDynamicallySized(), "Cannot create dynamically sized inline array."); define(_tuple) << m_utils.allocateMemoryArrayFunction(arrayType) << "(" << _tuple.components().size() << ")\n"; std::string mpos = IRVariable(_tuple).part("mpos").name(); Type const& baseType = *arrayType.baseType(); for (size_t i = 0; i < _tuple.components().size(); i++) { Expression const& component = *_tuple.components()[i]; component.accept(*this); setLocation(_tuple); IRVariable converted = convert(component, baseType); appendCode() << m_utils.writeToMemoryFunction(baseType) << "(" << ("add(" + mpos + ", " + std::to_string(i * arrayType.memoryStride()) + ")") << ", " << converted.commaSeparatedList() << ")\n"; } } else { bool willBeWrittenTo = _tuple.annotation().willBeWrittenTo; if (willBeWrittenTo) solAssert(!m_currentLValue); if (_tuple.components().size() == 1) { solAssert(_tuple.components().front()); _tuple.components().front()->accept(*this); setLocation(_tuple); if (willBeWrittenTo) solAssert(!!m_currentLValue); else define(_tuple, *_tuple.components().front()); } else { std::vector<std::optional<IRLValue>> lvalues; for (size_t i = 0; i < _tuple.components().size(); ++i) if (auto const& component = _tuple.components()[i]) { component->accept(*this); setLocation(_tuple); if (willBeWrittenTo) { solAssert(!!m_currentLValue); lvalues.emplace_back(std::move(m_currentLValue)); m_currentLValue.reset(); } else define(IRVariable(_tuple).tupleComponent(i), *component); } else if (willBeWrittenTo) lvalues.emplace_back(); if (_tuple.annotation().willBeWrittenTo) m_currentLValue.emplace(IRLValue{ *_tuple.annotation().type, IRLValue::Tuple{std::move(lvalues)} }); } } return false; } bool IRGeneratorForStatements::visit(Block const& _block) { if (_block.unchecked()) { solAssert(m_context.arithmetic() == Arithmetic::Checked); m_context.setArithmetic(Arithmetic::Wrapping); } return true; } void IRGeneratorForStatements::endVisit(Block const& _block) { if (_block.unchecked()) { solAssert(m_context.arithmetic() == Arithmetic::Wrapping); m_context.setArithmetic(Arithmetic::Checked); } } bool IRGeneratorForStatements::visit(IfStatement const& _ifStatement) { _ifStatement.condition().accept(*this); setLocation(_ifStatement); std::string condition = expressionAsType(_ifStatement.condition(), *TypeProvider::boolean()); if (_ifStatement.falseStatement()) { appendCode() << "switch " << condition << "\n" "case 0 {\n"; _ifStatement.falseStatement()->accept(*this); setLocation(_ifStatement); appendCode() << "}\n" "default {\n"; } else appendCode() << "if " << condition << " {\n"; _ifStatement.trueStatement().accept(*this); setLocation(_ifStatement); appendCode() << "}\n"; return false; } void IRGeneratorForStatements::endVisit(PlaceholderStatement const& _placeholder) { solAssert(m_placeholderCallback); setLocation(_placeholder); appendCode() << m_placeholderCallback(); } bool IRGeneratorForStatements::visit(ForStatement const& _forStatement) { setLocation(_forStatement); generateLoop( _forStatement.body(), _forStatement.condition(), _forStatement.initializationExpression(), _forStatement.loopExpression(), false, // _isDoWhile *_forStatement.annotation().isSimpleCounterLoop ); return false; } bool IRGeneratorForStatements::visit(WhileStatement const& _whileStatement) { setLocation(_whileStatement); generateLoop( _whileStatement.body(), &_whileStatement.condition(), nullptr, nullptr, _whileStatement.isDoWhile() ); return false; } bool IRGeneratorForStatements::visit(Continue const& _continue) { setLocation(_continue); appendCode() << "continue\n"; return false; } bool IRGeneratorForStatements::visit(Break const& _break) { setLocation(_break); appendCode() << "break\n"; return false; } void IRGeneratorForStatements::endVisit(Return const& _return) { setLocation(_return); if (Expression const* value = _return.expression()) { solAssert(_return.annotation().functionReturnParameters, "Invalid return parameters pointer."); std::vector<ASTPointer<VariableDeclaration>> const& returnParameters = _return.annotation().functionReturnParameters->parameters(); if (returnParameters.size() > 1) for (size_t i = 0; i < returnParameters.size(); ++i) assign(m_context.localVariable(*returnParameters[i]), IRVariable(*value).tupleComponent(i)); else if (returnParameters.size() == 1) assign(m_context.localVariable(*returnParameters.front()), *value); } appendCode() << "leave\n"; } bool IRGeneratorForStatements::visit(UnaryOperation const& _unaryOperation) { setLocation(_unaryOperation); FunctionDefinition const* function = *_unaryOperation.annotation().userDefinedFunction; if (function) { _unaryOperation.subExpression().accept(*this); setLocation(_unaryOperation); solAssert(function->isImplemented()); solAssert(function->isFree()); solAssert(function->parameters().size() == 1); solAssert(function->returnParameters().size() == 1); solAssert(*function->returnParameters()[0]->type() == *_unaryOperation.annotation().type); std::string argument = expressionAsType(_unaryOperation.subExpression(), *function->parameters()[0]->type()); solAssert(!argument.empty()); solAssert(_unaryOperation.userDefinedFunctionType()->kind() == FunctionType::Kind::Internal); define(_unaryOperation) << m_context.enqueueFunctionForCodeGeneration(*function) << ("(" + argument + ")\n"); return false; } Type const& resultType = type(_unaryOperation); Token const op = _unaryOperation.getOperator(); if (resultType.category() == Type::Category::RationalNumber) { define(_unaryOperation) << formatNumber(resultType.literalValue(nullptr)) << "\n"; return false; } _unaryOperation.subExpression().accept(*this); setLocation(_unaryOperation); if (op == Token::Delete) { solAssert(!!m_currentLValue, "LValue not retrieved."); std::visit( util::GenericVisitor{ [&](IRLValue::Storage const& _storage) { appendCode() << m_utils.storageSetToZeroFunction(m_currentLValue->type, VariableDeclaration::Location::Unspecified) << "(" << _storage.slot << ", " << _storage.offsetString() << ")\n"; m_currentLValue.reset(); }, [&](IRLValue::TransientStorage const& _transientStorage) { appendCode() << m_utils.storageSetToZeroFunction(m_currentLValue->type, VariableDeclaration::Location::Transient) << "(" << _transientStorage.slot << ", " << _transientStorage.offsetString() << ")\n"; m_currentLValue.reset(); }, [&](auto const&) { IRVariable zeroValue(m_context.newYulVariable(), m_currentLValue->type); define(zeroValue) << m_utils.zeroValueFunction(m_currentLValue->type) << "()\n"; writeToLValue(*m_currentLValue, zeroValue); m_currentLValue.reset(); } }, m_currentLValue->kind ); } else if (resultType.category() == Type::Category::Integer) { solAssert(resultType == type(_unaryOperation.subExpression()), "Result type doesn't match!"); if (op == Token::Inc || op == Token::Dec) { solAssert(!!m_currentLValue, "LValue not retrieved."); IRVariable modifiedValue(m_context.newYulVariable(), resultType); IRVariable originalValue = readFromLValue(*m_currentLValue); bool checked = m_context.arithmetic() == Arithmetic::Checked; define(modifiedValue) << (op == Token::Inc ? (checked ? m_utils.incrementCheckedFunction(resultType) : m_utils.incrementWrappingFunction(resultType)) : (checked ? m_utils.decrementCheckedFunction(resultType) : m_utils.decrementWrappingFunction(resultType)) ) << "(" << originalValue.name() << ")\n"; writeToLValue(*m_currentLValue, modifiedValue); m_currentLValue.reset(); define(_unaryOperation, _unaryOperation.isPrefixOperation() ? modifiedValue : originalValue); } else if (op == Token::BitNot) appendSimpleUnaryOperation(_unaryOperation, _unaryOperation.subExpression()); else if (op == Token::Add) // According to SyntaxChecker... solAssert(false, "Use of unary + is disallowed."); else if (op == Token::Sub) { IntegerType const& intType = *dynamic_cast<IntegerType const*>(&resultType); define(_unaryOperation) << ( m_context.arithmetic() == Arithmetic::Checked ? m_utils.negateNumberCheckedFunction(intType) : m_utils.negateNumberWrappingFunction(intType) ) << "(" << IRVariable(_unaryOperation.subExpression()).name() << ")\n"; } else solUnimplemented("Unary operator not yet implemented"); } else if (resultType.category() == Type::Category::FixedBytes) { solAssert(op == Token::BitNot, "Only bitwise negation is allowed for FixedBytes"); solAssert(resultType == type(_unaryOperation.subExpression()), "Result type doesn't match!"); appendSimpleUnaryOperation(_unaryOperation, _unaryOperation.subExpression()); } else if (resultType.category() == Type::Category::Bool) { solAssert( op != Token::BitNot, "Bitwise Negation can't be done on bool!" ); appendSimpleUnaryOperation(_unaryOperation, _unaryOperation.subExpression()); } else solUnimplemented("Unary operator not yet implemented"); return false; } void IRGeneratorForStatements::endVisit(RevertStatement const& _revertStatement) { ErrorDefinition const* error = dynamic_cast<ErrorDefinition const*>(ASTNode::referencedDeclaration(_revertStatement.errorCall().expression())); solAssert(error); revertWithError( error->functionType(true)->externalSignature(), error->functionType(true)->parameterTypes(), _revertStatement.errorCall().sortedArguments() ); } bool IRGeneratorForStatements::visit(BinaryOperation const& _binOp) { setLocation(_binOp); FunctionDefinition const* function = *_binOp.annotation().userDefinedFunction; if (function) { _binOp.leftExpression().accept(*this); _binOp.rightExpression().accept(*this); setLocation(_binOp); solAssert(function->isImplemented()); solAssert(function->isFree()); solAssert(function->parameters().size() == 2); solAssert(function->returnParameters().size() == 1); solAssert(*function->returnParameters()[0]->type() == *_binOp.annotation().type); std::string left = expressionAsType(_binOp.leftExpression(), *function->parameters()[0]->type()); std::string right = expressionAsType(_binOp.rightExpression(), *function->parameters()[1]->type()); solAssert(!left.empty() && !right.empty()); solAssert(_binOp.userDefinedFunctionType()->kind() == FunctionType::Kind::Internal); define(_binOp) << m_context.enqueueFunctionForCodeGeneration(*function) << ("(" + left + ", " + right + ")\n"); return false; } solAssert(!!_binOp.annotation().commonType); Type const* commonType = _binOp.annotation().commonType; langutil::Token op = _binOp.getOperator(); if (op == Token::And || op == Token::Or) { // This can short-circuit! appendAndOrOperatorCode(_binOp); return false; } if (commonType->category() == Type::Category::RationalNumber) { define(_binOp) << toCompactHexWithPrefix(commonType->literalValue(nullptr)) << "\n"; return false; // skip sub-expressions } _binOp.leftExpression().accept(*this); _binOp.rightExpression().accept(*this); setLocation(_binOp); if (TokenTraits::isCompareOp(op)) { solAssert(commonType->isValueType()); bool isSigned = false; if (auto type = dynamic_cast<IntegerType const*>(commonType)) isSigned = type->isSigned(); std::string args = expressionAsCleanedType(_binOp.leftExpression(), *commonType); args += ", " + expressionAsCleanedType(_binOp.rightExpression(), *commonType); auto functionType = dynamic_cast<FunctionType const*>(commonType); solAssert(functionType ? (op == Token::Equal || op == Token::NotEqual) : true, "Invalid function pointer comparison!"); std::string expr; if (functionType && functionType->kind() == FunctionType::Kind::External) { solUnimplementedAssert(functionType->sizeOnStack() == 2, ""); expr = m_utils.externalFunctionPointersEqualFunction() + "(" + IRVariable{_binOp.leftExpression()}.part("address").name() + "," + IRVariable{_binOp.leftExpression()}.part("functionSelector").name() + "," + IRVariable{_binOp.rightExpression()}.part("address").name() + "," + IRVariable{_binOp.rightExpression()}.part("functionSelector").name() + ")"; if (op == Token::NotEqual) expr = "iszero(" + expr + ")"; } else if (op == Token::Equal) expr = "eq(" + std::move(args) + ")"; else if (op == Token::NotEqual) expr = "iszero(eq(" + std::move(args) + "))"; else if (op == Token::GreaterThanOrEqual) expr = "iszero(" + std::string(isSigned ? "slt(" : "lt(") + std::move(args) + "))"; else if (op == Token::LessThanOrEqual) expr = "iszero(" + std::string(isSigned ? "sgt(" : "gt(") + std::move(args) + "))"; else if (op == Token::GreaterThan) expr = (isSigned ? "sgt(" : "gt(") + std::move(args) + ")"; else if (op == Token::LessThan) expr = (isSigned ? "slt(" : "lt(") + std::move(args) + ")"; else solAssert(false, "Unknown comparison operator."); define(_binOp) << expr << "\n"; } else if (op == Token::Exp) { IRVariable left = convert(_binOp.leftExpression(), *commonType); IRVariable right = convert(_binOp.rightExpression(), *type(_binOp.rightExpression()).mobileType()); if (m_context.arithmetic() == Arithmetic::Wrapping) define(_binOp) << m_utils.wrappingIntExpFunction( dynamic_cast<IntegerType const&>(left.type()), dynamic_cast<IntegerType const&>(right.type()) ) << "(" << left.name() << ", " << right.name() << ")\n"; else if (auto rationalNumberType = dynamic_cast<RationalNumberType const*>(_binOp.leftExpression().annotation().type)) { solAssert(rationalNumberType->integerType(), "Invalid literal as the base for exponentiation."); solAssert(dynamic_cast<IntegerType const*>(commonType)); define(_binOp) << m_utils.overflowCheckedIntLiteralExpFunction( *rationalNumberType, dynamic_cast<IntegerType const&>(right.type()), dynamic_cast<IntegerType const&>(*commonType) ) << "(" << right.name() << ")\n"; } else define(_binOp) << m_utils.overflowCheckedIntExpFunction( dynamic_cast<IntegerType const&>(left.type()), dynamic_cast<IntegerType const&>(right.type()) ) << "(" << left.name() << ", " << right.name() << ")\n"; } else if (TokenTraits::isShiftOp(op)) { IRVariable left = convert(_binOp.leftExpression(), *commonType); IRVariable right = convert(_binOp.rightExpression(), *type(_binOp.rightExpression()).mobileType()); define(_binOp) << shiftOperation(_binOp.getOperator(), left, right) << "\n"; } else { std::string left = expressionAsType(_binOp.leftExpression(), *commonType); std::string right = expressionAsType(_binOp.rightExpression(), *commonType); define(_binOp) << binaryOperation(_binOp.getOperator(), *commonType, left, right) << "\n"; } return false; } void IRGeneratorForStatements::endVisit(FunctionCall const& _functionCall) { setLocation(_functionCall); auto functionCallKind = *_functionCall.annotation().kind; if (functionCallKind == FunctionCallKind::TypeConversion) { solAssert( _functionCall.expression().annotation().type->category() == Type::Category::TypeType, "Expected category to be TypeType" ); solAssert(_functionCall.arguments().size() == 1, "Expected one argument for type conversion"); define(_functionCall, *_functionCall.arguments().front()); return; } FunctionTypePointer functionType = nullptr; if (functionCallKind == FunctionCallKind::StructConstructorCall) { auto const& type = dynamic_cast<TypeType const&>(*_functionCall.expression().annotation().type); auto const& structType = dynamic_cast<StructType const&>(*type.actualType()); functionType = structType.constructorType(); } else functionType = dynamic_cast<FunctionType const*>(_functionCall.expression().annotation().type); TypePointers parameterTypes = functionType->parameterTypes(); std::vector<ASTPointer<Expression const>> const& arguments = _functionCall.sortedArguments(); if (functionCallKind == FunctionCallKind::StructConstructorCall) { TypeType const& type = dynamic_cast<TypeType const&>(*_functionCall.expression().annotation().type); auto const& structType = dynamic_cast<StructType const&>(*type.actualType()); define(_functionCall) << m_utils.allocateMemoryStructFunction(structType) << "()\n"; MemberList::MemberMap members = structType.nativeMembers(nullptr); solAssert(members.size() == arguments.size(), "Struct parameter mismatch."); for (size_t i = 0; i < arguments.size(); i++) { IRVariable converted = convert(*arguments[i], *parameterTypes[i]); appendCode() << m_utils.writeToMemoryFunction(*functionType->parameterTypes()[i]) << "(add(" << IRVariable(_functionCall).part("mpos").name() << ", " << structType.memoryOffsetOfMember(members[i].name) << "), " << converted.commaSeparatedList() << ")\n"; } return; } switch (functionType->kind()) { case FunctionType::Kind::Declaration: solAssert(false, "Attempted to generate code for calling a function definition."); break; case FunctionType::Kind::Internal: { FunctionDefinition const* functionDef = ASTNode::resolveFunctionCall(_functionCall, &m_context.mostDerivedContract()); solAssert(!functionType->takesArbitraryParameters()); std::vector<std::string> args; if (functionType->hasBoundFirstArgument()) args += IRVariable(_functionCall.expression()).part("self").stackSlots(); for (size_t i = 0; i < arguments.size(); ++i) args += convert(*arguments[i], *parameterTypes[i]).stackSlots(); if (functionDef) { solAssert(functionDef->isImplemented()); define(_functionCall) << m_context.enqueueFunctionForCodeGeneration(*functionDef) << "(" << joinHumanReadable(args) << ")\n"; } else { YulArity arity = YulArity::fromType(*functionType); m_context.internalFunctionCalledThroughDispatch(arity); define(_functionCall) << IRNames::internalDispatch(arity) << "(" << IRVariable(_functionCall.expression()).part("functionIdentifier").name() << joinHumanReadablePrefixed(args) << ")\n"; } break; } case FunctionType::Kind::External: case FunctionType::Kind::DelegateCall: appendExternalFunctionCall(_functionCall, arguments); break; case FunctionType::Kind::BareCall: case FunctionType::Kind::BareDelegateCall: case FunctionType::Kind::BareStaticCall: appendBareCall(_functionCall, arguments); break; case FunctionType::Kind::BareCallCode: solAssert(false, "Callcode has been removed."); case FunctionType::Kind::Event: { auto const& event = dynamic_cast<EventDefinition const&>(functionType->declaration()); TypePointers paramTypes = functionType->parameterTypes(); ABIFunctions abi(m_context.evmVersion(), m_context.revertStrings(), m_context.functionCollector()); std::vector<IRVariable> indexedArgs; std::vector<std::string> nonIndexedArgs; TypePointers nonIndexedArgTypes; TypePointers nonIndexedParamTypes; if (!event.isAnonymous()) define(indexedArgs.emplace_back(m_context.newYulVariable(), *TypeProvider::uint256())) << formatNumber(u256(h256::Arith(keccak256(functionType->externalSignature())))) << "\n"; for (size_t i = 0; i < event.parameters().size(); ++i) { Expression const& arg = *arguments[i]; if (event.parameters()[i]->isIndexed()) { std::string value; if (auto const& referenceType = dynamic_cast<ReferenceType const*>(paramTypes[i])) define(indexedArgs.emplace_back(m_context.newYulVariable(), *TypeProvider::uint256())) << m_utils.packedHashFunction({arg.annotation().type}, {referenceType}) << "(" << IRVariable(arg).commaSeparatedList() << ")\n"; else if (auto functionType = dynamic_cast<FunctionType const*>(paramTypes[i])) { solAssert( IRVariable(arg).type() == *functionType && functionType->kind() == FunctionType::Kind::External && !functionType->hasBoundFirstArgument(), "" ); define(indexedArgs.emplace_back(m_context.newYulVariable(), *TypeProvider::fixedBytes(32))) << m_utils.combineExternalFunctionIdFunction() << "(" << IRVariable(arg).commaSeparatedList() << ")\n"; } else { solAssert(parameterTypes[i]->sizeOnStack() == 1, ""); indexedArgs.emplace_back(convertAndCleanup(arg, *parameterTypes[i])); } } else { nonIndexedArgs += IRVariable(arg).stackSlots(); nonIndexedArgTypes.push_back(arg.annotation().type); nonIndexedParamTypes.push_back(paramTypes[i]); } } solAssert(indexedArgs.size() <= 4, "Too many indexed arguments."); Whiskers templ(R"({ let <pos> := <allocateUnbounded>() let <end> := <encode>(<pos> <nonIndexedArgs>) <log>(<pos>, sub(<end>, <pos>) <indexedArgs>) })"); templ("pos", m_context.newYulVariable()); templ("end", m_context.newYulVariable()); templ("allocateUnbounded", m_utils.allocateUnboundedFunction()); templ("encode", abi.tupleEncoder(nonIndexedArgTypes, nonIndexedParamTypes)); templ("nonIndexedArgs", joinHumanReadablePrefixed(nonIndexedArgs)); templ("log", "log" + std::to_string(indexedArgs.size())); templ("indexedArgs", joinHumanReadablePrefixed(indexedArgs | ranges::views::transform([&](auto const& _arg) { return _arg.commaSeparatedList(); }))); appendCode() << templ.render(); break; } case FunctionType::Kind::Wrap: case FunctionType::Kind::Unwrap: { solAssert(arguments.size() == 1); FunctionType::Kind kind = functionType->kind(); if (kind == FunctionType::Kind::Wrap) solAssert( type(*arguments.at(0)).isImplicitlyConvertibleTo( dynamic_cast<UserDefinedValueType const&>(type(_functionCall)).underlyingType() ), "" ); else solAssert(type(*arguments.at(0)).category() == Type::Category::UserDefinedValueType); define(_functionCall, *arguments.at(0)); break; } case FunctionType::Kind::Assert: case FunctionType::Kind::Require: { solAssert(arguments.size() > 0, "Expected at least one parameter for require/assert"); solAssert(arguments.size() <= 2, "Expected no more than two parameters for require/assert"); Type const* messageArgumentType = arguments.size() > 1 && m_context.revertStrings() != RevertStrings::Strip ? arguments[1]->annotation().type : nullptr; auto const* magicType = dynamic_cast<MagicType const*>(messageArgumentType); if (magicType && magicType->kind() == MagicType::Kind::Error) { auto const& errorConstructorCall = dynamic_cast<FunctionCall const&>(*arguments[1]); appendCode() << m_utils.requireWithErrorFunction(errorConstructorCall) << "(" <<IRVariable(*arguments[0]).name(); for (auto argument: errorConstructorCall.arguments()) if (argument->annotation().type->sizeOnStack() > 0) appendCode() << ", " << IRVariable(*argument).commaSeparatedList(); appendCode() << ")\n"; } else { ASTPointer<Expression const> stringArgumentExpression = messageArgumentType ? arguments[1] : nullptr; std::string requireOrAssertFunction = m_utils.requireOrAssertFunction( functionType->kind() == FunctionType::Kind::Assert, messageArgumentType, stringArgumentExpression ); appendCode() << std::move(requireOrAssertFunction) << "(" << IRVariable(*arguments[0]).name(); if (messageArgumentType && messageArgumentType->sizeOnStack() > 0) appendCode() << ", " << IRVariable(*arguments[1]).commaSeparatedList(); appendCode() << ")\n"; } break; } case FunctionType::Kind::ABIEncode: case FunctionType::Kind::ABIEncodePacked: case FunctionType::Kind::ABIEncodeWithSelector: case FunctionType::Kind::ABIEncodeCall: case FunctionType::Kind::ABIEncodeWithSignature: { bool const isPacked = functionType->kind() == FunctionType::Kind::ABIEncodePacked; solAssert(functionType->padArguments() != isPacked); bool const hasSelectorOrSignature = functionType->kind() == FunctionType::Kind::ABIEncodeWithSelector || functionType->kind() == FunctionType::Kind::ABIEncodeCall || functionType->kind() == FunctionType::Kind::ABIEncodeWithSignature; TypePointers argumentTypes; TypePointers targetTypes; std::vector<std::string> argumentVars; std::string selector; std::vector<ASTPointer<Expression const>> argumentsOfEncodeFunction; if (functionType->kind() == FunctionType::Kind::ABIEncodeCall) { solAssert(arguments.size() == 2); // Account for tuples with one component which become that component if (type(*arguments[1]).category() == Type::Category::Tuple) { auto const& tupleExpression = dynamic_cast<TupleExpression const&>(*arguments[1]); for (auto component: tupleExpression.components()) argumentsOfEncodeFunction.push_back(component); } else argumentsOfEncodeFunction.push_back(arguments[1]); } else for (size_t i = 0; i < arguments.size(); ++i) { // ignore selector if (hasSelectorOrSignature && i == 0) continue; argumentsOfEncodeFunction.push_back(arguments[i]); } for (auto const& argument: argumentsOfEncodeFunction) { argumentTypes.emplace_back(&type(*argument)); argumentVars += IRVariable(*argument).stackSlots(); } if (functionType->kind() == FunctionType::Kind::ABIEncodeCall) { auto encodedFunctionType = dynamic_cast<FunctionType const*>(arguments.front()->annotation().type); solAssert(encodedFunctionType); encodedFunctionType = encodedFunctionType->asExternallyCallableFunction(false); solAssert(encodedFunctionType); targetTypes = encodedFunctionType->parameterTypes(); } else for (auto const& argument: argumentsOfEncodeFunction) targetTypes.emplace_back(type(*argument).fullEncodingType(false, true, isPacked)); if (functionType->kind() == FunctionType::Kind::ABIEncodeCall) { auto const& selectorType = dynamic_cast<FunctionType const&>(type(*arguments.front())); if (selectorType.kind() == FunctionType::Kind::Declaration) { solAssert(selectorType.hasDeclaration()); selector = formatNumber(selectorType.externalIdentifier() << (256 - 32)); } else { selector = convert( IRVariable(*arguments[0]).part("functionSelector"), *TypeProvider::fixedBytes(4) ).name(); } } else if (functionType->kind() == FunctionType::Kind::ABIEncodeWithSignature) { // hash the signature Type const& selectorType = type(*arguments.front()); if (auto const* stringType = dynamic_cast<StringLiteralType const*>(&selectorType)) selector = formatNumber(util::selectorFromSignatureU256(stringType->value())); else { // Used to reset the free memory pointer later. // TODO This is an abuse of the `allocateUnbounded` function. // We might want to introduce a new set of memory handling functions here // a la "setMemoryCheckPoint" and "freeUntilCheckPoint". std::string freeMemoryPre = m_context.newYulVariable(); appendCode() << "let " << freeMemoryPre << " := " << m_utils.allocateUnboundedFunction() << "()\n"; IRVariable array = convert(*arguments[0], *TypeProvider::bytesMemory()); IRVariable hashVariable(m_context.newYulVariable(), *TypeProvider::fixedBytes(32)); std::string dataAreaFunction = m_utils.arrayDataAreaFunction(*TypeProvider::bytesMemory()); std::string arrayLengthFunction = m_utils.arrayLengthFunction(*TypeProvider::bytesMemory()); define(hashVariable) << "keccak256(" << (dataAreaFunction + "(" + array.commaSeparatedList() + ")") << ", " << (arrayLengthFunction + "(" + array.commaSeparatedList() +")") << ")\n"; IRVariable selectorVariable(m_context.newYulVariable(), *TypeProvider::fixedBytes(4)); define(selectorVariable, hashVariable); selector = selectorVariable.name(); appendCode() << m_utils.finalizeAllocationFunction() << "(" << freeMemoryPre << ", 0)\n"; } } else if (functionType->kind() == FunctionType::Kind::ABIEncodeWithSelector) selector = convert(*arguments.front(), *TypeProvider::fixedBytes(4)).name(); Whiskers templ(R"( let <data> := <allocateUnbounded>() let <memPtr> := add(<data>, 0x20) <?+selector> mstore(<memPtr>, <selector>) <memPtr> := add(<memPtr>, 4) </+selector> let <mend> := <encode>(<memPtr><arguments>) mstore(<data>, sub(<mend>, add(<data>, 0x20))) <finalizeAllocation>(<data>, sub(<mend>, <data>)) )"); templ("data", IRVariable(_functionCall).part("mpos").name()); templ("allocateUnbounded", m_utils.allocateUnboundedFunction()); templ("memPtr", m_context.newYulVariable()); templ("mend", m_context.newYulVariable()); templ("selector", selector); templ("encode", isPacked ? m_context.abiFunctions().tupleEncoderPacked(argumentTypes, targetTypes) : m_context.abiFunctions().tupleEncoder(argumentTypes, targetTypes, false) ); templ("arguments", joinHumanReadablePrefixed(argumentVars)); templ("finalizeAllocation", m_utils.finalizeAllocationFunction()); appendCode() << templ.render(); break; } case FunctionType::Kind::ABIDecode: { Whiskers templ(R"( <?+retVars>let <retVars> := </+retVars> <abiDecode>(<offset>, add(<offset>, <length>)) )"); Type const* firstArgType = arguments.front()->annotation().type; TypePointers targetTypes; if (TupleType const* targetTupleType = dynamic_cast<TupleType const*>(_functionCall.annotation().type)) targetTypes = targetTupleType->components(); else targetTypes = TypePointers{_functionCall.annotation().type}; if ( auto referenceType = dynamic_cast<ReferenceType const*>(firstArgType); referenceType && referenceType->dataStoredIn(DataLocation::CallData) ) { solAssert(referenceType->isImplicitlyConvertibleTo(*TypeProvider::bytesCalldata())); IRVariable var = convert(*arguments[0], *TypeProvider::bytesCalldata()); templ("abiDecode", m_context.abiFunctions().tupleDecoder(targetTypes, false)); templ("offset", var.part("offset").name()); templ("length", var.part("length").name()); } else { IRVariable var = convert(*arguments[0], *TypeProvider::bytesMemory()); templ("abiDecode", m_context.abiFunctions().tupleDecoder(targetTypes, true)); templ("offset", "add(" + var.part("mpos").name() + ", 32)"); templ("length", m_utils.arrayLengthFunction(*TypeProvider::bytesMemory()) + "(" + var.part("mpos").name() + ")" ); } templ("retVars", IRVariable(_functionCall).commaSeparatedList()); appendCode() << templ.render(); break; } case FunctionType::Kind::Revert: { solAssert(arguments.size() == parameterTypes.size()); solAssert(arguments.size() <= 1); solAssert( arguments.empty() || arguments.front()->annotation().type->isImplicitlyConvertibleTo(*TypeProvider::stringMemory()), ""); if (m_context.revertStrings() == RevertStrings::Strip || arguments.empty()) appendCode() << "revert(0, 0)\n"; else revertWithError( "Error(string)", {TypeProvider::stringMemory()}, {arguments.front()} ); break; } // Array creation using new case FunctionType::Kind::ObjectCreation: { ArrayType const& arrayType = dynamic_cast<ArrayType const&>(*_functionCall.annotation().type); solAssert(arguments.size() == 1); IRVariable value = convert(*arguments[0], *TypeProvider::uint256()); define(_functionCall) << m_utils.allocateAndInitializeMemoryArrayFunction(arrayType) << "(" << value.commaSeparatedList() << ")\n"; break; } case FunctionType::Kind::KECCAK256: { solAssert(arguments.size() == 1); ArrayType const* arrayType = TypeProvider::bytesMemory(); if (auto const* stringLiteral = dynamic_cast<StringLiteralType const*>(arguments.front()->annotation().type)) { // Optimization: Compute keccak256 on string literals at compile-time. define(_functionCall) << ("0x" + keccak256(stringLiteral->value()).hex()) << "\n"; } else { auto array = convert(*arguments[0], *arrayType); std::string dataAreaFunction = m_utils.arrayDataAreaFunction(*arrayType); std::string arrayLengthFunction = m_utils.arrayLengthFunction(*arrayType); define(_functionCall) << "keccak256(" << (dataAreaFunction + "(" + array.commaSeparatedList() + ")") << ", " << (arrayLengthFunction + "(" + array.commaSeparatedList() +")") << ")\n"; } break; } case FunctionType::Kind::ArrayPop: { solAssert(functionType->hasBoundFirstArgument()); solAssert(functionType->parameterTypes().empty()); ArrayType const* arrayType = dynamic_cast<ArrayType const*>(functionType->selfType()); solAssert(arrayType); define(_functionCall) << m_utils.storageArrayPopFunction(*arrayType) << "(" << IRVariable(_functionCall.expression()).commaSeparatedList() << ")\n"; break; } case FunctionType::Kind::ArrayPush: { ArrayType const* arrayType = dynamic_cast<ArrayType const*>(functionType->selfType()); solAssert(arrayType); if (arguments.empty()) { auto slotName = m_context.newYulVariable(); auto offsetName = m_context.newYulVariable(); appendCode() << "let " << slotName << ", " << offsetName << " := " << m_utils.storageArrayPushZeroFunction(*arrayType) << "(" << IRVariable(_functionCall.expression()).commaSeparatedList() << ")\n"; setLValue(_functionCall, IRLValue{ *arrayType->baseType(), IRLValue::Storage{ slotName, offsetName, } }); } else { IRVariable argument = arrayType->baseType()->isValueType() ? convert(*arguments.front(), *arrayType->baseType()) : *arguments.front(); appendCode() << m_utils.storageArrayPushFunction(*arrayType, &argument.type()) << "(" << IRVariable(_functionCall.expression()).commaSeparatedList() << (argument.stackSlots().empty() ? "" : (", " + argument.commaSeparatedList())) << ")\n"; } break; } case FunctionType::Kind::StringConcat: case FunctionType::Kind::BytesConcat: { TypePointers argumentTypes; std::vector<std::string> argumentVars; for (ASTPointer<Expression const> const& argument: arguments) { argumentTypes.emplace_back(&type(*argument)); argumentVars += IRVariable(*argument).stackSlots(); } define(IRVariable(_functionCall)) << m_utils.bytesOrStringConcatFunction(argumentTypes, functionType->kind()) << "(" << joinHumanReadable(argumentVars) << ")\n"; break; } case FunctionType::Kind::Error: case FunctionType::Kind::MetaType: { break; } case FunctionType::Kind::AddMod: case FunctionType::Kind::MulMod: { static std::map<FunctionType::Kind, std::string> functions = { {FunctionType::Kind::AddMod, "addmod"}, {FunctionType::Kind::MulMod, "mulmod"}, }; solAssert(functions.find(functionType->kind()) != functions.end()); solAssert(arguments.size() == 3 && parameterTypes.size() == 3); IRVariable modulus(m_context.newYulVariable(), *(parameterTypes[2])); define(modulus, *arguments[2]); Whiskers templ("if iszero(<modulus>) { <panic>() }\n"); templ("modulus", modulus.name()); templ("panic", m_utils.panicFunction(PanicCode::DivisionByZero)); appendCode() << templ.render(); std::string args; for (size_t i = 0; i < 2; ++i) args += expressionAsType(*arguments[i], *(parameterTypes[i])) + ", "; args += modulus.name(); define(_functionCall) << functions[functionType->kind()] << "(" << args << ")\n"; break; } case FunctionType::Kind::GasLeft: case FunctionType::Kind::Selfdestruct: case FunctionType::Kind::BlockHash: case FunctionType::Kind::BlobHash: { static std::map<FunctionType::Kind, std::string> functions = { {FunctionType::Kind::GasLeft, "gas"}, {FunctionType::Kind::Selfdestruct, "selfdestruct"}, {FunctionType::Kind::BlockHash, "blockhash"}, {FunctionType::Kind::BlobHash, "blobhash"}, }; solAssert(functions.find(functionType->kind()) != functions.end()); std::string args; for (size_t i = 0; i < arguments.size(); ++i) args += (args.empty() ? "" : ", ") + expressionAsType(*arguments[i], *(parameterTypes[i])); define(_functionCall) << functions[functionType->kind()] << "(" << args << ")\n"; break; } case FunctionType::Kind::Creation: { solAssert(!functionType->gasSet(), "Gas limit set for contract creation."); solAssert( functionType->returnParameterTypes().size() == 1, "Constructor should return only one type" ); TypePointers argumentTypes; std::vector<std::string> constructorParams; for (ASTPointer<Expression const> const& arg: arguments) { argumentTypes.push_back(arg->annotation().type); constructorParams += IRVariable{*arg}.stackSlots(); } ContractDefinition const* contract = &dynamic_cast<ContractType const&>(*functionType->returnParameterTypes().front()).contractDefinition(); m_context.addSubObject(contract); Whiskers t(R"( <?eof> let <memPos> := <allocateUnbounded>() let <memEnd> := <abiEncode>(<memPos><constructorParams>) let <address> := eofcreate("<object>", <value>, <salt>, <memPos>, sub(<memEnd>, <memPos>)) <!eof> let <memPos> := <allocateUnbounded>() let <memEnd> := add(<memPos>, datasize("<object>")) if or(gt(<memEnd>, 0xffffffffffffffff), lt(<memEnd>, <memPos>)) { <panic>() } datacopy(<memPos>, dataoffset("<object>"), datasize("<object>")) <memEnd> := <abiEncode>(<memEnd><constructorParams>) <?saltSet> let <address> := create2(<value>, <memPos>, sub(<memEnd>, <memPos>), <salt>) <!saltSet> let <address> := create(<value>, <memPos>, sub(<memEnd>, <memPos>)) </saltSet> </eof> <?isTryCall> let <success> := iszero(iszero(<address>)) <!isTryCall> if iszero(<address>) { <forwardingRevert>() } </isTryCall> )"); t("eof", m_context.eofVersion().has_value()); t("memPos", m_context.newYulVariable()); t("memEnd", m_context.newYulVariable()); t("allocateUnbounded", m_utils.allocateUnboundedFunction()); t("object", IRNames::creationObject(*contract)); t("panic", m_utils.panicFunction(PanicCode::ResourceError)); t("abiEncode", m_context.abiFunctions().tupleEncoder(argumentTypes, functionType->parameterTypes(), false) ); t("constructorParams", joinHumanReadablePrefixed(constructorParams)); t("value", functionType->valueSet() ? IRVariable(_functionCall.expression()).part("value").name() : "0"); t("saltSet", functionType->saltSet()); if (functionType->saltSet()) t("salt", IRVariable(_functionCall.expression()).part("salt").name()); else if (m_context.eofVersion().has_value()) // Set salt to 0 if not defined. t("salt", "0"); // TODO: We should reject non-salted creation during analysis and not set here solAssert(IRVariable(_functionCall).stackSlots().size() == 1); t("address", IRVariable(_functionCall).commaSeparatedList()); t("isTryCall", _functionCall.annotation().tryCall); if (_functionCall.annotation().tryCall) t("success", IRNames::trySuccessConditionVariable(_functionCall)); else t("forwardingRevert", m_utils.forwardingRevertFunction()); appendCode() << t.render(); break; } case FunctionType::Kind::Send: case FunctionType::Kind::Transfer: { solAssert(arguments.size() == 1 && parameterTypes.size() == 1); std::string address{IRVariable(_functionCall.expression()).part("address").name()}; std::string value{expressionAsType(*arguments[0], *(parameterTypes[0]))}; Whiskers templ(R"( let <gas> := 0 if iszero(<value>) { <gas> := <callStipend> } let <success> := call(<gas>, <address>, <value>, 0, 0, 0, 0) <?isTransfer> if iszero(<success>) { <forwardingRevert>() } </isTransfer> )"); templ("gas", m_context.newYulVariable()); templ("callStipend", toString(evmasm::GasCosts::callStipend)); templ("address", address); templ("value", value); if (functionType->kind() == FunctionType::Kind::Transfer) templ("success", m_context.newYulVariable()); else templ("success", IRVariable(_functionCall).commaSeparatedList()); templ("isTransfer", functionType->kind() == FunctionType::Kind::Transfer); templ("forwardingRevert", m_utils.forwardingRevertFunction()); appendCode() << templ.render(); break; } case FunctionType::Kind::ECRecover: case FunctionType::Kind::RIPEMD160: case FunctionType::Kind::SHA256: { solAssert(!_functionCall.annotation().tryCall); solAssert(!functionType->valueSet()); solAssert(!functionType->gasSet()); solAssert(!functionType->hasBoundFirstArgument()); static std::map<FunctionType::Kind, std::tuple<unsigned, size_t>> precompiles = { {FunctionType::Kind::ECRecover, std::make_tuple(1, 0)}, {FunctionType::Kind::SHA256, std::make_tuple(2, 0)}, {FunctionType::Kind::RIPEMD160, std::make_tuple(3, 12)}, }; auto [ address, offset ] = precompiles[functionType->kind()]; TypePointers argumentTypes; std::vector<std::string> argumentStrings; for (auto const& arg: arguments) { argumentTypes.emplace_back(&type(*arg)); argumentStrings += IRVariable(*arg).stackSlots(); } Whiskers templ(R"( let <pos> := <allocateUnbounded>() let <end> := <encodeArgs>(<pos> <argumentString>) <?isECRecover> mstore(0, 0) </isECRecover> let <success> := <call>(<gas>, <address> <?isCall>, 0</isCall>, <pos>, sub(<end>, <pos>), 0, 32) if iszero(<success>) { <forwardingRevert>() } let <retVars> := <shl>(mload(0)) )"); templ("call", m_context.evmVersion().hasStaticCall() ? "staticcall" : "call"); templ("isCall", !m_context.evmVersion().hasStaticCall()); templ("shl", m_utils.shiftLeftFunction(offset * 8)); templ("allocateUnbounded", m_utils.allocateUnboundedFunction()); templ("pos", m_context.newYulVariable()); templ("end", m_context.newYulVariable()); templ("isECRecover", FunctionType::Kind::ECRecover == functionType->kind()); if (FunctionType::Kind::ECRecover == functionType->kind()) templ("encodeArgs", m_context.abiFunctions().tupleEncoder(argumentTypes, parameterTypes)); else templ("encodeArgs", m_context.abiFunctions().tupleEncoderPacked(argumentTypes, parameterTypes)); templ("argumentString", joinHumanReadablePrefixed(argumentStrings)); templ("address", toString(address)); templ("success", m_context.newYulVariable()); templ("retVars", IRVariable(_functionCall).commaSeparatedList()); templ("forwardingRevert", m_utils.forwardingRevertFunction()); if (m_context.evmVersion().canOverchargeGasForCall()) // Send all gas (requires tangerine whistle EVM) templ("gas", "gas()"); else { // @todo The value 10 is not exact and this could be fine-tuned, // but this has worked for years in the old code generator. u256 gasNeededByCaller = evmasm::GasCosts::callGas(m_context.evmVersion()) + 10 + evmasm::GasCosts::callNewAccountGas; templ("gas", "sub(gas(), " + formatNumber(gasNeededByCaller) + ")"); } appendCode() << templ.render(); break; } default: solUnimplemented("FunctionKind " + toString(static_cast<int>(functionType->kind())) + " not yet implemented"); } } void IRGeneratorForStatements::endVisit(FunctionCallOptions const& _options) { setLocation(_options); FunctionType const& previousType = dynamic_cast<FunctionType const&>(*_options.expression().annotation().type); solUnimplementedAssert(!previousType.hasBoundFirstArgument()); // Copy over existing values. for (auto const& item: previousType.stackItems()) define(IRVariable(_options).part(std::get<0>(item)), IRVariable(_options.expression()).part(std::get<0>(item))); for (size_t i = 0; i < _options.names().size(); ++i) { std::string const& name = *_options.names()[i]; solAssert(name == "salt" || name == "gas" || name == "value"); define(IRVariable(_options).part(name), *_options.options()[i]); } } bool IRGeneratorForStatements::visit(MemberAccess const& _memberAccess) { // A shortcut for <address>.code.length. We skip visiting <address>.code and directly visit // <address>. The actual code is generated in endVisit. if ( auto innerExpression = dynamic_cast<MemberAccess const*>(&_memberAccess.expression()); _memberAccess.memberName() == "length" && innerExpression && innerExpression->memberName() == "code" && innerExpression->expression().annotation().type->category() == Type::Category::Address ) { solAssert(innerExpression->annotation().type->category() == Type::Category::Array); // Skip visiting <address>.code innerExpression->expression().accept(*this); return false; } return true; } void IRGeneratorForStatements::endVisit(MemberAccess const& _memberAccess) { setLocation(_memberAccess); ASTString const& member = _memberAccess.memberName(); auto memberFunctionType = dynamic_cast<FunctionType const*>(_memberAccess.annotation().type); Type::Category objectCategory = _memberAccess.expression().annotation().type->category(); if (memberFunctionType && memberFunctionType->hasBoundFirstArgument()) { define(IRVariable(_memberAccess).part("self"), _memberAccess.expression()); solAssert(*_memberAccess.annotation().requiredLookup == VirtualLookup::Static); if (memberFunctionType->kind() == FunctionType::Kind::Internal) assignInternalFunctionIDIfNotCalledDirectly( _memberAccess, dynamic_cast<FunctionDefinition const&>(memberFunctionType->declaration()) ); else if ( memberFunctionType->kind() == FunctionType::Kind::ArrayPush || memberFunctionType->kind() == FunctionType::Kind::ArrayPop ) { // Nothing to do. } else { auto const& functionDefinition = dynamic_cast<FunctionDefinition const&>(memberFunctionType->declaration()); solAssert(memberFunctionType->kind() == FunctionType::Kind::DelegateCall); auto contract = dynamic_cast<ContractDefinition const*>(functionDefinition.scope()); solAssert(contract && contract->isLibrary()); define(IRVariable(_memberAccess).part("address")) << linkerSymbol(*contract) << "\n"; define(IRVariable(_memberAccess).part("functionSelector")) << memberFunctionType->externalIdentifier() << "\n"; } return; } switch (objectCategory) { case Type::Category::Contract: { ContractType const& type = dynamic_cast<ContractType const&>(*_memberAccess.expression().annotation().type); if (type.isSuper()) solAssert(false); // ordinary contract type else if (Declaration const* declaration = _memberAccess.annotation().referencedDeclaration) { u256 identifier; if (auto const* variable = dynamic_cast<VariableDeclaration const*>(declaration)) identifier = FunctionType(*variable).externalIdentifier(); else if (auto const* function = dynamic_cast<FunctionDefinition const*>(declaration)) identifier = FunctionType(*function).externalIdentifier(); else solAssert(false, "Contract member is neither variable nor function."); define(IRVariable(_memberAccess).part("address"), _memberAccess.expression()); define(IRVariable(_memberAccess).part("functionSelector")) << formatNumber(identifier) << "\n"; } else solAssert(false, "Invalid member access in contract"); break; } case Type::Category::Integer: { solAssert(false, "Invalid member access to integer"); break; } case Type::Category::Address: { if (member == "balance") define(_memberAccess) << "balance(" << expressionAsType(_memberAccess.expression(), *TypeProvider::address()) << ")\n"; else if (member == "code") { std::string externalCodeFunction = m_utils.externalCodeFunction(); define(_memberAccess) << externalCodeFunction << "(" << expressionAsType(_memberAccess.expression(), *TypeProvider::address()) << ")\n"; } else if (member == "codehash") define(_memberAccess) << "extcodehash(" << expressionAsType(_memberAccess.expression(), *TypeProvider::address()) << ")\n"; else if (std::set<std::string>{"send", "transfer"}.count(member)) { solAssert(dynamic_cast<AddressType const&>(*_memberAccess.expression().annotation().type).stateMutability() == StateMutability::Payable); define(IRVariable{_memberAccess}.part("address"), _memberAccess.expression()); } else if (std::set<std::string>{"call", "callcode", "delegatecall", "staticcall"}.count(member)) define(IRVariable{_memberAccess}.part("address"), _memberAccess.expression()); else solAssert(false, "Invalid member access to address"); break; } case Type::Category::Function: if (member == "selector") { FunctionType const& functionType = dynamic_cast<FunctionType const&>( *_memberAccess.expression().annotation().type ); if ( functionType.kind() == FunctionType::Kind::External || functionType.kind() == FunctionType::Kind::DelegateCall ) define(IRVariable{_memberAccess}, IRVariable(_memberAccess.expression()).part("functionSelector")); else if ( functionType.kind() == FunctionType::Kind::Declaration || functionType.kind() == FunctionType::Kind::Error || // In some situations, internal function types also provide the "selector" member. // See Types.cpp for details. functionType.kind() == FunctionType::Kind::Internal ) { solAssert(functionType.hasDeclaration()); solAssert( functionType.kind() == FunctionType::Kind::Error || functionType.declaration().isPartOfExternalInterface(), "" ); define(IRVariable{_memberAccess}) << formatNumber( util::selectorFromSignatureU256(functionType.externalSignature()) ) << "\n"; } else if (functionType.kind() == FunctionType::Kind::Event) { solAssert(functionType.hasDeclaration()); solAssert(functionType.kind() == FunctionType::Kind::Event); solAssert( !(dynamic_cast<EventDefinition const&>(functionType.declaration()).isAnonymous()) ); define(IRVariable{_memberAccess}) << formatNumber( u256(h256::Arith(util::keccak256(functionType.externalSignature()))) ) << "\n"; } else solAssert(false, "Invalid use of .selector: " + functionType.toString(false)); } else if (member == "address") { solUnimplementedAssert( dynamic_cast<FunctionType const&>(*_memberAccess.expression().annotation().type).kind() == FunctionType::Kind::External ); define(IRVariable{_memberAccess}, IRVariable(_memberAccess.expression()).part("address")); } else solAssert( !!_memberAccess.expression().annotation().type->memberType(member), "Invalid member access to function." ); break; case Type::Category::Magic: // we can ignore the kind of magic and only look at the name of the member if (member == "coinbase") define(_memberAccess) << "coinbase()\n"; else if (member == "timestamp") define(_memberAccess) << "timestamp()\n"; else if (member == "difficulty" || member == "prevrandao") { if (m_context.evmVersion().hasPrevRandao()) define(_memberAccess) << "prevrandao()\n"; else define(_memberAccess) << "difficulty()\n"; } else if (member == "number") define(_memberAccess) << "number()\n"; else if (member == "gaslimit") define(_memberAccess) << "gaslimit()\n"; else if (member == "sender") define(_memberAccess) << "caller()\n"; else if (member == "value") define(_memberAccess) << "callvalue()\n"; else if (member == "origin") define(_memberAccess) << "origin()\n"; else if (member == "gasprice") define(_memberAccess) << "gasprice()\n"; else if (member == "chainid") define(_memberAccess) << "chainid()\n"; else if (member == "basefee") define(_memberAccess) << "basefee()\n"; else if (member == "blobbasefee") define(_memberAccess) << "blobbasefee()\n"; else if (member == "data") { IRVariable var(_memberAccess); define(var.part("offset")) << "0\n"; define(var.part("length")) << "calldatasize()\n"; } else if (member == "sig") define(_memberAccess) << "and(calldataload(0), " << formatNumber(u256(0xffffffff) << (256 - 32)) << ")\n"; else if (member == "gas") solAssert(false, "Gas has been removed."); else if (member == "blockhash") solAssert(false, "Blockhash has been removed."); else if (member == "creationCode" || member == "runtimeCode") { Type const* arg = dynamic_cast<MagicType const&>(*_memberAccess.expression().annotation().type).typeArgument(); auto const& contractType = dynamic_cast<ContractType const&>(*arg); solAssert(!contractType.isSuper()); ContractDefinition const& contract = contractType.contractDefinition(); m_context.addSubObject(&contract); appendCode() << Whiskers(R"( let <size> := datasize("<objectName>") let <result> := <allocationFunction>(add(<size>, 32)) mstore(<result>, <size>) datacopy(add(<result>, 32), dataoffset("<objectName>"), <size>) )") ("allocationFunction", m_utils.allocationFunction()) ("size", m_context.newYulVariable()) ("objectName", IRNames::creationObject(contract) + (member == "runtimeCode" ? "." + IRNames::deployedObject(contract) : "")) ("result", IRVariable(_memberAccess).commaSeparatedList()).render(); } else if (member == "name") { Type const* arg = dynamic_cast<MagicType const&>(*_memberAccess.expression().annotation().type).typeArgument(); ContractDefinition const& contract = dynamic_cast<ContractType const&>(*arg).contractDefinition(); define(IRVariable(_memberAccess)) << m_utils.copyLiteralToMemoryFunction(contract.name()) << "()\n"; } else if (member == "interfaceId") { Type const* arg = dynamic_cast<MagicType const&>(*_memberAccess.expression().annotation().type).typeArgument(); auto const& contractType = dynamic_cast<ContractType const&>(*arg); solAssert(!contractType.isSuper()); ContractDefinition const& contract = contractType.contractDefinition(); define(_memberAccess) << formatNumber(u256{contract.interfaceId()} << (256 - 32)) << "\n"; } else if (member == "min" || member == "max") { MagicType const* arg = dynamic_cast<MagicType const*>(_memberAccess.expression().annotation().type); std::string requestedValue; if (IntegerType const* integerType = dynamic_cast<IntegerType const*>(arg->typeArgument())) { if (member == "min") requestedValue = formatNumber(integerType->min()); else requestedValue = formatNumber(integerType->max()); } else if (EnumType const* enumType = dynamic_cast<EnumType const*>(arg->typeArgument())) { if (member == "min") requestedValue = std::to_string(enumType->minValue()); else requestedValue = std::to_string(enumType->maxValue()); } else solAssert(false, "min/max requested on unexpected type."); define(_memberAccess) << requestedValue << "\n"; } else if (std::set<std::string>{"encode", "encodePacked", "encodeWithSelector", "encodeCall", "encodeWithSignature", "decode"}.count(member)) { // no-op } else solAssert(false, "Unknown magic member."); break; case Type::Category::Struct: { auto const& structType = dynamic_cast<StructType const&>(*_memberAccess.expression().annotation().type); IRVariable expression(_memberAccess.expression()); switch (structType.location()) { case DataLocation::Storage: { std::pair<u256, unsigned> const& offsets = structType.storageOffsetsOfMember(member); std::string slot = m_context.newYulVariable(); appendCode() << "let " << slot << " := " << ("add(" + expression.part("slot").name() + ", " + offsets.first.str() + ")\n"); setLValue(_memberAccess, IRLValue{ type(_memberAccess), IRLValue::Storage{slot, offsets.second} }); break; } case DataLocation::Memory: { std::string pos = m_context.newYulVariable(); appendCode() << "let " << pos << " := " << ("add(" + expression.part("mpos").name() + ", " + structType.memoryOffsetOfMember(member).str() + ")\n"); setLValue(_memberAccess, IRLValue{ type(_memberAccess), IRLValue::Memory{pos} }); break; } case DataLocation::CallData: { std::string baseRef = expression.part("offset").name(); std::string offset = m_context.newYulVariable(); appendCode() << "let " << offset << " := " << "add(" << baseRef << ", " << std::to_string(structType.calldataOffsetOfMember(member)) << ")\n"; if (_memberAccess.annotation().type->isDynamicallyEncoded()) define(_memberAccess) << m_utils.accessCalldataTailFunction(*_memberAccess.annotation().type) << "(" << baseRef << ", " << offset << ")\n"; else if ( dynamic_cast<ArrayType const*>(_memberAccess.annotation().type) || dynamic_cast<StructType const*>(_memberAccess.annotation().type) ) define(_memberAccess) << offset << "\n"; else define(_memberAccess) << m_utils.readFromCalldata(*_memberAccess.annotation().type) << "(" << offset << ")\n"; break; } default: solAssert(false, "Illegal data location for struct."); } break; } case Type::Category::Enum: { EnumType const& type = dynamic_cast<EnumType const&>(*_memberAccess.expression().annotation().type); define(_memberAccess) << std::to_string(type.memberValue(_memberAccess.memberName())) << "\n"; break; } case Type::Category::Array: { auto const& type = dynamic_cast<ArrayType const&>(*_memberAccess.expression().annotation().type); if (member == "length") { // shortcut for <address>.code.length if ( auto innerExpression = dynamic_cast<MemberAccess const*>(&_memberAccess.expression()); innerExpression && innerExpression->memberName() == "code" && innerExpression->expression().annotation().type->category() == Type::Category::Address ) define(_memberAccess) << "extcodesize(" << expressionAsType(innerExpression->expression(), *TypeProvider::address()) << ")\n"; else define(_memberAccess) << m_utils.arrayLengthFunction(type) << "(" << IRVariable(_memberAccess.expression()).commaSeparatedList() << ")\n"; } else if (member == "pop" || member == "push") { solAssert(type.location() == DataLocation::Storage); define(IRVariable{_memberAccess}.part("slot"), IRVariable{_memberAccess.expression()}.part("slot")); } else solAssert(false, "Invalid array member access."); break; } case Type::Category::FixedBytes: { auto const& type = dynamic_cast<FixedBytesType const&>(*_memberAccess.expression().annotation().type); if (member == "length") define(_memberAccess) << std::to_string(type.numBytes()) << "\n"; else solAssert(false, "Illegal fixed bytes member."); break; } case Type::Category::TypeType: { Type const& actualType = *dynamic_cast<TypeType const&>( *_memberAccess.expression().annotation().type ).actualType(); if (actualType.category() == Type::Category::Contract) { ContractType const& contractType = dynamic_cast<ContractType const&>(actualType); if (contractType.isSuper()) { solAssert(!!_memberAccess.annotation().referencedDeclaration, "Referenced declaration not resolved."); ContractDefinition const* super = contractType.contractDefinition().superContract(m_context.mostDerivedContract()); solAssert(super, "Super contract not available."); FunctionDefinition const& resolvedFunctionDef = dynamic_cast<FunctionDefinition const&>( *_memberAccess.annotation().referencedDeclaration ).resolveVirtual(m_context.mostDerivedContract(), super); solAssert(resolvedFunctionDef.functionType(true)); solAssert(resolvedFunctionDef.functionType(true)->kind() == FunctionType::Kind::Internal); assignInternalFunctionIDIfNotCalledDirectly(_memberAccess, resolvedFunctionDef); } else if (auto const* variable = dynamic_cast<VariableDeclaration const*>(_memberAccess.annotation().referencedDeclaration)) handleVariableReference(*variable, _memberAccess); else if (memberFunctionType) { switch (memberFunctionType->kind()) { case FunctionType::Kind::Declaration: break; case FunctionType::Kind::Internal: if (auto const* function = dynamic_cast<FunctionDefinition const*>(_memberAccess.annotation().referencedDeclaration)) assignInternalFunctionIDIfNotCalledDirectly(_memberAccess, *function); else solAssert(false, "Function not found in member access"); break; case FunctionType::Kind::Event: solAssert( dynamic_cast<EventDefinition const*>(_memberAccess.annotation().referencedDeclaration), "Event not found" ); // the call will do the resolving break; case FunctionType::Kind::Error: solAssert( dynamic_cast<ErrorDefinition const*>(_memberAccess.annotation().referencedDeclaration), "Error not found" ); // The function call will resolve the selector. break; case FunctionType::Kind::DelegateCall: define(IRVariable(_memberAccess).part("address"), _memberAccess.expression()); define(IRVariable(_memberAccess).part("functionSelector")) << formatNumber(memberFunctionType->externalIdentifier()) << "\n"; break; case FunctionType::Kind::External: case FunctionType::Kind::Creation: case FunctionType::Kind::Send: case FunctionType::Kind::BareCall: case FunctionType::Kind::BareCallCode: case FunctionType::Kind::BareDelegateCall: case FunctionType::Kind::BareStaticCall: case FunctionType::Kind::Transfer: case FunctionType::Kind::ECRecover: case FunctionType::Kind::SHA256: case FunctionType::Kind::RIPEMD160: default: solAssert(false, "unsupported member function"); } } else if (dynamic_cast<TypeType const*>(_memberAccess.annotation().type)) { // no-op } else // The old code generator had a generic "else" case here // without any specific code being generated, // but it would still be better to have an exhaustive list. solAssert(false); } else if (EnumType const* enumType = dynamic_cast<EnumType const*>(&actualType)) define(_memberAccess) << std::to_string(enumType->memberValue(_memberAccess.memberName())) << "\n"; else if (dynamic_cast<UserDefinedValueType const*>(&actualType)) solAssert(member == "wrap" || member == "unwrap"); else if (auto const* arrayType = dynamic_cast<ArrayType const*>(&actualType)) solAssert(arrayType->isByteArrayOrString() && member == "concat"); else // The old code generator had a generic "else" case here // without any specific code being generated, // but it would still be better to have an exhaustive list. solAssert(false); break; } case Type::Category::Module: { Type::Category category = _memberAccess.annotation().type->category(); solAssert( dynamic_cast<VariableDeclaration const*>(_memberAccess.annotation().referencedDeclaration) || dynamic_cast<FunctionDefinition const*>(_memberAccess.annotation().referencedDeclaration) || dynamic_cast<ErrorDefinition const*>(_memberAccess.annotation().referencedDeclaration) || category == Type::Category::TypeType || category == Type::Category::Module, "" ); if (auto variable = dynamic_cast<VariableDeclaration const*>(_memberAccess.annotation().referencedDeclaration)) { solAssert(variable->isConstant()); handleVariableReference(*variable, static_cast<Expression const&>(_memberAccess)); } else if (auto const* function = dynamic_cast<FunctionDefinition const*>(_memberAccess.annotation().referencedDeclaration)) { auto funType = dynamic_cast<FunctionType const*>(_memberAccess.annotation().type); solAssert(function && function->isFree()); solAssert(function->functionType(true)); solAssert(function->functionType(true)->kind() == FunctionType::Kind::Internal); solAssert(funType->kind() == FunctionType::Kind::Internal); solAssert(*_memberAccess.annotation().requiredLookup == VirtualLookup::Static); assignInternalFunctionIDIfNotCalledDirectly(_memberAccess, *function); } else if (auto const* contract = dynamic_cast<ContractDefinition const*>(_memberAccess.annotation().referencedDeclaration)) { if (contract->isLibrary()) define(IRVariable(_memberAccess).part("address")) << linkerSymbol(*contract) << "\n"; } break; } default: solAssert(false, "Member access to unknown type."); } } bool IRGeneratorForStatements::visit(InlineAssembly const& _inlineAsm) { setLocation(_inlineAsm); if (*_inlineAsm.annotation().hasMemoryEffects && !_inlineAsm.annotation().markedMemorySafe) m_context.setMemoryUnsafeInlineAssemblySeen(); CopyTranslate bodyCopier{_inlineAsm.dialect(), m_context, _inlineAsm.annotation().externalReferences}; yul::Statement modified = bodyCopier(_inlineAsm.operations().root()); solAssert(std::holds_alternative<yul::Block>(modified)); appendCode() << yul::AsmPrinter(_inlineAsm.dialect())(std::get<yul::Block>(modified)) << "\n"; return false; } void IRGeneratorForStatements::endVisit(IndexAccess const& _indexAccess) { setLocation(_indexAccess); Type const& baseType = *_indexAccess.baseExpression().annotation().type; if (baseType.category() == Type::Category::Mapping) { solAssert(_indexAccess.indexExpression(), "Index expression expected."); MappingType const& mappingType = dynamic_cast<MappingType const&>(baseType); Type const& keyType = *_indexAccess.indexExpression()->annotation().type; std::string slot = m_context.newYulVariable(); Whiskers templ("let <slot> := <indexAccess>(<base><?+key>,<key></+key>)\n"); templ("slot", slot); templ("indexAccess", m_utils.mappingIndexAccessFunction(mappingType, keyType)); templ("base", IRVariable(_indexAccess.baseExpression()).commaSeparatedList()); templ("key", IRVariable(*_indexAccess.indexExpression()).commaSeparatedList()); appendCode() << templ.render(); setLValue(_indexAccess, IRLValue{ *_indexAccess.annotation().type, IRLValue::Storage{ slot, 0u } }); } else if (baseType.category() == Type::Category::Array || baseType.category() == Type::Category::ArraySlice) { ArrayType const& arrayType = baseType.category() == Type::Category::Array ? dynamic_cast<ArrayType const&>(baseType) : dynamic_cast<ArraySliceType const&>(baseType).arrayType(); if (baseType.category() == Type::Category::ArraySlice) solAssert(arrayType.dataStoredIn(DataLocation::CallData) && arrayType.isDynamicallySized()); solAssert(_indexAccess.indexExpression(), "Index expression expected."); switch (arrayType.location()) { case DataLocation::Storage: { std::string slot = m_context.newYulVariable(); std::string offset = m_context.newYulVariable(); appendCode() << Whiskers(R"( let <slot>, <offset> := <indexFunc>(<array>, <index>) )") ("slot", slot) ("offset", offset) ("indexFunc", m_utils.storageArrayIndexAccessFunction(arrayType)) ("array", IRVariable(_indexAccess.baseExpression()).part("slot").name()) ("index", IRVariable(*_indexAccess.indexExpression()).name()) .render(); setLValue(_indexAccess, IRLValue{ *_indexAccess.annotation().type, IRLValue::Storage{slot, offset} }); break; } case DataLocation::Transient: solUnimplemented("Transient data location is only supported for value types."); break; case DataLocation::Memory: { std::string const indexAccessFunction = m_utils.memoryArrayIndexAccessFunction(arrayType); std::string const baseRef = IRVariable(_indexAccess.baseExpression()).part("mpos").name(); std::string const indexExpression = expressionAsType( *_indexAccess.indexExpression(), *TypeProvider::uint256() ); std::string const memAddress = indexAccessFunction + "(" + baseRef + ", " + indexExpression + ")"; setLValue(_indexAccess, IRLValue{ *arrayType.baseType(), IRLValue::Memory{memAddress, arrayType.isByteArrayOrString()} }); break; } case DataLocation::CallData: { std::string const indexAccessFunction = m_utils.calldataArrayIndexAccessFunction(arrayType); std::string const baseRef = IRVariable(_indexAccess.baseExpression()).commaSeparatedList(); std::string const indexExpression = expressionAsType( *_indexAccess.indexExpression(), *TypeProvider::uint256() ); std::string const calldataAddress = indexAccessFunction + "(" + baseRef + ", " + indexExpression + ")"; if (arrayType.isByteArrayOrString()) define(_indexAccess) << m_utils.cleanupFunction(*arrayType.baseType()) << "(calldataload(" << calldataAddress << "))\n"; else if (arrayType.baseType()->isValueType()) define(_indexAccess) << m_utils.readFromCalldata(*arrayType.baseType()) << "(" << calldataAddress << ")\n"; else define(_indexAccess) << calldataAddress << "\n"; break; } } } else if (baseType.category() == Type::Category::FixedBytes) { auto const& fixedBytesType = dynamic_cast<FixedBytesType const&>(baseType); solAssert(_indexAccess.indexExpression(), "Index expression expected."); IRVariable index{m_context.newYulVariable(), *TypeProvider::uint256()}; define(index, *_indexAccess.indexExpression()); appendCode() << Whiskers(R"( if iszero(lt(<index>, <length>)) { <panic>() } let <result> := <shl248>(byte(<index>, <array>)) )") ("index", index.name()) ("length", std::to_string(fixedBytesType.numBytes())) ("panic", m_utils.panicFunction(PanicCode::ArrayOutOfBounds)) ("array", IRVariable(_indexAccess.baseExpression()).name()) ("shl248", m_utils.shiftLeftFunction(256 - 8)) ("result", IRVariable(_indexAccess).name()) .render(); } else if (baseType.category() == Type::Category::TypeType) { solAssert(baseType.sizeOnStack() == 0); solAssert(_indexAccess.annotation().type->sizeOnStack() == 0); // no-op - this seems to be a lone array type (`structType[];`) } else solAssert(false, "Index access only allowed for mappings or arrays."); } void IRGeneratorForStatements::endVisit(IndexRangeAccess const& _indexRangeAccess) { setLocation(_indexRangeAccess); Type const& baseType = *_indexRangeAccess.baseExpression().annotation().type; solAssert( baseType.category() == Type::Category::Array || baseType.category() == Type::Category::ArraySlice, "Index range accesses is available only on arrays and array slices." ); ArrayType const& arrayType = baseType.category() == Type::Category::Array ? dynamic_cast<ArrayType const &>(baseType) : dynamic_cast<ArraySliceType const &>(baseType).arrayType(); switch (arrayType.location()) { case DataLocation::CallData: { solAssert(baseType.isDynamicallySized()); IRVariable sliceStart{m_context.newYulVariable(), *TypeProvider::uint256()}; if (_indexRangeAccess.startExpression()) define(sliceStart, IRVariable{*_indexRangeAccess.startExpression()}); else define(sliceStart) << u256(0) << "\n"; IRVariable sliceEnd{ m_context.newYulVariable(), *TypeProvider::uint256() }; if (_indexRangeAccess.endExpression()) define(sliceEnd, IRVariable{*_indexRangeAccess.endExpression()}); else define(sliceEnd, IRVariable{_indexRangeAccess.baseExpression()}.part("length")); IRVariable range{_indexRangeAccess}; define(range) << m_utils.calldataArrayIndexRangeAccess(arrayType) << "(" << IRVariable{_indexRangeAccess.baseExpression()}.commaSeparatedList() << ", " << sliceStart.name() << ", " << sliceEnd.name() << ")\n"; break; } default: solUnimplemented("Index range accesses is implemented only on calldata arrays."); } } void IRGeneratorForStatements::endVisit(Identifier const& _identifier) { setLocation(_identifier); Declaration const* declaration = _identifier.annotation().referencedDeclaration; if (MagicVariableDeclaration const* magicVar = dynamic_cast<MagicVariableDeclaration const*>(declaration)) { switch (magicVar->type()->category()) { case Type::Category::Contract: solAssert(_identifier.name() == "this"); define(_identifier) << "address()\n"; break; case Type::Category::Integer: solAssert(_identifier.name() == "now"); define(_identifier) << "timestamp()\n"; break; case Type::Category::TypeType: { auto typeType = dynamic_cast<TypeType const*>(magicVar->type()); if (auto contractType = dynamic_cast<ContractType const*>(typeType->actualType())) solAssert(!contractType->isSuper() || _identifier.name() == "super"); break; } default: break; } return; } else if (FunctionDefinition const* functionDef = dynamic_cast<FunctionDefinition const*>(declaration)) { solAssert(*_identifier.annotation().requiredLookup == VirtualLookup::Virtual); FunctionDefinition const& resolvedFunctionDef = functionDef->resolveVirtual(m_context.mostDerivedContract()); solAssert(resolvedFunctionDef.functionType(true)); solAssert(resolvedFunctionDef.functionType(true)->kind() == FunctionType::Kind::Internal); assignInternalFunctionIDIfNotCalledDirectly(_identifier, resolvedFunctionDef); } else if (VariableDeclaration const* varDecl = dynamic_cast<VariableDeclaration const*>(declaration)) handleVariableReference(*varDecl, _identifier); else if (auto const* contract = dynamic_cast<ContractDefinition const*>(declaration)) { if (contract->isLibrary()) define(IRVariable(_identifier).part("address")) << linkerSymbol(*contract) << "\n"; } else if (dynamic_cast<EventDefinition const*>(declaration)) { // no-op } else if (dynamic_cast<ErrorDefinition const*>(declaration)) { // no-op } else if (dynamic_cast<EnumDefinition const*>(declaration)) { // no-op } else if (dynamic_cast<StructDefinition const*>(declaration)) { // no-op } else if (dynamic_cast<ImportDirective const*>(declaration)) { // no-op } else if (dynamic_cast<UserDefinedValueTypeDefinition const*>(declaration)) { // no-op } else { solAssert(false, "Identifier type not expected in expression context."); } } bool IRGeneratorForStatements::visit(Literal const& _literal) { setLocation(_literal); Type const& literalType = type(_literal); switch (literalType.category()) { case Type::Category::RationalNumber: case Type::Category::Bool: case Type::Category::Address: define(_literal) << toCompactHexWithPrefix(literalType.literalValue(&_literal)) << "\n"; break; case Type::Category::StringLiteral: break; // will be done during conversion default: solUnimplemented("Only integer, boolean and string literals implemented for now."); } return false; } void IRGeneratorForStatements::handleVariableReference( VariableDeclaration const& _variable, Expression const& _referencingExpression ) { if ((_variable.isStateVariable() || _variable.isFileLevelVariable()) && _variable.isConstant()) define(_referencingExpression) << constantValueFunction(_variable) << "()\n"; else if (_variable.isStateVariable() && _variable.immutable()) setLValue(_referencingExpression, IRLValue{ *_variable.annotation().type, IRLValue::Immutable{&_variable} }); else if (m_context.isLocalVariable(_variable)) setLValue(_referencingExpression, IRLValue{ *_variable.annotation().type, IRLValue::Stack{m_context.localVariable(_variable)} }); else if (m_context.isStateVariable(_variable) && _variable.referenceLocation() == VariableDeclaration::Location::Transient) setLValue(_referencingExpression, IRLValue{ *_variable.annotation().type, IRLValue::TransientStorage{ toCompactHexWithPrefix(m_context.storageLocationOfStateVariable(_variable).first), m_context.storageLocationOfStateVariable(_variable).second } }); else if (m_context.isStateVariable(_variable)) { solAssert(_variable.referenceLocation() == VariableDeclaration::Location::Unspecified, "Must have storage location."); setLValue(_referencingExpression, IRLValue{ *_variable.annotation().type, IRLValue::Storage{ toCompactHexWithPrefix(m_context.storageLocationOfStateVariable(_variable).first), m_context.storageLocationOfStateVariable(_variable).second } }); } else solAssert(false, "Invalid variable kind."); } void IRGeneratorForStatements::appendExternalFunctionCall( FunctionCall const& _functionCall, std::vector<ASTPointer<Expression const>> const& _arguments ) { FunctionType const& funType = dynamic_cast<FunctionType const&>(type(_functionCall.expression())); solAssert(!funType.takesArbitraryParameters()); solAssert(_arguments.size() == funType.parameterTypes().size()); solAssert(!funType.isBareCall()); FunctionType::Kind const funKind = funType.kind(); solAssert( funKind == FunctionType::Kind::External || funKind == FunctionType::Kind::DelegateCall, "Can only be used for regular external calls." ); bool const isDelegateCall = funKind == FunctionType::Kind::DelegateCall; bool const useStaticCall = funType.stateMutability() <= StateMutability::View && m_context.evmVersion().hasStaticCall(); ReturnInfo const returnInfo{m_context.evmVersion(), funType}; TypePointers parameterTypes = funType.parameterTypes(); TypePointers argumentTypes; std::vector<std::string> argumentStrings; if (funType.hasBoundFirstArgument()) { parameterTypes.insert(parameterTypes.begin(), funType.selfType()); argumentTypes.emplace_back(funType.selfType()); argumentStrings += IRVariable(_functionCall.expression()).part("self").stackSlots(); } for (auto const& arg: _arguments) { argumentTypes.emplace_back(&type(*arg)); argumentStrings += IRVariable(*arg).stackSlots(); } if (!m_context.evmVersion().canOverchargeGasForCall()) { // Touch the end of the output area so that we do not pay for memory resize during the call // (which we would have to subtract from the gas left) // We could also just use MLOAD; POP right before the gas calculation, but the optimizer // would remove that, so we use MSTORE here. if (!funType.gasSet() && returnInfo.estimatedReturnSize > 0) appendCode() << "mstore(add(" << m_utils.allocateUnboundedFunction() << "() , " << std::to_string(returnInfo.estimatedReturnSize) << "), 0)\n"; } // NOTE: When the expected size of returndata is static, we pass that in to the call opcode and it gets copied automatically. // When it's dynamic, we get zero from estimatedReturnSize() instead and then we need an explicit returndatacopy(). Whiskers templ(R"( <?checkExtcodesize> if iszero(extcodesize(<address>)) { <revertNoCode>() } </checkExtcodesize> // storage for arguments and returned data let <pos> := <allocateUnbounded>() mstore(<pos>, <shl28>(<funSel>)) let <end> := <encodeArgs>(add(<pos>, 4) <argumentString>) let <success> := <call>(<gas>, <address>, <?hasValue> <value>, </hasValue> <pos>, sub(<end>, <pos>), <pos>, <staticReturndataSize>) <?noTryCall> if iszero(<success>) { <forwardingRevert>() } </noTryCall> <?+retVars> let <retVars> </+retVars> if <success> { <?isReturndataSizeDynamic> let <returnDataSizeVar> := returndatasize() returndatacopy(<pos>, 0, <returnDataSizeVar>) <!isReturndataSizeDynamic> let <returnDataSizeVar> := <staticReturndataSize> <?supportsReturnData> if gt(<returnDataSizeVar>, returndatasize()) { <returnDataSizeVar> := returndatasize() } </supportsReturnData> </isReturndataSizeDynamic> // update freeMemoryPointer according to dynamic return size <finalizeAllocation>(<pos>, <returnDataSizeVar>) // decode return parameters from external try-call into retVars <?+retVars> <retVars> := </+retVars> <abiDecode>(<pos>, add(<pos>, <returnDataSizeVar>)) } )"); templ("revertNoCode", m_utils.revertReasonIfDebugFunction("Target contract does not contain code")); // We do not need to check extcodesize if we expect return data: If there is no // code, the call will return empty data and the ABI decoder will revert. size_t encodedHeadSize = 0; for (auto const& t: returnInfo.returnTypes) encodedHeadSize += t->decodingType()->calldataHeadSize(); bool const checkExtcodesize = encodedHeadSize == 0 || !m_context.evmVersion().supportsReturndata() || m_context.revertStrings() >= RevertStrings::Debug; templ("checkExtcodesize", checkExtcodesize); templ("pos", m_context.newYulVariable()); templ("end", m_context.newYulVariable()); if (_functionCall.annotation().tryCall) templ("success", IRNames::trySuccessConditionVariable(_functionCall)); else templ("success", m_context.newYulVariable()); templ("allocateUnbounded", m_utils.allocateUnboundedFunction()); templ("finalizeAllocation", m_utils.finalizeAllocationFunction()); templ("shl28", m_utils.shiftLeftFunction(8 * (32 - 4))); templ("funSel", IRVariable(_functionCall.expression()).part("functionSelector").name()); templ("address", IRVariable(_functionCall.expression()).part("address").name()); if (returnInfo.dynamicReturnSize) solAssert(m_context.evmVersion().supportsReturndata()); templ("returnDataSizeVar", m_context.newYulVariable()); templ("staticReturndataSize", std::to_string(returnInfo.estimatedReturnSize)); templ("supportsReturnData", m_context.evmVersion().supportsReturndata()); std::string const retVars = IRVariable(_functionCall).commaSeparatedList(); templ("retVars", retVars); solAssert(retVars.empty() == returnInfo.returnTypes.empty()); templ("abiDecode", m_context.abiFunctions().tupleDecoder(returnInfo.returnTypes, true)); templ("isReturndataSizeDynamic", returnInfo.dynamicReturnSize); templ("noTryCall", !_functionCall.annotation().tryCall); bool encodeForLibraryCall = funKind == FunctionType::Kind::DelegateCall; solAssert(funType.padArguments()); templ("encodeArgs", m_context.abiFunctions().tupleEncoder(argumentTypes, parameterTypes, encodeForLibraryCall)); templ("argumentString", joinHumanReadablePrefixed(argumentStrings)); solAssert(!isDelegateCall || !funType.valueSet(), "Value set for delegatecall"); solAssert(!useStaticCall || !funType.valueSet(), "Value set for staticcall"); templ("hasValue", !isDelegateCall && !useStaticCall); templ("value", funType.valueSet() ? IRVariable(_functionCall.expression()).part("value").name() : "0"); if (funType.gasSet()) templ("gas", IRVariable(_functionCall.expression()).part("gas").name()); else if (m_context.evmVersion().canOverchargeGasForCall()) // Send all gas (requires tangerine whistle EVM) templ("gas", "gas()"); else { // send all gas except the amount needed to execute "SUB" and "CALL" // @todo this retains too much gas for now, needs to be fine-tuned. u256 gasNeededByCaller = evmasm::GasCosts::callGas(m_context.evmVersion()) + 10; if (funType.valueSet()) gasNeededByCaller += evmasm::GasCosts::callValueTransferGas; if (!checkExtcodesize) gasNeededByCaller += evmasm::GasCosts::callNewAccountGas; // we never know templ("gas", "sub(gas(), " + formatNumber(gasNeededByCaller) + ")"); } // Order is important here, STATICCALL might overlap with DELEGATECALL. if (isDelegateCall) templ("call", "delegatecall"); else if (useStaticCall) templ("call", "staticcall"); else templ("call", "call"); templ("forwardingRevert", m_utils.forwardingRevertFunction()); appendCode() << templ.render(); } void IRGeneratorForStatements::appendBareCall( FunctionCall const& _functionCall, std::vector<ASTPointer<Expression const>> const& _arguments ) { FunctionType const& funType = dynamic_cast<FunctionType const&>(type(_functionCall.expression())); solAssert( !funType.hasBoundFirstArgument() && !funType.takesArbitraryParameters() && _arguments.size() == 1 && funType.parameterTypes().size() == 1, "" ); FunctionType::Kind const funKind = funType.kind(); solAssert(funKind != FunctionType::Kind::BareStaticCall || m_context.evmVersion().hasStaticCall()); solAssert(funKind != FunctionType::Kind::BareCallCode, "Callcode has been removed."); solAssert( funKind == FunctionType::Kind::BareCall || funKind == FunctionType::Kind::BareDelegateCall || funKind == FunctionType::Kind::BareStaticCall, "" ); solAssert(!_functionCall.annotation().tryCall); Whiskers templ(R"( <?needsEncoding> let <pos> := <allocateUnbounded>() let <length> := sub(<encode>(<pos> <?+arg>,</+arg> <arg>), <pos>) <!needsEncoding> let <pos> := add(<arg>, 0x20) let <length> := mload(<arg>) </needsEncoding> let <success> := <call>(<gas>, <address>, <?+value> <value>, </+value> <pos>, <length>, 0, 0) let <returndataVar> := <extractReturndataFunction>() )"); templ("allocateUnbounded", m_utils.allocateUnboundedFunction()); templ("pos", m_context.newYulVariable()); templ("length", m_context.newYulVariable()); templ("arg", IRVariable(*_arguments.front()).commaSeparatedList()); Type const& argType = type(*_arguments.front()); if (argType == *TypeProvider::bytesMemory() || argType == *TypeProvider::stringMemory()) templ("needsEncoding", false); else { templ("needsEncoding", true); ABIFunctions abi(m_context.evmVersion(), m_context.revertStrings(), m_context.functionCollector()); templ("encode", abi.tupleEncoderPacked({&argType}, {TypeProvider::bytesMemory()})); } templ("success", IRVariable(_functionCall).tupleComponent(0).name()); templ("returndataVar", IRVariable(_functionCall).tupleComponent(1).commaSeparatedList()); templ("extractReturndataFunction", m_utils.extractReturndataFunction()); templ("address", IRVariable(_functionCall.expression()).part("address").name()); if (funKind == FunctionType::Kind::BareCall) { templ("value", funType.valueSet() ? IRVariable(_functionCall.expression()).part("value").name() : "0"); templ("call", "call"); } else { solAssert(!funType.valueSet(), "Value set for delegatecall or staticcall."); templ("value", ""); if (funKind == FunctionType::Kind::BareStaticCall) templ("call", "staticcall"); else templ("call", "delegatecall"); } if (funType.gasSet()) templ("gas", IRVariable(_functionCall.expression()).part("gas").name()); else if (m_context.evmVersion().canOverchargeGasForCall()) // Send all gas (requires tangerine whistle EVM) templ("gas", "gas()"); else { // send all gas except the amount needed to execute "SUB" and "CALL" // @todo this retains too much gas for now, needs to be fine-tuned. u256 gasNeededByCaller = evmasm::GasCosts::callGas(m_context.evmVersion()) + 10; if (funType.valueSet()) gasNeededByCaller += evmasm::GasCosts::callValueTransferGas; gasNeededByCaller += evmasm::GasCosts::callNewAccountGas; // we never know templ("gas", "sub(gas(), " + formatNumber(gasNeededByCaller) + ")"); } appendCode() << templ.render(); } void IRGeneratorForStatements::assignInternalFunctionIDIfNotCalledDirectly( Expression const& _expression, FunctionDefinition const& _referencedFunction ) { solAssert( dynamic_cast<MemberAccess const*>(&_expression) || dynamic_cast<Identifier const*>(&_expression), "" ); if (_expression.annotation().calledDirectly) return; define(IRVariable(_expression).part("functionIdentifier")) << std::to_string(m_context.mostDerivedContract().annotation().internalFunctionIDs.at(&_referencedFunction)) << "\n"; m_context.addToInternalDispatch(_referencedFunction); } IRVariable IRGeneratorForStatements::convert(IRVariable const& _from, Type const& _to) { if (_from.type() == _to) return _from; else { IRVariable converted(m_context.newYulVariable(), _to); define(converted, _from); return converted; } } IRVariable IRGeneratorForStatements::convertAndCleanup(IRVariable const& _from, Type const& _to) { IRVariable converted(m_context.newYulVariable(), _to); defineAndCleanup(converted, _from); return converted; } std::string IRGeneratorForStatements::expressionAsType(Expression const& _expression, Type const& _to) { IRVariable from(_expression); if (from.type() == _to) return from.commaSeparatedList(); else return m_utils.conversionFunction(from.type(), _to) + "(" + from.commaSeparatedList() + ")"; } std::string IRGeneratorForStatements::expressionAsCleanedType(Expression const& _expression, Type const& _to) { IRVariable from(_expression); if (from.type() == _to) return m_utils.cleanupFunction(_to) + "(" + expressionAsType(_expression, _to) + ")"; else return expressionAsType(_expression, _to) ; } std::ostream& IRGeneratorForStatements::define(IRVariable const& _var) { if (_var.type().sizeOnStack() > 0) appendCode() << "let " << _var.commaSeparatedList() << " := "; return appendCode(false); } void IRGeneratorForStatements::declare(IRVariable const& _var) { if (_var.type().sizeOnStack() > 0) appendCode() << "let " << _var.commaSeparatedList() << "\n"; } void IRGeneratorForStatements::declareAssign(IRVariable const& _lhs, IRVariable const& _rhs, bool _declare, bool _forceCleanup) { std::string output; if (_lhs.type() == _rhs.type() && !_forceCleanup) for (auto const& [stackItemName, stackItemType]: _lhs.type().stackItems()) if (stackItemType) declareAssign(_lhs.part(stackItemName), _rhs.part(stackItemName), _declare); else appendCode() << (_declare ? "let ": "") << _lhs.part(stackItemName).name() << " := " << _rhs.part(stackItemName).name() << "\n"; else { if (_lhs.type().sizeOnStack() > 0) appendCode() << (_declare ? "let ": "") << _lhs.commaSeparatedList() << " := "; appendCode() << m_context.utils().conversionFunction(_rhs.type(), _lhs.type()) << "(" << _rhs.commaSeparatedList() << ")\n"; } } IRVariable IRGeneratorForStatements::zeroValue(Type const& _type, bool _splitFunctionTypes) { IRVariable irVar{IRNames::zeroValue(_type, m_context.newYulVariable()), _type}; define(irVar) << m_utils.zeroValueFunction(_type, _splitFunctionTypes) << "()\n"; return irVar; } void IRGeneratorForStatements::appendSimpleUnaryOperation(UnaryOperation const& _operation, Expression const& _expr) { std::string func; if (_operation.getOperator() == Token::Not) func = "iszero"; else if (_operation.getOperator() == Token::BitNot) func = "not"; else solAssert(false, "Invalid Token!"); define(_operation) << m_utils.cleanupFunction(type(_expr)) << "(" << func << "(" << IRVariable(_expr).commaSeparatedList() << ")" << ")\n"; } std::string IRGeneratorForStatements::binaryOperation( langutil::Token _operator, Type const& _type, std::string const& _left, std::string const& _right ) { solAssert( !TokenTraits::isShiftOp(_operator), "Have to use specific shift operation function for shifts." ); std::string fun; if (TokenTraits::isBitOp(_operator)) { solAssert( _type.category() == Type::Category::Integer || _type.category() == Type::Category::FixedBytes, "" ); switch (_operator) { case Token::BitOr: fun = "or"; break; case Token::BitXor: fun = "xor"; break; case Token::BitAnd: fun = "and"; break; default: break; } } else if (TokenTraits::isArithmeticOp(_operator)) { solUnimplementedAssert( _type.category() != Type::Category::FixedPoint, "Not yet implemented - FixedPointType." ); IntegerType const* type = dynamic_cast<IntegerType const*>(&_type); solAssert(type); bool checked = m_context.arithmetic() == Arithmetic::Checked; switch (_operator) { case Token::Add: fun = checked ? m_utils.overflowCheckedIntAddFunction(*type) : m_utils.wrappingIntAddFunction(*type); break; case Token::Sub: fun = checked ? m_utils.overflowCheckedIntSubFunction(*type) : m_utils.wrappingIntSubFunction(*type); break; case Token::Mul: fun = checked ? m_utils.overflowCheckedIntMulFunction(*type) : m_utils.wrappingIntMulFunction(*type); break; case Token::Div: fun = checked ? m_utils.overflowCheckedIntDivFunction(*type) : m_utils.wrappingIntDivFunction(*type); break; case Token::Mod: fun = m_utils.intModFunction(*type); break; default: break; } } solUnimplementedAssert(!fun.empty(), "Type: " + _type.toString()); return fun + "(" + _left + ", " + _right + ")\n"; } std::string IRGeneratorForStatements::shiftOperation( langutil::Token _operator, IRVariable const& _value, IRVariable const& _amountToShift ) { solUnimplementedAssert( _amountToShift.type().category() != Type::Category::FixedPoint && _value.type().category() != Type::Category::FixedPoint, "Not yet implemented - FixedPointType." ); IntegerType const* amountType = dynamic_cast<IntegerType const*>(&_amountToShift.type()); solAssert(amountType); solAssert(_operator == Token::SHL || _operator == Token::SAR); return Whiskers(R"( <shift>(<value>, <amount>) )") ("shift", _operator == Token::SHL ? m_utils.typedShiftLeftFunction(_value.type(), *amountType) : m_utils.typedShiftRightFunction(_value.type(), *amountType) ) ("value", _value.name()) ("amount", _amountToShift.name()) .render(); } void IRGeneratorForStatements::appendAndOrOperatorCode(BinaryOperation const& _binOp) { langutil::Token const op = _binOp.getOperator(); solAssert(op == Token::Or || op == Token::And); _binOp.leftExpression().accept(*this); setLocation(_binOp); IRVariable value(_binOp); define(value, _binOp.leftExpression()); if (op == Token::Or) appendCode() << "if iszero(" << value.name() << ") {\n"; else appendCode() << "if " << value.name() << " {\n"; _binOp.rightExpression().accept(*this); setLocation(_binOp); assign(value, _binOp.rightExpression()); appendCode() << "}\n"; } void IRGeneratorForStatements::writeToLValue(IRLValue const& _lvalue, IRVariable const& _value) { std::visit( util::GenericVisitor{ [&](IRLValue::Storage const& _storage) { std::string offsetArgument; std::optional<unsigned> offsetStatic; std::visit(GenericVisitor{ [&](unsigned _offset) { offsetStatic = _offset; }, [&](std::string const& _offset) { offsetArgument = ", " + _offset; } }, _storage.offset); appendCode() << m_utils.updateStorageValueFunction(_value.type(), _lvalue.type, VariableDeclaration::Location::Unspecified, offsetStatic) << "(" << _storage.slot << offsetArgument << _value.commaSeparatedListPrefixed() << ")\n"; }, [&](IRLValue::TransientStorage const& _transientStorage) { std::string offsetArgument; std::optional<unsigned> offsetStatic; std::visit(GenericVisitor{ [&](unsigned _offset) { offsetStatic = _offset; }, [&](std::string const& _offset) { offsetArgument = ", " + _offset; } }, _transientStorage.offset); appendCode() << m_utils.updateStorageValueFunction(_value.type(), _lvalue.type, VariableDeclaration::Location::Transient, offsetStatic) << "(" << _transientStorage.slot << offsetArgument << _value.commaSeparatedListPrefixed() << ")\n"; }, [&](IRLValue::Memory const& _memory) { if (_lvalue.type.isValueType()) { IRVariable prepared(m_context.newYulVariable(), _lvalue.type); define(prepared, _value); if (_memory.byteArrayElement) { solAssert(_lvalue.type == *TypeProvider::byte()); appendCode() << "mstore8(" + _memory.address + ", byte(0, " + prepared.commaSeparatedList() + "))\n"; } else appendCode() << m_utils.writeToMemoryFunction(_lvalue.type) << "(" << _memory.address << ", " << prepared.commaSeparatedList() << ")\n"; } else if (auto const* literalType = dynamic_cast<StringLiteralType const*>(&_value.type())) { std::string writeUInt = m_utils.writeToMemoryFunction(*TypeProvider::uint256()); appendCode() << writeUInt << "(" << _memory.address << ", " << m_utils.copyLiteralToMemoryFunction(literalType->value()) + "()" << ")\n"; } else { solAssert(_lvalue.type.sizeOnStack() == 1); auto const* valueReferenceType = dynamic_cast<ReferenceType const*>(&_value.type()); solAssert(valueReferenceType); if (valueReferenceType->dataStoredIn(DataLocation::Memory)) appendCode() << "mstore(" + _memory.address + ", " + _value.part("mpos").name() + ")\n"; else appendCode() << "mstore(" + _memory.address + ", " + m_utils.conversionFunction(_value.type(), _lvalue.type) + "(" + _value.commaSeparatedList() + "))\n"; } }, [&](IRLValue::Stack const& _stack) { assign(_stack.variable, _value); }, [&](IRLValue::Immutable const& _immutable) { solUnimplementedAssert(_lvalue.type.isValueType()); solUnimplementedAssert(_lvalue.type.sizeOnStack() == 1); solAssert(_lvalue.type == *_immutable.variable->type()); size_t memOffset = m_context.immutableMemoryOffset(*_immutable.variable); IRVariable prepared(m_context.newYulVariable(), _lvalue.type); define(prepared, _value); appendCode() << "mstore(" << std::to_string(memOffset) << ", " << prepared.commaSeparatedList() << ")\n"; }, [&](IRLValue::Tuple const& _tuple) { auto components = std::move(_tuple.components); for (size_t i = 0; i < components.size(); i++) { size_t idx = components.size() - i - 1; if (components[idx]) writeToLValue(*components[idx], _value.tupleComponent(idx)); } } }, _lvalue.kind ); } IRVariable IRGeneratorForStatements::readFromLValue(IRLValue const& _lvalue) { IRVariable result{m_context.newYulVariable(), _lvalue.type}; std::visit(GenericVisitor{ [&](IRLValue::Storage const& _storage) { if (!_lvalue.type.isValueType()) define(result) << _storage.slot << "\n"; else if (std::holds_alternative<std::string>(_storage.offset)) define(result) << m_utils.readFromStorageDynamic(_lvalue.type, true, VariableDeclaration::Location::Unspecified) << "(" << _storage.slot << ", " << std::get<std::string>(_storage.offset) << ")\n"; else define(result) << m_utils.readFromStorage(_lvalue.type, std::get<unsigned>(_storage.offset), true, VariableDeclaration::Location::Unspecified) << "(" << _storage.slot << ")\n"; }, [&](IRLValue::TransientStorage const& _transientStorage) { if (!_lvalue.type.isValueType()) define(result) << _transientStorage.slot << "\n"; else if (std::holds_alternative<std::string>(_transientStorage.offset)) define(result) << m_utils.readFromStorageDynamic(_lvalue.type, true, VariableDeclaration::Location::Transient) << "(" << _transientStorage.slot << ", " << std::get<std::string>(_transientStorage.offset) << ")\n"; else define(result) << m_utils.readFromStorage(_lvalue.type, std::get<unsigned>(_transientStorage.offset), true, VariableDeclaration::Location::Transient) << "(" << _transientStorage.slot << ")\n"; }, [&](IRLValue::Memory const& _memory) { if (_lvalue.type.isValueType()) define(result) << m_utils.readFromMemory(_lvalue.type) << "(" << _memory.address << ")\n"; else define(result) << "mload(" << _memory.address << ")\n"; }, [&](IRLValue::Stack const& _stack) { define(result, _stack.variable); }, [&](IRLValue::Immutable const& _immutable) { solUnimplementedAssert(_lvalue.type.isValueType()); solUnimplementedAssert(_lvalue.type.sizeOnStack() == 1); solAssert(_lvalue.type == *_immutable.variable->type()); if (m_context.executionContext() == IRGenerationContext::ExecutionContext::Creation) { std::string readFunction = m_utils.readFromMemory(*_immutable.variable->type()); define(result) << readFunction << "(" << std::to_string(m_context.immutableMemoryOffset(*_immutable.variable)) << ")\n"; } else { if (!m_context.eofVersion().has_value()) define(result) << "loadimmutable(\"" << std::to_string(_immutable.variable->id()) << "\")\n"; else define(result) << "auxdataloadn(" << std::to_string(m_context.immutableMemoryOffsetRelative(*_immutable.variable)) << ")\n"; } }, [&](IRLValue::Tuple const&) { solAssert(false, "Attempted to read from tuple lvalue."); } }, _lvalue.kind); return result; } void IRGeneratorForStatements::setLValue(Expression const& _expression, IRLValue _lvalue) { solAssert(!m_currentLValue); if (_expression.annotation().willBeWrittenTo) { m_currentLValue.emplace(std::move(_lvalue)); if (_lvalue.type.dataStoredIn(DataLocation::CallData)) solAssert(std::holds_alternative<IRLValue::Stack>(_lvalue.kind)); } else // Only define the expression, if it will not be written to. define(_expression, readFromLValue(_lvalue)); } void IRGeneratorForStatements::generateLoop( Statement const& _body, Expression const* _conditionExpression, Statement const* _initExpression, ExpressionStatement const* _loopExpression, bool _isDoWhile, bool _isSimpleCounterLoop ) { std::string firstRun; if (_isDoWhile) { solAssert(_conditionExpression, "Expected condition for doWhile"); firstRun = m_context.newYulVariable(); appendCode() << "let " << firstRun << " := 1\n"; } appendCode() << "for {\n"; if (_initExpression) _initExpression->accept(*this); appendCode() << "} 1 {\n"; if (_loopExpression) { Arithmetic previousArithmetic = m_context.arithmetic(); if (m_optimiserSettings.simpleCounterForLoopUncheckedIncrement && _isSimpleCounterLoop) m_context.setArithmetic(Arithmetic::Wrapping); _loopExpression->accept(*this); m_context.setArithmetic(previousArithmetic); } appendCode() << "}\n"; appendCode() << "{\n"; if (_conditionExpression) { if (_isDoWhile) appendCode() << "if iszero(" << firstRun << ") {\n"; _conditionExpression->accept(*this); appendCode() << "if iszero(" << expressionAsType(*_conditionExpression, *TypeProvider::boolean()) << ") { break }\n"; if (_isDoWhile) appendCode() << "}\n" << firstRun << " := 0\n"; } _body.accept(*this); appendCode() << "}\n"; } Type const& IRGeneratorForStatements::type(Expression const& _expression) { solAssert(_expression.annotation().type, "Type of expression not set."); return *_expression.annotation().type; } bool IRGeneratorForStatements::visit(TryStatement const& _tryStatement) { Expression const& externalCall = _tryStatement.externalCall(); externalCall.accept(*this); setLocation(_tryStatement); appendCode() << "switch iszero(" << IRNames::trySuccessConditionVariable(externalCall) << ")\n"; appendCode() << "case 0 { // success case\n"; TryCatchClause const& successClause = *_tryStatement.clauses().front(); if (successClause.parameters()) { size_t i = 0; for (ASTPointer<VariableDeclaration> const& varDecl: successClause.parameters()->parameters()) { solAssert(varDecl); define(m_context.addLocalVariable(*varDecl), successClause.parameters()->parameters().size() == 1 ? IRVariable(externalCall) : IRVariable(externalCall).tupleComponent(i++) ); } } successClause.block().accept(*this); setLocation(_tryStatement); appendCode() << "}\n"; appendCode() << "default { // failure case\n"; handleCatch(_tryStatement); appendCode() << "}\n"; return false; } void IRGeneratorForStatements::handleCatch(TryStatement const& _tryStatement) { setLocation(_tryStatement); std::string const runFallback = m_context.newYulVariable(); appendCode() << "let " << runFallback << " := 1\n"; // This function returns zero on "short returndata". We have to add a success flag // once we implement custom error codes. if (_tryStatement.errorClause() || _tryStatement.panicClause()) appendCode() << "switch " << m_utils.returnDataSelectorFunction() << "()\n"; if (TryCatchClause const* errorClause = _tryStatement.errorClause()) { appendCode() << "case " << selectorFromSignatureU32("Error(string)") << " {\n"; setLocation(*errorClause); std::string const dataVariable = m_context.newYulVariable(); appendCode() << "let " << dataVariable << " := " << m_utils.tryDecodeErrorMessageFunction() << "()\n"; appendCode() << "if " << dataVariable << " {\n"; appendCode() << runFallback << " := 0\n"; if (errorClause->parameters()) { solAssert(errorClause->parameters()->parameters().size() == 1); IRVariable const& var = m_context.addLocalVariable(*errorClause->parameters()->parameters().front()); define(var) << dataVariable << "\n"; } errorClause->accept(*this); setLocation(*errorClause); appendCode() << "}\n"; setLocation(_tryStatement); appendCode() << "}\n"; } if (TryCatchClause const* panicClause = _tryStatement.panicClause()) { appendCode() << "case " << selectorFromSignatureU32("Panic(uint256)") << " {\n"; setLocation(*panicClause); std::string const success = m_context.newYulVariable(); std::string const code = m_context.newYulVariable(); appendCode() << "let " << success << ", " << code << " := " << m_utils.tryDecodePanicDataFunction() << "()\n"; appendCode() << "if " << success << " {\n"; appendCode() << runFallback << " := 0\n"; if (panicClause->parameters()) { solAssert(panicClause->parameters()->parameters().size() == 1); IRVariable const& var = m_context.addLocalVariable(*panicClause->parameters()->parameters().front()); define(var) << code << "\n"; } panicClause->accept(*this); setLocation(*panicClause); appendCode() << "}\n"; setLocation(_tryStatement); appendCode() << "}\n"; } setLocation(_tryStatement); appendCode() << "if " << runFallback << " {\n"; if (_tryStatement.fallbackClause()) handleCatchFallback(*_tryStatement.fallbackClause()); else appendCode() << m_utils.forwardingRevertFunction() << "()\n"; setLocation(_tryStatement); appendCode() << "}\n"; } void IRGeneratorForStatements::handleCatchFallback(TryCatchClause const& _fallback) { setLocation(_fallback); if (_fallback.parameters()) { solAssert(m_context.evmVersion().supportsReturndata()); solAssert( _fallback.parameters()->parameters().size() == 1 && _fallback.parameters()->parameters().front() && *_fallback.parameters()->parameters().front()->annotation().type == *TypeProvider::bytesMemory(), "" ); VariableDeclaration const& paramDecl = *_fallback.parameters()->parameters().front(); define(m_context.addLocalVariable(paramDecl)) << m_utils.extractReturndataFunction() << "()\n"; } _fallback.accept(*this); } void IRGeneratorForStatements::revertWithError( std::string const& _signature, std::vector<Type const*> const& _parameterTypes, std::vector<ASTPointer<Expression const>> const& _errorArguments ) { appendCode() << m_utils.revertWithError( _signature, _parameterTypes, _errorArguments, m_context.newYulVariable(), m_context.newYulVariable() ); } bool IRGeneratorForStatements::visit(TryCatchClause const& _clause) { _clause.block().accept(*this); return false; } std::string IRGeneratorForStatements::linkerSymbol(ContractDefinition const& _library) const { solAssert(_library.isLibrary()); return "linkersymbol(" + util::escapeAndQuoteString(_library.fullyQualifiedName()) + ")"; }
122,533
C++
.cpp
3,171
35.221066
160
0.712386
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
3,193
IRGenerationContext.cpp
ethereum_solidity/libsolidity/codegen/ir/IRGenerationContext.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 /** * Class that contains contextual information during IR generation. */ #include <libsolidity/codegen/ir/IRGenerationContext.h> #include <libsolidity/codegen/YulUtilFunctions.h> #include <libsolidity/codegen/ABIFunctions.h> #include <libsolidity/codegen/CompilerUtils.h> #include <libsolidity/ast/AST.h> #include <libsolidity/ast/TypeProvider.h> #include <libsolutil/Whiskers.h> #include <libsolutil/StringUtils.h> #include <range/v3/view/map.hpp> #include <range/v3/algorithm/find.hpp> using namespace solidity; using namespace solidity::util; using namespace solidity::frontend; std::string IRGenerationContext::enqueueFunctionForCodeGeneration(FunctionDefinition const& _function) { std::string name = IRNames::function(_function); if (!m_functions.contains(name)) m_functionGenerationQueue.push_back(&_function); return name; } FunctionDefinition const* IRGenerationContext::dequeueFunctionForCodeGeneration() { solAssert(!m_functionGenerationQueue.empty(), ""); FunctionDefinition const* result = m_functionGenerationQueue.front(); m_functionGenerationQueue.pop_front(); return result; } ContractDefinition const& IRGenerationContext::mostDerivedContract() const { solAssert(m_mostDerivedContract, "Most derived contract requested but not set."); return *m_mostDerivedContract; } IRVariable const& IRGenerationContext::addLocalVariable(VariableDeclaration const& _varDecl) { auto const& [it, didInsert] = m_localVariables.emplace( std::make_pair(&_varDecl, IRVariable{_varDecl}) ); solAssert(didInsert, "Local variable added multiple times."); return it->second; } IRVariable const& IRGenerationContext::localVariable(VariableDeclaration const& _varDecl) { solAssert( m_localVariables.count(&_varDecl), "Unknown variable: " + _varDecl.name() ); return m_localVariables.at(&_varDecl); } void IRGenerationContext::resetLocalVariables() { m_localVariables.clear(); } void IRGenerationContext::registerImmutableVariable(VariableDeclaration const& _variable) { solAssert(_variable.immutable(), "Attempted to register a non-immutable variable as immutable."); solUnimplementedAssert( _variable.annotation().type->isValueType(), "Only immutable variables of value type are supported." ); solAssert(m_reservedMemory.has_value(), "Reserved memory has already been reset."); m_immutableVariables[&_variable] = CompilerUtils::generalPurposeMemoryStart + *m_reservedMemory; solAssert(_variable.annotation().type->memoryHeadSize() == 32, "Memory writes might overlap."); *m_reservedMemory += _variable.annotation().type->memoryHeadSize(); } size_t IRGenerationContext::immutableMemoryOffset(VariableDeclaration const& _variable) const { solAssert( m_immutableVariables.count(&_variable), "Unknown immutable variable: " + _variable.name() ); return m_immutableVariables.at(&_variable); } size_t IRGenerationContext::immutableMemoryOffsetRelative(VariableDeclaration const& _variable) const { auto const absoluteOffset = immutableMemoryOffset(_variable); solAssert(absoluteOffset >= CompilerUtils::generalPurposeMemoryStart); return absoluteOffset - CompilerUtils::generalPurposeMemoryStart; } size_t IRGenerationContext::reservedMemorySize() const { solAssert(m_reservedMemory.has_value()); return *m_reservedMemory; } void IRGenerationContext::registerLibraryAddressImmutable() { solAssert(m_reservedMemory.has_value(), "Reserved memory has already been reset."); solAssert(!m_libraryAddressImmutableOffset.has_value()); m_libraryAddressImmutableOffset = CompilerUtils::generalPurposeMemoryStart + *m_reservedMemory; *m_reservedMemory += 32; } size_t IRGenerationContext::libraryAddressImmutableOffset() const { solAssert(m_libraryAddressImmutableOffset.has_value()); return *m_libraryAddressImmutableOffset; } size_t IRGenerationContext::libraryAddressImmutableOffsetRelative() const { solAssert(m_libraryAddressImmutableOffset.has_value()); solAssert(m_libraryAddressImmutableOffset >= CompilerUtils::generalPurposeMemoryStart); return *m_libraryAddressImmutableOffset - CompilerUtils::generalPurposeMemoryStart; } size_t IRGenerationContext::reservedMemory() { solAssert(m_reservedMemory.has_value(), "Reserved memory was used before."); size_t reservedMemory = *m_reservedMemory; // We assume reserved memory contains only immutable variables. // This memory is used i.e. by RETURNCONTRACT to create new EOF container with aux data. size_t immutableVariablesSize = 0; for (auto const* var: keys(m_immutableVariables)) { solUnimplementedAssert(var->type()->isValueType()); solUnimplementedAssert(var->type()->sizeOnStack() == 1); immutableVariablesSize += var->type()->sizeOnStack() * 32; } solAssert(immutableVariablesSize == reservedMemory); m_reservedMemory = std::nullopt; return reservedMemory; } void IRGenerationContext::addStateVariable( VariableDeclaration const& _declaration, u256 _storageOffset, unsigned _byteOffset ) { m_stateVariables[&_declaration] = std::make_pair(std::move(_storageOffset), _byteOffset); } std::string IRGenerationContext::newYulVariable() { return "_" + std::to_string(++m_varCounter); } void IRGenerationContext::initializeInternalDispatch(InternalDispatchMap _internalDispatch) { solAssert(internalDispatchClean(), ""); for (DispatchQueue const& functions: _internalDispatch | ranges::views::values) for (auto function: functions) enqueueFunctionForCodeGeneration(*function); m_internalDispatchMap = std::move(_internalDispatch); } InternalDispatchMap IRGenerationContext::consumeInternalDispatchMap() { InternalDispatchMap internalDispatch = std::move(m_internalDispatchMap); m_internalDispatchMap.clear(); return internalDispatch; } void IRGenerationContext::addToInternalDispatch(FunctionDefinition const& _function) { FunctionType const* functionType = TypeProvider::function(_function, FunctionType::Kind::Internal); solAssert(functionType); YulArity arity = YulArity::fromType(*functionType); DispatchQueue& dispatchQueue = m_internalDispatchMap[arity]; if (ranges::find(dispatchQueue, &_function) == ranges::end(dispatchQueue)) { dispatchQueue.push_back(&_function); enqueueFunctionForCodeGeneration(_function); } } void IRGenerationContext::internalFunctionCalledThroughDispatch(YulArity const& _arity) { m_internalDispatchMap.try_emplace(_arity); } YulUtilFunctions IRGenerationContext::utils() { return YulUtilFunctions(m_evmVersion, m_revertStrings, m_functions); } ABIFunctions IRGenerationContext::abiFunctions() { return ABIFunctions(m_evmVersion, m_revertStrings, m_functions); }
7,258
C++
.cpp
185
37.383784
102
0.810892
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,197
ControlFlowRevertPruner.cpp
ethereum_solidity/libsolidity/analysis/ControlFlowRevertPruner.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libsolidity/analysis/ControlFlowRevertPruner.h> #include <libsolutil/Algorithms.h> #include <range/v3/algorithm/remove.hpp> namespace solidity::frontend { namespace { /// Find the right scope for the called function: When calling a base function, /// we keep the most derived, but we use the called contract in case it is a /// library function or nullptr for a free function. ContractDefinition const* findScopeContract(FunctionDefinition const& _function, ContractDefinition const* _callingContract) { if (auto const* functionContract = _function.annotation().contract) { if (_callingContract && _callingContract->derivesFrom(*functionContract)) return _callingContract; else return functionContract; } return nullptr; } } void ControlFlowRevertPruner::run() { for (auto& [pair, flow]: m_cfg.allFunctionFlows()) m_functions[pair] = RevertState::Unknown; findRevertStates(); modifyFunctionFlows(); } void ControlFlowRevertPruner::findRevertStates() { std::set<CFG::FunctionContractTuple> pendingFunctions = util::keys(m_functions); // We interrupt the search whenever we encounter a call to a function with (yet) unknown // revert behaviour. The ``wakeUp`` data structure contains information about which // searches to restart once we know about the behaviour. std::map<CFG::FunctionContractTuple, std::set<CFG::FunctionContractTuple>> wakeUp; while (!pendingFunctions.empty()) { CFG::FunctionContractTuple item = *pendingFunctions.begin(); pendingFunctions.erase(pendingFunctions.begin()); if (m_functions[item] != RevertState::Unknown) continue; bool foundExit = false; bool foundUnknown = false; FunctionFlow const& functionFlow = m_cfg.functionFlow(*item.function, item.contract); solidity::util::BreadthFirstSearch<CFGNode*>{{functionFlow.entry}}.run( [&](CFGNode* _node, auto&& _addChild) { if (_node == functionFlow.exit) foundExit = true; auto const* resolvedFunction = _node->functionDefinition; if (resolvedFunction && resolvedFunction->isImplemented()) { CFG::FunctionContractTuple calledFunctionTuple{ findScopeContract(*resolvedFunction, item.contract), resolvedFunction }; switch (m_functions.at(calledFunctionTuple)) { case RevertState::Unknown: wakeUp[calledFunctionTuple].insert(item); foundUnknown = true; return; case RevertState::AllPathsRevert: return; case RevertState::HasNonRevertingPath: break; } } for (CFGNode* exit: _node->exits) _addChild(exit); } ); auto& revertState = m_functions[item]; if (foundExit) revertState = RevertState::HasNonRevertingPath; else if (!foundUnknown) revertState = RevertState::AllPathsRevert; if (revertState != RevertState::Unknown && wakeUp.count(item)) { // Restart all searches blocked by this function. for (CFG::FunctionContractTuple const& nextItem: wakeUp[item]) if (m_functions.at(nextItem) == RevertState::Unknown) pendingFunctions.insert(nextItem); wakeUp.erase(item); } } } void ControlFlowRevertPruner::modifyFunctionFlows() { for (auto& item: m_functions) { FunctionFlow const& functionFlow = m_cfg.functionFlow(*item.first.function, item.first.contract); solidity::util::BreadthFirstSearch<CFGNode*>{{functionFlow.entry}}.run( [&](CFGNode* _node, auto&& _addChild) { auto const* resolvedFunction = _node->functionDefinition; if (resolvedFunction && resolvedFunction->isImplemented()) switch (m_functions.at({findScopeContract(*resolvedFunction, item.first.contract), resolvedFunction})) { case RevertState::Unknown: [[fallthrough]]; case RevertState::AllPathsRevert: // If the revert states of the functions do not // change anymore, we treat all "unknown" states as // "reverting", since they can only be caused by // recursion. for (CFGNode * node: _node->exits) ranges::remove(node->entries, _node); _node->exits = {functionFlow.revert}; functionFlow.revert->entries.push_back(_node); return; default: break; } for (CFGNode* exit: _node->exits) _addChild(exit); }); } } }
4,920
C++
.cpp
133
33.052632
124
0.736289
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
3,198
DocStringTagParser.cpp
ethereum_solidity/libsolidity/analysis/DocStringTagParser.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ /** * @author Christian <c@ethdev.com> * @date 2015 * Parses and analyses the doc strings. * Stores the parsing results in the AST annotations and reports errors. */ #include <libsolidity/analysis/DocStringTagParser.h> #include <libsolidity/ast/AST.h> #include <libsolidity/parsing/DocStringParser.h> #include <libsolidity/analysis/NameAndTypeResolver.h> #include <liblangutil/ErrorReporter.h> #include <liblangutil/Common.h> #include <range/v3/algorithm/any_of.hpp> #include <range/v3/view/filter.hpp> #include <boost/algorithm/string.hpp> #include <regex> #include <string_view> using namespace solidity; using namespace solidity::langutil; using namespace solidity::frontend; bool DocStringTagParser::parseDocStrings(SourceUnit const& _sourceUnit) { auto errorWatcher = m_errorReporter.errorWatcher(); _sourceUnit.accept(*this); return errorWatcher.ok(); } bool DocStringTagParser::validateDocStringsUsingTypes(SourceUnit const& _sourceUnit) { ErrorReporter::ErrorWatcher errorWatcher = m_errorReporter.errorWatcher(); SimpleASTVisitor visitReturns( [](ASTNode const&) { return true; }, [&](ASTNode const& _node) { if (auto const* annotation = dynamic_cast<StructurallyDocumentedAnnotation const*>(&_node.annotation())) { auto const& documentationNode = dynamic_cast<StructurallyDocumented const&>(_node); size_t returnTagsVisited = 0; for (auto const& [tagName, tagValue]: annotation->docTags) if (tagName == "return") { returnTagsVisited++; std::vector<std::string> returnParameterNames; if (auto const* varDecl = dynamic_cast<VariableDeclaration const*>(&_node)) { if (!varDecl->isPublic()) continue; // FunctionType() requires the DeclarationTypeChecker to have run. returnParameterNames = FunctionType(*varDecl).returnParameterNames(); } else if (auto const* function = dynamic_cast<FunctionDefinition const*>(&_node)) returnParameterNames = FunctionType(*function).returnParameterNames(); else continue; std::string content = tagValue.content; std::string firstWord = content.substr(0, content.find_first_of(" \t")); if (returnTagsVisited > returnParameterNames.size()) m_errorReporter.docstringParsingError( 2604_error, documentationNode.documentation()->location(), "Documentation tag \"@" + tagName + " " + content + "\"" + " exceeds the number of return parameters." ); else { std::string const& parameter = returnParameterNames.at(returnTagsVisited - 1); if (!parameter.empty() && parameter != firstWord) m_errorReporter.docstringParsingError( 5856_error, documentationNode.documentation()->location(), "Documentation tag \"@" + tagName + " " + content + "\"" + " does not contain the name of its return parameter." ); } } } }); _sourceUnit.accept(visitReturns); return errorWatcher.ok(); } bool DocStringTagParser::visit(ContractDefinition const& _contract) { static std::set<std::string> const validTags = std::set<std::string>{"author", "title", "dev", "notice"}; parseDocStrings(_contract, _contract.annotation(), validTags, "contracts"); return true; } bool DocStringTagParser::visit(FunctionDefinition const& _function) { if (_function.isConstructor()) handleConstructor(_function, _function, _function.annotation()); else handleCallable(_function, _function, _function.annotation()); return true; } bool DocStringTagParser::visit(VariableDeclaration const& _variable) { if (_variable.isStateVariable()) { if (_variable.isPublic()) parseDocStrings(_variable, _variable.annotation(), {"dev", "notice", "return", "inheritdoc"}, "public state variables"); else parseDocStrings(_variable, _variable.annotation(), {"dev", "notice", "inheritdoc"}, "non-public state variables"); } else if (_variable.isFileLevelVariable()) parseDocStrings(_variable, _variable.annotation(), {"dev"}, "file-level variables"); return false; } bool DocStringTagParser::visit(ModifierDefinition const& _modifier) { handleCallable(_modifier, _modifier, _modifier.annotation()); return true; } bool DocStringTagParser::visit(EventDefinition const& _event) { handleCallable(_event, _event, _event.annotation()); return true; } bool DocStringTagParser::visit(ErrorDefinition const& _error) { handleCallable(_error, _error, _error.annotation()); return true; } bool DocStringTagParser::visit(InlineAssembly const& _assembly) { if (!_assembly.documentation()) return true; StructuredDocumentation documentation{-1, _assembly.location(), _assembly.documentation()}; ErrorList errors; ErrorReporter errorReporter{errors}; auto docTags = DocStringParser{documentation, errorReporter}.parse(); if (!errors.empty()) { SecondarySourceLocation ssl; for (auto const& error: errors) if (error->comment()) ssl.append( *error->comment(), _assembly.location() ); m_errorReporter.warning( 7828_error, _assembly.location(), "Inline assembly has invalid NatSpec documentation.", ssl ); } for (auto const& [tagName, tagValue]: docTags) { if (tagName == "solidity") { std::vector<std::string> values; boost::split(values, tagValue.content, isWhiteSpace); std::set<std::string> valuesSeen; std::set<std::string> duplicates; for (auto const& value: values | ranges::views::filter(not_fn(&std::string::empty))) if (valuesSeen.insert(value).second) { if (value == "memory-safe-assembly") { if (_assembly.annotation().markedMemorySafe) m_errorReporter.warning( 8544_error, _assembly.location(), "Inline assembly marked as memory safe using both a NatSpec tag and an assembly flag. " "If you are not concerned with backwards compatibility, only use the assembly flag, " "otherwise only use the NatSpec tag." ); _assembly.annotation().markedMemorySafe = true; } else m_errorReporter.warning( 8787_error, _assembly.location(), "Unexpected value for @solidity tag in inline assembly: " + value ); } else if (duplicates.insert(value).second) m_errorReporter.warning( 4377_error, _assembly.location(), "Value for @solidity tag in inline assembly specified multiple times: " + value ); } else m_errorReporter.warning( 6269_error, _assembly.location(), "Unexpected NatSpec tag \"" + tagName + "\" with value \"" + tagValue.content + "\" in inline assembly." ); } return true; } void DocStringTagParser::checkParameters( CallableDeclaration const& _callable, StructurallyDocumented const& _node, StructurallyDocumentedAnnotation& _annotation ) { std::set<std::string> validParams; for (auto const& p: _callable.parameters()) validParams.insert(p->name()); if (_callable.returnParameterList()) for (auto const& p: _callable.returnParameterList()->parameters()) validParams.insert(p->name()); auto paramRange = _annotation.docTags.equal_range("param"); for (auto i = paramRange.first; i != paramRange.second; ++i) if (!validParams.count(i->second.paramName)) m_errorReporter.docstringParsingError( 3881_error, _node.documentation()->location(), "Documented parameter \"" + i->second.paramName + "\" not found in the parameter list of the function." ); } void DocStringTagParser::handleConstructor( CallableDeclaration const& _callable, StructurallyDocumented const& _node, StructurallyDocumentedAnnotation& _annotation ) { static std::set<std::string> const validTags = std::set<std::string>{"author", "dev", "notice", "param"}; parseDocStrings(_node, _annotation, validTags, "constructor"); checkParameters(_callable, _node, _annotation); } void DocStringTagParser::handleCallable( CallableDeclaration const& _callable, StructurallyDocumented const& _node, StructurallyDocumentedAnnotation& _annotation ) { static std::set<std::string> const validEventTags = std::set<std::string>{"dev", "notice", "return", "param"}; static std::set<std::string> const validErrorTags = std::set<std::string>{"dev", "notice", "param"}; static std::set<std::string> const validModifierTags = std::set<std::string>{"dev", "notice", "param", "inheritdoc"}; static std::set<std::string> const validTags = std::set<std::string>{"dev", "notice", "return", "param", "inheritdoc"}; if (dynamic_cast<EventDefinition const*>(&_callable)) parseDocStrings(_node, _annotation, validEventTags, "events"); else if (dynamic_cast<ErrorDefinition const*>(&_callable)) parseDocStrings(_node, _annotation, validErrorTags, "errors"); else if (dynamic_cast<ModifierDefinition const*>(&_callable)) parseDocStrings(_node, _annotation, validModifierTags, "modifiers"); else parseDocStrings(_node, _annotation, validTags, "functions"); checkParameters(_callable, _node, _annotation); } void DocStringTagParser::parseDocStrings( StructurallyDocumented const& _node, StructurallyDocumentedAnnotation& _annotation, std::set<std::string> const& _validTags, std::string const& _nodeName ) { if (!_node.documentation()) return; _annotation.docTags = DocStringParser{*_node.documentation(), m_errorReporter}.parse(); for (auto const& [tagName, tagValue]: _annotation.docTags) { std::string_view static constexpr customPrefix("custom:"); if (tagName == "custom" || tagName == "custom:") m_errorReporter.docstringParsingError( 6564_error, _node.documentation()->location(), "Custom documentation tag must contain a chosen name, i.e. @custom:mytag." ); else if (boost::starts_with(tagName, customPrefix) && tagName.size() > customPrefix.size()) { std::regex static const customRegex("^custom:[a-z][a-z-]*$"); if (!regex_match(tagName, customRegex)) m_errorReporter.docstringParsingError( 2968_error, _node.documentation()->location(), "Invalid character in custom tag @" + tagName + ". Only lowercase letters and \"-\" are permitted." ); continue; } else if (!_validTags.count(tagName)) m_errorReporter.docstringParsingError( 6546_error, _node.documentation()->location(), "Documentation tag @" + tagName + " not valid for " + _nodeName + "." ); } }
10,981
C++
.cpp
295
33.532203
123
0.72301
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
3,199
ControlFlowGraph.cpp
ethereum_solidity/libsolidity/analysis/ControlFlowGraph.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libsolidity/analysis/ControlFlowGraph.h> #include <libsolidity/analysis/ControlFlowBuilder.h> using namespace solidity::langutil; using namespace solidity::frontend; bool CFG::constructFlow(ASTNode const& _astRoot) { _astRoot.accept(*this); return !Error::containsErrors(m_errorReporter.errors()); } bool CFG::visit(FunctionDefinition const& _function) { if (_function.isImplemented() && _function.isFree()) m_functionControlFlow[{nullptr, &_function}] = ControlFlowBuilder::createFunctionFlow( m_nodeContainer, _function, nullptr /* _contract */ ); return false; } bool CFG::visit(ContractDefinition const& _contract) { for (ContractDefinition const* contract: _contract.annotation().linearizedBaseContracts) for (FunctionDefinition const* function: contract->definedFunctions()) if (function->isImplemented()) m_functionControlFlow[{&_contract, function}] = ControlFlowBuilder::createFunctionFlow(m_nodeContainer, *function, &_contract); return true; } FunctionFlow const& CFG::functionFlow(FunctionDefinition const& _function, ContractDefinition const* _contract) const { return *m_functionControlFlow.at({_contract, &_function}); } CFGNode* CFG::NodeContainer::newNode() { m_nodes.emplace_back(std::make_unique<CFGNode>()); return m_nodes.back().get(); }
2,000
C++
.cpp
51
37.039216
117
0.782541
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
3,200
StaticAnalyzer.cpp
ethereum_solidity/libsolidity/analysis/StaticAnalyzer.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 /** * @author Federico Bond <federicobond@gmail.com> * @date 2016 * Static analyzer and checker. */ #include <libsolidity/analysis/StaticAnalyzer.h> #include <libsolidity/analysis/ConstantEvaluator.h> #include <libsolidity/ast/AST.h> #include <libsolidity/ast/ASTUtils.h> #include <liblangutil/ErrorReporter.h> #include <range/v3/view/enumerate.hpp> #include <memory> using namespace solidity; using namespace solidity::langutil; using namespace solidity::frontend; /** * Helper class that determines whether a contract's constructor uses inline assembly. */ class solidity::frontend::ConstructorUsesAssembly { public: /// @returns true if and only if the contract's or any of its bases' constructors /// use inline assembly. bool check(ContractDefinition const& _contract) { for (auto const* base: _contract.annotation().linearizedBaseContracts) if (checkInternal(*base)) return true; return false; } private: class Checker: public ASTConstVisitor { public: Checker(FunctionDefinition const& _f) { _f.accept(*this); } bool visit(InlineAssembly const&) override { assemblySeen = true; return false; } bool assemblySeen = false; }; bool checkInternal(ContractDefinition const& _contract) { if (!m_usesAssembly.count(&_contract)) { bool usesAssembly = false; if (_contract.constructor()) usesAssembly = Checker{*_contract.constructor()}.assemblySeen; m_usesAssembly[&_contract] = usesAssembly; } return m_usesAssembly[&_contract]; } std::map<ContractDefinition const*, bool> m_usesAssembly; }; StaticAnalyzer::StaticAnalyzer(ErrorReporter& _errorReporter): m_errorReporter(_errorReporter) { } StaticAnalyzer::~StaticAnalyzer() { } bool StaticAnalyzer::analyze(SourceUnit const& _sourceUnit) { _sourceUnit.accept(*this); return !Error::containsErrors(m_errorReporter.errors()); } bool StaticAnalyzer::visit(Assignment const& _assignment) { Type const* lhsType = _assignment.leftHandSide().annotation().type; Type const* rhsType = _assignment.rightHandSide().annotation().type; solAssert(lhsType && rhsType, "Both left and right hand side expressions in an assignment must have a type."); if (dynamic_cast<TupleType const*>(lhsType) && dynamic_cast<TupleType const*>(rhsType)) checkDoubleStorageAssignment(_assignment); return true; } bool StaticAnalyzer::visit(ContractDefinition const& _contract) { m_library = _contract.isLibrary(); m_currentContract = &_contract; return true; } void StaticAnalyzer::endVisit(ContractDefinition const&) { m_library = false; m_currentContract = nullptr; } bool StaticAnalyzer::visit(FunctionDefinition const& _function) { if (_function.isImplemented()) m_currentFunction = &_function; else solAssert(!m_currentFunction, ""); solAssert(m_localVarUseCount.empty(), ""); m_constructor = _function.isConstructor(); return true; } void StaticAnalyzer::endVisit(FunctionDefinition const&) { if (m_currentFunction && !m_currentFunction->body().statements().empty()) for (auto const& var: m_localVarUseCount) if (var.second == 0) { if (var.first.second->isCallableOrCatchParameter()) m_errorReporter.warning( 5667_error, var.first.second->location(), "Unused " + std::string(var.first.second->isTryCatchParameter() ? "try/catch" : "function") + " parameter. Remove or comment out the variable name to silence this warning." ); else m_errorReporter.warning(2072_error, var.first.second->location(), "Unused local variable."); } m_localVarUseCount.clear(); m_constructor = false; m_currentFunction = nullptr; } bool StaticAnalyzer::visit(Identifier const& _identifier) { if (m_currentFunction) if (auto var = dynamic_cast<VariableDeclaration const*>(_identifier.annotation().referencedDeclaration)) { solAssert(!var->name().empty(), ""); if (var->isLocalVariable()) m_localVarUseCount[std::make_pair(var->id(), var)] += 1; } return true; } bool StaticAnalyzer::visit(VariableDeclaration const& _variable) { if (m_currentFunction) { solAssert(_variable.isLocalVariable(), ""); if (_variable.name() != "") // This is not a no-op, the entry might pre-exist. m_localVarUseCount[std::make_pair(_variable.id(), &_variable)] += 0; } if (_variable.isStateVariable() || _variable.referenceLocation() == VariableDeclaration::Location::Storage) if (auto varType = dynamic_cast<CompositeType const*>(_variable.annotation().type)) for (Type const* type: varType->fullDecomposition()) if (type->storageSizeUpperBound() >= (bigint(1) << 64)) { std::string message = "Type " + type->toString(true) + " covers a large part of storage and thus makes collisions likely." " Either use mappings or dynamic arrays and allow their size to be increased only" " in small quantities per transaction."; m_errorReporter.warning(7325_error, _variable.typeName().location(), message); } return true; } bool StaticAnalyzer::visit(Return const& _return) { // If the return has an expression, it counts as // a "use" of the return parameters. if (m_currentFunction && _return.expression()) for (auto const& var: m_currentFunction->returnParameters()) if (!var->name().empty()) m_localVarUseCount[std::make_pair(var->id(), var.get())] += 1; return true; } bool StaticAnalyzer::visit(ExpressionStatement const& _statement) { if (*_statement.expression().annotation().isPure) m_errorReporter.warning( 6133_error, _statement.location(), "Statement has no effect." ); return true; } bool StaticAnalyzer::visit(MemberAccess const& _memberAccess) { if (MagicType const* type = dynamic_cast<MagicType const*>(_memberAccess.expression().annotation().type)) { if (type->kind() == MagicType::Kind::Message && _memberAccess.memberName() == "gas") m_errorReporter.typeError( 1400_error, _memberAccess.location(), "\"msg.gas\" has been deprecated in favor of \"gasleft()\"" ); else if (type->kind() == MagicType::Kind::Block && _memberAccess.memberName() == "blockhash") m_errorReporter.typeError( 8113_error, _memberAccess.location(), "\"block.blockhash()\" has been deprecated in favor of \"blockhash()\"" ); else if (type->kind() == MagicType::Kind::MetaType && _memberAccess.memberName() == "runtimeCode") { if (!m_constructorUsesAssembly) m_constructorUsesAssembly = std::make_unique<ConstructorUsesAssembly>(); ContractType const& contract = dynamic_cast<ContractType const&>(*type->typeArgument()); if (m_constructorUsesAssembly->check(contract.contractDefinition())) m_errorReporter.warning( 6417_error, _memberAccess.location(), "The constructor of the contract (or its base) uses inline assembly. " "Because of that, it might be that the deployed bytecode is different from type(...).runtimeCode." ); } else if ( m_currentFunction && m_currentFunction->isReceive() && type->kind() == MagicType::Kind::Message && _memberAccess.memberName() == "data" ) m_errorReporter.typeError( 7139_error, _memberAccess.location(), R"("msg.data" cannot be used inside of "receive" function.)" ); } if (_memberAccess.memberName() == "callcode") if (auto const* type = dynamic_cast<FunctionType const*>(_memberAccess.annotation().type)) if (type->kind() == FunctionType::Kind::BareCallCode) m_errorReporter.typeError( 2256_error, _memberAccess.location(), "\"callcode\" has been deprecated in favour of \"delegatecall\"." ); if (m_constructor) { auto const* expr = &_memberAccess.expression(); while (expr) { if (auto id = dynamic_cast<Identifier const*>(expr)) { if (id->name() == "this") m_errorReporter.warning( 5805_error, id->location(), "\"this\" used in constructor. " "Note that external functions of a contract " "cannot be called while it is being constructed."); break; } else if (auto tuple = dynamic_cast<TupleExpression const*>(expr)) { if (tuple->components().size() == 1) expr = tuple->components().front().get(); else break; } else break; } } return true; } bool StaticAnalyzer::visit(InlineAssembly const& _inlineAssembly) { if (!m_currentFunction) return true; for (auto const& ref: _inlineAssembly.annotation().externalReferences) { if (auto var = dynamic_cast<VariableDeclaration const*>(ref.second.declaration)) { solAssert(!var->name().empty(), ""); if (var->isLocalVariable()) m_localVarUseCount[std::make_pair(var->id(), var)] += 1; } } return true; } bool StaticAnalyzer::visit(BinaryOperation const& _operation) { if ( *_operation.rightExpression().annotation().isPure && (_operation.getOperator() == Token::Div || _operation.getOperator() == Token::Mod) && ConstantEvaluator::evaluate(m_errorReporter, _operation.leftExpression()) ) if (auto rhs = ConstantEvaluator::evaluate(m_errorReporter, _operation.rightExpression())) if (rhs->value == 0) m_errorReporter.typeError( 1211_error, _operation.location(), (_operation.getOperator() == Token::Div) ? "Division by zero." : "Modulo zero." ); return true; } bool StaticAnalyzer::visit(FunctionCall const& _functionCall) { if (*_functionCall.annotation().kind == FunctionCallKind::FunctionCall) { auto functionType = dynamic_cast<FunctionType const*>(_functionCall.expression().annotation().type); solAssert(functionType, ""); if (functionType->kind() == FunctionType::Kind::AddMod || functionType->kind() == FunctionType::Kind::MulMod) { solAssert(_functionCall.arguments().size() == 3, ""); if (*_functionCall.arguments()[2]->annotation().isPure) if (auto lastArg = ConstantEvaluator::evaluate(m_errorReporter, *(_functionCall.arguments())[2])) if (lastArg->value == 0) m_errorReporter.typeError( 4195_error, _functionCall.location(), "Arithmetic modulo zero." ); } if ( m_currentContract && m_currentContract->isLibrary() && functionType->kind() == FunctionType::Kind::DelegateCall && functionType->declaration().scope() == m_currentContract ) m_errorReporter.typeError( 6700_error, _functionCall.location(), SecondarySourceLocation().append( "The function declaration is here:", functionType->declaration().scope()->location() ), "Libraries cannot call their own functions externally." ); } return true; } void StaticAnalyzer::checkDoubleStorageAssignment(Assignment const& _assignment) { size_t storageToStorageCopies = 0; size_t toStorageCopies = 0; size_t storageByteArrayPushes = 0; size_t storageByteAccesses = 0; auto count = [&](TupleExpression const& _lhs, TupleType const& _rhs, auto _recurse) -> void { TupleType const& lhsType = dynamic_cast<TupleType const&>(*type(_lhs)); TupleExpression const* lhsResolved = dynamic_cast<TupleExpression const*>(resolveOuterUnaryTuples(&_lhs)); solAssert(lhsResolved && lhsResolved->components().size() == lhsType.components().size()); if (lhsType.components().size() != _rhs.components().size()) { solAssert(m_errorReporter.hasErrors(), ""); return; } for (auto&& [index, componentType]: lhsType.components() | ranges::views::enumerate) { if (ReferenceType const* ref = dynamic_cast<ReferenceType const*>(componentType)) { if (ref->dataStoredIn(DataLocation::Storage) && !ref->isPointer()) { toStorageCopies++; if (_rhs.components()[index]->dataStoredIn(DataLocation::Storage)) storageToStorageCopies++; } } else if (FixedBytesType const* bytesType = dynamic_cast<FixedBytesType const*>(componentType)) { if (bytesType->numBytes() == 1) { if (FunctionCall const* lhsCall = dynamic_cast<FunctionCall const*>(resolveOuterUnaryTuples(lhsResolved->components().at(index).get()))) { FunctionType const& callType = dynamic_cast<FunctionType const&>(*type(lhsCall->expression())); if (callType.kind() == FunctionType::Kind::ArrayPush) { ArrayType const& arrayType = dynamic_cast<ArrayType const&>(*callType.selfType()); if (arrayType.isByteArray() && arrayType.dataStoredIn(DataLocation::Storage)) { ++storageByteAccesses; ++storageByteArrayPushes; } } } else if (IndexAccess const* indexAccess = dynamic_cast<IndexAccess const*>(resolveOuterUnaryTuples(lhsResolved->components().at(index).get()))) { if (ArrayType const* arrayType = dynamic_cast<ArrayType const*>(type(indexAccess->baseExpression()))) if (arrayType->isByteArray() && arrayType->dataStoredIn(DataLocation::Storage)) ++storageByteAccesses; } } } else if (dynamic_cast<TupleType const*>(componentType)) if (auto const* lhsNested = dynamic_cast<TupleExpression const*>(lhsResolved->components().at(index).get())) if (auto const* rhsNestedType = dynamic_cast<TupleType const*>(_rhs.components().at(index))) _recurse( *lhsNested, *rhsNestedType, _recurse ); } }; TupleExpression const* lhsTupleExpression = dynamic_cast<TupleExpression const*>(&_assignment.leftHandSide()); if (!lhsTupleExpression) { solAssert(m_errorReporter.hasErrors()); return; } count( *lhsTupleExpression, dynamic_cast<TupleType const&>(*type(_assignment.rightHandSide())), count ); if (storageToStorageCopies >= 1 && toStorageCopies >= 2) m_errorReporter.warning( 7238_error, _assignment.location(), "This assignment performs two copies to storage. Since storage copies do not first " "copy to a temporary location, one of them might be overwritten before the second " "is executed and thus may have unexpected effects. It is safer to perform the copies " "separately or assign to storage pointers first." ); if (storageByteArrayPushes >= 1 && storageByteAccesses >= 2) m_errorReporter.warning( 7239_error, _assignment.location(), "This assignment involves multiple accesses to a bytes array in storage while simultaneously enlarging it. " "When a bytes array is enlarged, it may transition from short storage layout to long storage layout, " "which invalidates all references to its elements. It is safer to only enlarge byte arrays in a single " "operation, one element at a time." ); }
15,032
C++
.cpp
417
32.529976
148
0.718463
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,203
ControlFlowAnalyzer.cpp
ethereum_solidity/libsolidity/analysis/ControlFlowAnalyzer.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libsolidity/analysis/ControlFlowAnalyzer.h> #include <liblangutil/SourceLocation.h> #include <libsolutil/Algorithms.h> #include <range/v3/algorithm/sort.hpp> #include <functional> using namespace std::placeholders; using namespace solidity::langutil; using namespace solidity::frontend; bool ControlFlowAnalyzer::run() { for (auto& [pair, flow]: m_cfg.allFunctionFlows()) analyze(*pair.function, pair.contract, *flow); return !Error::containsErrors(m_errorReporter.errors()); } void ControlFlowAnalyzer::analyze(FunctionDefinition const& _function, ContractDefinition const* _contract, FunctionFlow const& _flow) { if (!_function.isImplemented()) return; std::optional<std::string> mostDerivedContractName; // The name of the most derived contract only required if it differs from // the functions contract if (_contract && _contract != _function.annotation().contract) mostDerivedContractName = _contract->name(); checkUninitializedAccess( _flow.entry, _flow.exit, _function.body().statements().empty(), mostDerivedContractName ); checkUnreachable(_flow.entry, _flow.exit, _flow.revert, _flow.transactionReturn); } void ControlFlowAnalyzer::checkUninitializedAccess(CFGNode const* _entry, CFGNode const* _exit, bool _emptyBody, std::optional<std::string> _contractName) { struct NodeInfo { std::set<VariableDeclaration const*> unassignedVariablesAtEntry; std::set<VariableDeclaration const*> unassignedVariablesAtExit; std::set<VariableOccurrence const*> uninitializedVariableAccesses; /// Propagate the information from another node to this node. /// To be used to propagate information from a node to its exit nodes. /// Returns true, if new variables were added and thus the current node has /// to be traversed again. bool propagateFrom(NodeInfo const& _entryNode) { size_t previousUnassignedVariablesAtEntry = unassignedVariablesAtEntry.size(); size_t previousUninitializedVariableAccessess = uninitializedVariableAccesses.size(); unassignedVariablesAtEntry += _entryNode.unassignedVariablesAtExit; uninitializedVariableAccesses += _entryNode.uninitializedVariableAccesses; return unassignedVariablesAtEntry.size() > previousUnassignedVariablesAtEntry || uninitializedVariableAccesses.size() > previousUninitializedVariableAccessess ; } }; std::map<CFGNode const*, NodeInfo> nodeInfos; std::set<CFGNode const*> nodesToTraverse; nodesToTraverse.insert(_entry); // Walk all paths starting from the nodes in ``nodesToTraverse`` until ``NodeInfo::propagateFrom`` // returns false for all exits, i.e. until all paths have been walked with maximal sets of unassigned // variables and accesses. while (!nodesToTraverse.empty()) { CFGNode const* currentNode = *nodesToTraverse.begin(); nodesToTraverse.erase(nodesToTraverse.begin()); auto& nodeInfo = nodeInfos[currentNode]; auto unassignedVariables = nodeInfo.unassignedVariablesAtEntry; for (auto const& variableOccurrence: currentNode->variableOccurrences) { switch (variableOccurrence.kind()) { case VariableOccurrence::Kind::Assignment: unassignedVariables.erase(&variableOccurrence.declaration()); break; case VariableOccurrence::Kind::InlineAssembly: // We consider all variables referenced in inline assembly as accessed. // So far any reference is enough, but we might want to actually analyze // the control flow in the assembly at some point. case VariableOccurrence::Kind::Access: case VariableOccurrence::Kind::Return: if (unassignedVariables.count(&variableOccurrence.declaration())) { // Merely store the unassigned access. We do not generate an error right away, since this // path might still always revert. It is only an error if this is propagated to the exit // node of the function (i.e. there is a path with an uninitialized access). nodeInfo.uninitializedVariableAccesses.insert(&variableOccurrence); } break; case VariableOccurrence::Kind::Declaration: unassignedVariables.insert(&variableOccurrence.declaration()); break; } } nodeInfo.unassignedVariablesAtExit = std::move(unassignedVariables); // Propagate changes to all exits and queue them for traversal, if needed. for (auto const& exit: currentNode->exits) if ( auto exists = util::valueOrNullptr(nodeInfos, exit); nodeInfos[exit].propagateFrom(nodeInfo) || !exists ) nodesToTraverse.insert(exit); } auto const& exitInfo = nodeInfos[_exit]; if (!exitInfo.uninitializedVariableAccesses.empty()) { std::vector<VariableOccurrence const*> uninitializedAccessesOrdered( exitInfo.uninitializedVariableAccesses.begin(), exitInfo.uninitializedVariableAccesses.end() ); ranges::sort( uninitializedAccessesOrdered, [](VariableOccurrence const* lhs, VariableOccurrence const* rhs) -> bool { return *lhs < *rhs; } ); for (auto const* variableOccurrence: uninitializedAccessesOrdered) { VariableDeclaration const& varDecl = variableOccurrence->declaration(); SecondarySourceLocation ssl; if (variableOccurrence->occurrence()) ssl.append("The variable was declared here.", varDecl.location()); bool isStorage = varDecl.type()->dataStoredIn(DataLocation::Storage); bool isCalldata = varDecl.type()->dataStoredIn(DataLocation::CallData); if (isStorage || isCalldata) m_errorReporter.typeError( 3464_error, variableOccurrence->occurrence() ? *variableOccurrence->occurrence() : varDecl.location(), ssl, "This variable is of " + std::string(isStorage ? "storage" : "calldata") + " pointer type and can be " + (variableOccurrence->kind() == VariableOccurrence::Kind::Return ? "returned" : "accessed") + " without prior assignment, which would lead to undefined behaviour." ); else if (!_emptyBody && varDecl.name().empty()) { if (!m_unassignedReturnVarsAlreadyWarnedFor.emplace(&varDecl).second) continue; m_errorReporter.warning( 6321_error, varDecl.location(), "Unnamed return variable can remain unassigned" + ( _contractName.has_value() ? " when the function is called when \"" + _contractName.value() + "\" is the most derived contract." : "." ) + " Add an explicit return with value to all non-reverting code paths or name the variable." ); } } } } void ControlFlowAnalyzer::checkUnreachable(CFGNode const* _entry, CFGNode const* _exit, CFGNode const* _revert, CFGNode const* _transactionReturn) { // collect all nodes reachable from the entry point std::set<CFGNode const*> reachable = util::BreadthFirstSearch<CFGNode const*>{{_entry}}.run( [](CFGNode const* _node, auto&& _addChild) { for (CFGNode const* exit: _node->exits) _addChild(exit); } ).visited; // traverse all paths backwards from exit, revert and transaction return // and extract (valid) source locations of unreachable nodes into sorted set std::set<SourceLocation> unreachable; util::BreadthFirstSearch<CFGNode const*>{{_exit, _revert, _transactionReturn}}.run( [&](CFGNode const* _node, auto&& _addChild) { if (!reachable.count(_node) && _node->location.isValid()) unreachable.insert(_node->location); for (CFGNode const* entry: _node->entries) _addChild(entry); } ); for (auto it = unreachable.begin(); it != unreachable.end();) { SourceLocation location = *it++; // Extend the location, as long as the next location overlaps (unreachable is sorted). for (; it != unreachable.end() && it->start <= location.end; ++it) location.end = std::max(location.end, it->end); if (m_unreachableLocationsAlreadyWarnedFor.emplace(location).second) m_errorReporter.warning(5740_error, location, "Unreachable code."); } }
8,492
C++
.cpp
199
39.070352
154
0.751331
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
3,205
ReferencesResolver.cpp
ethereum_solidity/libsolidity/analysis/ReferencesResolver.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 /** * @author Christian <c@ethdev.com> * @date 2015 * Component that resolves type names to types and annotates the AST accordingly. */ #include <libsolidity/analysis/ReferencesResolver.h> #include <libsolidity/analysis/NameAndTypeResolver.h> #include <libsolidity/ast/AST.h> #include <libyul/AsmAnalysis.h> #include <libyul/AsmAnalysisInfo.h> #include <libyul/AST.h> #include <libyul/backends/evm/EVMDialect.h> #include <liblangutil/ErrorReporter.h> #include <liblangutil/Exceptions.h> #include <libsolutil/StringUtils.h> #include <libsolutil/CommonData.h> #include <boost/algorithm/string.hpp> #include <boost/algorithm/string/split.hpp> using namespace solidity; using namespace solidity::langutil; using namespace solidity::frontend; bool ReferencesResolver::resolve(ASTNode const& _root) { auto errorWatcher = m_errorReporter.errorWatcher(); _root.accept(*this); return errorWatcher.ok(); } bool ReferencesResolver::visit(Block const& _block) { if (!m_resolveInsideCode) return false; m_resolver.setScope(&_block); return true; } void ReferencesResolver::endVisit(Block const& _block) { if (!m_resolveInsideCode) return; m_resolver.setScope(_block.scope()); } bool ReferencesResolver::visit(TryCatchClause const& _tryCatchClause) { if (!m_resolveInsideCode) return false; m_resolver.setScope(&_tryCatchClause); return true; } void ReferencesResolver::endVisit(TryCatchClause const& _tryCatchClause) { if (!m_resolveInsideCode) return; m_resolver.setScope(_tryCatchClause.scope()); } bool ReferencesResolver::visit(ForStatement const& _for) { if (!m_resolveInsideCode) return false; m_resolver.setScope(&_for); return true; } void ReferencesResolver::endVisit(ForStatement const& _for) { if (!m_resolveInsideCode) return; m_resolver.setScope(_for.scope()); } void ReferencesResolver::endVisit(VariableDeclarationStatement const& _varDeclStatement) { if (!m_resolveInsideCode) return; for (auto const& var: _varDeclStatement.declarations()) if (var) m_resolver.activateVariable(var->name()); } bool ReferencesResolver::visit(VariableDeclaration const& _varDecl) { if (_varDecl.documentation()) resolveInheritDoc(*_varDecl.documentation(), _varDecl.annotation()); if (m_resolver.experimentalSolidity()) { solAssert(!_varDecl.hasTypeName()); if (_varDecl.typeExpression()) { ScopedSaveAndRestore typeContext{m_typeContext, true}; _varDecl.typeExpression()->accept(*this); } if (_varDecl.overrides()) _varDecl.overrides()->accept(*this); if (_varDecl.value()) _varDecl.value()->accept(*this); return false; } return true; } bool ReferencesResolver::visit(Identifier const& _identifier) { auto declarations = m_resolver.nameFromCurrentScope(_identifier.name()); if (declarations.empty()) { if (m_resolver.experimentalSolidity() && m_typeContext) return false; std::string suggestions = m_resolver.similarNameSuggestions(_identifier.name()); std::string errorMessage = "Undeclared identifier."; if (!suggestions.empty()) { if ("\"" + _identifier.name() + "\"" == suggestions) errorMessage += " " + std::move(suggestions) + " is not (or not yet) visible at this point."; else errorMessage += " Did you mean " + std::move(suggestions) + "?"; } m_errorReporter.declarationError(7576_error, _identifier.location(), errorMessage); } else if (declarations.size() == 1) _identifier.annotation().referencedDeclaration = declarations.front(); else _identifier.annotation().candidateDeclarations = declarations; return false; } bool ReferencesResolver::visit(FunctionDefinition const& _functionDefinition) { m_functionDefinitions.push_back(&_functionDefinition); if (_functionDefinition.documentation()) resolveInheritDoc(*_functionDefinition.documentation(), _functionDefinition.annotation()); return true; } void ReferencesResolver::endVisit(FunctionDefinition const&) { solAssert(!m_functionDefinitions.empty(), ""); m_functionDefinitions.pop_back(); } bool ReferencesResolver::visit(ModifierDefinition const& _modifierDefinition) { m_functionDefinitions.push_back(nullptr); if (_modifierDefinition.documentation()) resolveInheritDoc(*_modifierDefinition.documentation(), _modifierDefinition.annotation()); return true; } void ReferencesResolver::endVisit(ModifierDefinition const&) { solAssert(!m_functionDefinitions.empty(), ""); m_functionDefinitions.pop_back(); } void ReferencesResolver::endVisit(IdentifierPath const& _path) { // Note that library/functions names in "using {} for" directive are resolved separately in visit(UsingForDirective) std::vector<Declaration const*> declarations = m_resolver.pathFromCurrentScopeWithAllDeclarations(_path.path()); if (declarations.empty()) { m_errorReporter.fatalDeclarationError(7920_error, _path.location(), "Identifier not found or not unique."); return; } _path.annotation().referencedDeclaration = declarations.back(); _path.annotation().pathDeclarations = std::move(declarations); } bool ReferencesResolver::visit(UsingForDirective const& _usingFor) { for (ASTPointer<IdentifierPath> const& path: _usingFor.functionsOrLibrary()) { // _includeInvisibles is enabled here because external library functions are marked invisible. // As unintended side-effects other invisible names (eg.: super, this) may be returned as well. // DeclarationTypeChecker should detect and report such situations. std::vector<Declaration const*> declarations = m_resolver.pathFromCurrentScopeWithAllDeclarations(path->path(), true /* _includeInvisibles */); if (declarations.empty()) { std::string libraryOrFunctionNameErrorMessage = _usingFor.usesBraces() ? "Identifier is not a function name or not unique." : "Identifier is not a library name."; m_errorReporter.fatalDeclarationError( 9589_error, path->location(), libraryOrFunctionNameErrorMessage ); break; } path->annotation().referencedDeclaration = declarations.back(); path->annotation().pathDeclarations = std::move(declarations); } if (_usingFor.typeName()) _usingFor.typeName()->accept(*this); return false; } bool ReferencesResolver::visit(InlineAssembly const& _inlineAssembly) { m_yulAnnotation = &_inlineAssembly.annotation(); (*this)(_inlineAssembly.operations().root()); m_yulAnnotation = nullptr; return false; } bool ReferencesResolver::visit(Return const& _return) { solAssert(!m_functionDefinitions.empty(), ""); _return.annotation().function = m_functionDefinitions.back(); _return.annotation().functionReturnParameters = m_functionDefinitions.back() ? m_functionDefinitions.back()->returnParameterList().get() : nullptr; return true; } bool ReferencesResolver::visit(BinaryOperation const& _binaryOperation) { if (m_resolver.experimentalSolidity()) { _binaryOperation.leftExpression().accept(*this); if (_binaryOperation.getOperator() == Token::Colon) { ScopedSaveAndRestore typeContext(m_typeContext, !m_typeContext); _binaryOperation.rightExpression().accept(*this); } else _binaryOperation.rightExpression().accept(*this); return false; } else return ASTConstVisitor::visit(_binaryOperation); } void ReferencesResolver::operator()(yul::FunctionDefinition const& _function) { solAssert(nativeLocationOf(_function) == originLocationOf(_function), ""); validateYulIdentifierName(_function.name, nativeLocationOf(_function)); for (yul::NameWithDebugData const& varName: _function.parameters + _function.returnVariables) { solAssert(nativeLocationOf(varName) == originLocationOf(varName), ""); validateYulIdentifierName(varName.name, nativeLocationOf(varName)); } bool wasInsideFunction = m_yulInsideFunction; m_yulInsideFunction = true; this->operator()(_function.body); m_yulInsideFunction = wasInsideFunction; } void ReferencesResolver::operator()(yul::Identifier const& _identifier) { solAssert(nativeLocationOf(_identifier) == originLocationOf(_identifier), ""); if (m_resolver.experimentalSolidity()) { std::vector<std::string> splitName; boost::split(splitName, _identifier.name.str(), boost::is_any_of(".")); solAssert(!splitName.empty()); if (splitName.size() > 2) { m_errorReporter.declarationError( 4955_error, nativeLocationOf(_identifier), "Unsupported identifier in inline assembly." ); return; } std::string name = splitName.front(); auto declarations = m_resolver.nameFromCurrentScope(name); switch (declarations.size()) { case 0: if (splitName.size() > 1) m_errorReporter.declarationError( 7531_error, nativeLocationOf(_identifier), "Unsupported identifier in inline assembly." ); break; case 1: m_yulAnnotation->externalReferences[&_identifier].declaration = declarations.front(); m_yulAnnotation->externalReferences[&_identifier].suffix = splitName.size() > 1 ? splitName.back() : ""; break; default: m_errorReporter.declarationError( 5387_error, nativeLocationOf(_identifier), "Multiple matching identifiers. Resolving overloaded identifiers is not supported." ); break; } return; } static std::set<std::string> suffixes{"slot", "offset", "length", "address", "selector"}; std::string suffix; for (std::string const& s: suffixes) if (boost::algorithm::ends_with(_identifier.name.str(), "." + s)) suffix = s; // Could also use `pathFromCurrentScope`, split by '.'. // If we do that, suffix should only be set for when it has a special // meaning, not for normal identifierPaths. auto declarations = m_resolver.nameFromCurrentScope(_identifier.name.str()); if (!suffix.empty()) { // special mode to access storage variables if (!declarations.empty()) // the special identifier exists itself, we should not allow that. return; std::string realName = _identifier.name.str().substr(0, _identifier.name.str().size() - suffix.size() - 1); solAssert(!realName.empty(), "Empty name."); declarations = m_resolver.nameFromCurrentScope(realName); if (!declarations.empty()) // To support proper path resolution, we have to use pathFromCurrentScope. solAssert(!util::contains(realName, '.'), ""); } if (declarations.size() > 1) { m_errorReporter.declarationError( 4718_error, nativeLocationOf(_identifier), "Multiple matching identifiers. Resolving overloaded identifiers is not supported." ); return; } else if (declarations.size() == 0) { if ( boost::algorithm::ends_with(_identifier.name.str(), "_slot") || boost::algorithm::ends_with(_identifier.name.str(), "_offset") ) m_errorReporter.declarationError( 9467_error, nativeLocationOf(_identifier), "Identifier not found. Use \".slot\" and \".offset\" to access storage or transient storage variables." ); return; } if (auto var = dynamic_cast<VariableDeclaration const*>(declarations.front())) if (var->isLocalVariable() && m_yulInsideFunction) { m_errorReporter.declarationError( 6578_error, nativeLocationOf(_identifier), "Cannot access local Solidity variables from inside an inline assembly function." ); return; } m_yulAnnotation->externalReferences[&_identifier].suffix = std::move(suffix); m_yulAnnotation->externalReferences[&_identifier].declaration = declarations.front(); } void ReferencesResolver::operator()(yul::VariableDeclaration const& _varDecl) { for (auto const& identifier: _varDecl.variables) { solAssert(nativeLocationOf(identifier) == originLocationOf(identifier), ""); validateYulIdentifierName(identifier.name, nativeLocationOf(identifier)); if ( auto declarations = m_resolver.nameFromCurrentScope(identifier.name.str()); !declarations.empty() ) { SecondarySourceLocation ssl; for (auto const* decl: declarations) ssl.append("The shadowed declaration is here:", decl->location()); if (!ssl.infos.empty()) m_errorReporter.declarationError( 3859_error, nativeLocationOf(identifier), ssl, "This declaration shadows a declaration outside the inline assembly block." ); } } if (_varDecl.value) visit(*_varDecl.value); } void ReferencesResolver::resolveInheritDoc(StructuredDocumentation const& _documentation, StructurallyDocumentedAnnotation& _annotation) { switch (_annotation.docTags.count("inheritdoc")) { case 0: break; case 1: { std::string const& name = _annotation.docTags.find("inheritdoc")->second.content; if (name.empty()) { m_errorReporter.docstringParsingError( 1933_error, _documentation.location(), "Expected contract name following documentation tag @inheritdoc." ); return; } std::vector<std::string> path; boost::split(path, name, boost::is_any_of(".")); if (any_of(path.begin(), path.end(), [](auto& _str) { return _str.empty(); })) { m_errorReporter.docstringParsingError( 5967_error, _documentation.location(), "Documentation tag @inheritdoc reference \"" + name + "\" is malformed." ); return; } Declaration const* result = m_resolver.pathFromCurrentScope(path); if (result == nullptr) { m_errorReporter.docstringParsingError( 9397_error, _documentation.location(), "Documentation tag @inheritdoc references inexistent contract \"" + name + "\"." ); return; } else { _annotation.inheritdocReference = dynamic_cast<ContractDefinition const*>(result); if (!_annotation.inheritdocReference) m_errorReporter.docstringParsingError( 1430_error, _documentation.location(), "Documentation tag @inheritdoc reference \"" + name + "\" is not a contract." ); } break; } default: m_errorReporter.docstringParsingError( 5142_error, _documentation.location(), "Documentation tag @inheritdoc can only be given once." ); break; } } void ReferencesResolver::validateYulIdentifierName(yul::YulName _name, SourceLocation const& _location) { if (util::contains(_name.str(), '.')) m_errorReporter.declarationError( 3927_error, _location, "User-defined identifiers in inline assembly cannot contain '.'." ); if (std::set<std::string>{"this", "super", "_"}.count(_name.str())) m_errorReporter.declarationError( 4113_error, _location, "The identifier name \"" + _name.str() + "\" is reserved." ); }
14,969
C++
.cpp
448
30.571429
148
0.750259
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
3,206
ImmutableValidator.cpp
ethereum_solidity/libsolidity/analysis/ImmutableValidator.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libsolidity/analysis/ImmutableValidator.h> #include <range/v3/view/reverse.hpp> using namespace solidity::frontend; using namespace solidity::langutil; void ImmutableValidator::analyze() { auto linearizedContracts = m_mostDerivedContract.annotation().linearizedBaseContracts | ranges::views::reverse; for (ContractDefinition const* contract: linearizedContracts) { for (FunctionDefinition const* function: contract->definedFunctions()) function->accept(*this); for (ModifierDefinition const* modifier: contract->functionModifiers()) modifier->accept(*this); } } bool ImmutableValidator::visit(FunctionDefinition const& _functionDefinition) { return !_functionDefinition.isConstructor(); } void ImmutableValidator::endVisit(MemberAccess const& _memberAccess) { analyseVariableReference(_memberAccess.annotation().referencedDeclaration, _memberAccess); } void ImmutableValidator::endVisit(Identifier const& _identifier) { analyseVariableReference(_identifier.annotation().referencedDeclaration, _identifier); } void ImmutableValidator::analyseVariableReference(Declaration const* _reference, Expression const& _expression) { auto const* variable = dynamic_cast<VariableDeclaration const*>(_reference); if (!variable || !variable->isStateVariable() || !variable->immutable()) return; // If this is not an ordinary assignment, we write and read at the same time. if (_expression.annotation().willBeWrittenTo) m_errorReporter.typeError( 1581_error, _expression.location(), "Cannot write to immutable here: Immutable variables can only be initialized inline or assigned directly in the constructor." ); }
2,341
C++
.cpp
54
41.222222
128
0.802464
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,208
Scoper.cpp
ethereum_solidity/libsolidity/analysis/Scoper.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libsolidity/analysis/Scoper.h> #include <libsolidity/ast/AST.h> using namespace solidity; using namespace solidity::frontend; void Scoper::assignScopes(ASTNode const& _astRoot) { Scoper scoper; _astRoot.accept(scoper); } bool Scoper::visit(ContractDefinition const& _contract) { solAssert(m_contract == nullptr, ""); m_contract = &_contract; return ASTConstVisitor::visit(_contract); } void Scoper::endVisit(ContractDefinition const& _contract) { solAssert(m_contract == &_contract, ""); m_contract = nullptr; ASTConstVisitor::endVisit(_contract); } bool Scoper::visitNode(ASTNode const& _node) { if (auto const* scopable = dynamic_cast<Scopable const*>(&_node)) { scopable->annotation().scope = m_scopes.empty() ? nullptr : m_scopes.back(); scopable->annotation().contract = m_contract; } if (dynamic_cast<ScopeOpener const*>(&_node)) m_scopes.push_back(&_node); return true; } void Scoper::endVisitNode(ASTNode const& _node) { if (dynamic_cast<ScopeOpener const*>(&_node)) m_scopes.pop_back(); }
1,723
C++
.cpp
51
31.921569
78
0.7646
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
3,209
ConstantEvaluator.cpp
ethereum_solidity/libsolidity/analysis/ConstantEvaluator.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 /** * @author Christian <c@ethdev.com> * @date 2015 * Evaluator for types of constant expressions. */ #include <libsolidity/analysis/ConstantEvaluator.h> #include <libsolidity/ast/AST.h> #include <libsolidity/ast/TypeProvider.h> #include <liblangutil/ErrorReporter.h> #include <limits> using namespace solidity; using namespace solidity::frontend; using namespace solidity::langutil; using TypedRational = ConstantEvaluator::TypedRational; namespace { /// Check whether (_base ** _exp) fits into 4096 bits. bool fitsPrecisionExp(bigint const& _base, bigint const& _exp) { if (_base == 0) return true; solAssert(_base > 0, ""); std::size_t const bitsMax = 4096; std::size_t mostSignificantBaseBit = static_cast<std::size_t>(boost::multiprecision::msb(_base)); if (mostSignificantBaseBit == 0) // _base == 1 return true; if (mostSignificantBaseBit > bitsMax) // _base >= 2 ^ 4096 return false; bigint bitsNeeded = _exp * (mostSignificantBaseBit + 1); return bitsNeeded <= bitsMax; } /// Checks whether _mantissa * (2 ** _expBase10) fits into 4096 bits. bool fitsPrecisionBase2(bigint const& _mantissa, uint32_t _expBase2) { return fitsPrecisionBaseX(_mantissa, 1.0, _expBase2); } } std::optional<rational> ConstantEvaluator::evaluateBinaryOperator(Token _operator, rational const& _left, rational const& _right) { bool fractional = _left.denominator() != 1 || _right.denominator() != 1; switch (_operator) { //bit operations will only be enabled for integers and fixed types that resemble integers case Token::BitOr: if (fractional) return std::nullopt; else return _left.numerator() | _right.numerator(); case Token::BitXor: if (fractional) return std::nullopt; else return _left.numerator() ^ _right.numerator(); case Token::BitAnd: if (fractional) return std::nullopt; else return _left.numerator() & _right.numerator(); case Token::Add: return _left + _right; case Token::Sub: return _left - _right; case Token::Mul: return _left * _right; case Token::Div: if (_right == rational(0)) return std::nullopt; else return _left / _right; case Token::Mod: if (_right == rational(0)) return std::nullopt; else if (fractional) { rational tempValue = _left / _right; return _left - (tempValue.numerator() / tempValue.denominator()) * _right; } else return _left.numerator() % _right.numerator(); break; case Token::Exp: { if (_right.denominator() != 1) return std::nullopt; bigint const& exp = _right.numerator(); // x ** 0 = 1 // for 0, 1 and -1 the size of the exponent doesn't have to be restricted if (exp == 0) return 1; else if (_left == 0 || _left == 1) return _left; else if (_left == -1) { bigint isOdd = abs(exp) & bigint(1); return 1 - 2 * isOdd.convert_to<int>(); } else { if (abs(exp) > std::numeric_limits<uint32_t>::max()) return std::nullopt; // This will need too much memory to represent. uint32_t absExp = bigint(abs(exp)).convert_to<uint32_t>(); if (!fitsPrecisionExp(abs(_left.numerator()), absExp) || !fitsPrecisionExp(abs(_left.denominator()), absExp)) return std::nullopt; static auto const optimizedPow = [](bigint const& _base, uint32_t _exponent) -> bigint { if (_base == 1) return 1; else if (_base == -1) return 1 - 2 * static_cast<int>(_exponent & 1); else return boost::multiprecision::pow(_base, _exponent); }; bigint numerator = optimizedPow(_left.numerator(), absExp); bigint denominator = optimizedPow(_left.denominator(), absExp); if (exp >= 0) return makeRational(numerator, denominator); else // invert return makeRational(denominator, numerator); } break; } case Token::SHL: { if (fractional) return std::nullopt; else if (_right < 0) return std::nullopt; else if (_right > std::numeric_limits<uint32_t>::max()) return std::nullopt; if (_left.numerator() == 0) return 0; else { uint32_t exponent = _right.numerator().convert_to<uint32_t>(); if (!fitsPrecisionBase2(abs(_left.numerator()), exponent)) return std::nullopt; return _left.numerator() * boost::multiprecision::pow(bigint(2), exponent); } break; } // NOTE: we're using >> (SAR) to denote right shifting. The type of the LValue // determines the resulting type and the type of shift (SAR or SHR). case Token::SAR: { if (fractional) return std::nullopt; else if (_right < 0) return std::nullopt; else if (_right > std::numeric_limits<uint32_t>::max()) return std::nullopt; if (_left.numerator() == 0) return 0; else { uint32_t exponent = _right.numerator().convert_to<uint32_t>(); if (exponent > boost::multiprecision::msb(boost::multiprecision::abs(_left.numerator()))) return _left.numerator() < 0 ? -1 : 0; else { if (_left.numerator() < 0) // Add 1 to the negative value before dividing to get a result that is strictly too large, // then subtract 1 afterwards to round towards negative infinity. // This is the same algorithm as used in ExpressionCompiler::appendShiftOperatorCode(...). // To see this note that for negative x, xor(x,all_ones) = (-x-1) and // therefore xor(div(xor(x,all_ones), exp(2, shift_amount)), all_ones) is // -(-x - 1) / 2^shift_amount - 1, which is the same as // (x + 1) / 2^shift_amount - 1. return rational((_left.numerator() + 1) / boost::multiprecision::pow(bigint(2), exponent) - bigint(1), 1); else return rational(_left.numerator() / boost::multiprecision::pow(bigint(2), exponent), 1); } } break; } default: return std::nullopt; } } std::optional<rational> ConstantEvaluator::evaluateUnaryOperator(Token _operator, rational const& _input) { switch (_operator) { case Token::BitNot: if (_input.denominator() != 1) return std::nullopt; else return ~_input.numerator(); case Token::Sub: return -_input; default: return std::nullopt; } } namespace { std::optional<TypedRational> convertType(rational const& _value, Type const& _type) { if (_type.category() == Type::Category::RationalNumber) return TypedRational{TypeProvider::rationalNumber(_value), _value}; else if (auto const* integerType = dynamic_cast<IntegerType const*>(&_type)) { if (_value > integerType->maxValue() || _value < integerType->minValue()) return std::nullopt; else return TypedRational{&_type, _value.numerator() / _value.denominator()}; } else return std::nullopt; } std::optional<TypedRational> convertType(std::optional<TypedRational> const& _value, Type const& _type) { return _value ? convertType(_value->value, _type) : std::nullopt; } std::optional<TypedRational> constantToTypedValue(Type const& _type) { if (_type.category() == Type::Category::RationalNumber) return TypedRational{&_type, dynamic_cast<RationalNumberType const&>(_type).value()}; else return std::nullopt; } } std::optional<TypedRational> ConstantEvaluator::evaluate( langutil::ErrorReporter& _errorReporter, Expression const& _expr ) { return ConstantEvaluator{_errorReporter}.evaluate(_expr); } std::optional<TypedRational> ConstantEvaluator::evaluate(ASTNode const& _node) { if (!m_values.count(&_node)) { if (auto const* varDecl = dynamic_cast<VariableDeclaration const*>(&_node)) { solAssert(varDecl->isConstant(), ""); // In some circumstances, we do not yet have a type for the variable. if (!varDecl->value() || !varDecl->type()) m_values[&_node] = std::nullopt; else { m_depth++; if (m_depth > 32) m_errorReporter.fatalTypeError( 5210_error, varDecl->location(), "Cyclic constant definition (or maximum recursion depth exhausted)." ); m_values[&_node] = convertType(evaluate(*varDecl->value()), *varDecl->type()); m_depth--; } } else if (auto const* expression = dynamic_cast<Expression const*>(&_node)) { expression->accept(*this); if (!m_values.count(&_node)) m_values[&_node] = std::nullopt; } } return m_values.at(&_node); } void ConstantEvaluator::endVisit(UnaryOperation const& _operation) { std::optional<TypedRational> value = evaluate(_operation.subExpression()); if (!value) return; Type const* resultType = value->type->unaryOperatorResult(_operation.getOperator()); if (!resultType) return; value = convertType(value, *resultType); if (!value) return; if (std::optional<rational> result = evaluateUnaryOperator(_operation.getOperator(), value->value)) { std::optional<TypedRational> convertedValue = convertType(*result, *resultType); if (!convertedValue) m_errorReporter.fatalTypeError( 3667_error, _operation.location(), "Arithmetic error when computing constant value." ); m_values[&_operation] = convertedValue; } } void ConstantEvaluator::endVisit(BinaryOperation const& _operation) { std::optional<TypedRational> left = evaluate(_operation.leftExpression()); std::optional<TypedRational> right = evaluate(_operation.rightExpression()); if (!left || !right) return; // If this is implemented in the future: Comparison operators have a "binaryOperatorResult" // that is non-bool, but the result has to be bool. if (TokenTraits::isCompareOp(_operation.getOperator())) return; Type const* resultType = left->type->binaryOperatorResult(_operation.getOperator(), right->type); if (!resultType) { m_errorReporter.fatalTypeError( 6020_error, _operation.location(), "Operator " + std::string(TokenTraits::toString(_operation.getOperator())) + " not compatible with types " + left->type->toString() + " and " + right->type->toString() ); return; } left = convertType(left, *resultType); right = convertType(right, *resultType); if (!left || !right) return; if (std::optional<rational> value = evaluateBinaryOperator(_operation.getOperator(), left->value, right->value)) { std::optional<TypedRational> convertedValue = convertType(*value, *resultType); if (!convertedValue) m_errorReporter.fatalTypeError( 2643_error, _operation.location(), "Arithmetic error when computing constant value." ); m_values[&_operation] = convertedValue; } } void ConstantEvaluator::endVisit(Literal const& _literal) { if (Type const* literalType = TypeProvider::forLiteral(_literal)) m_values[&_literal] = constantToTypedValue(*literalType); } void ConstantEvaluator::endVisit(Identifier const& _identifier) { VariableDeclaration const* variableDeclaration = dynamic_cast<VariableDeclaration const*>(_identifier.annotation().referencedDeclaration); if (variableDeclaration && variableDeclaration->isConstant()) m_values[&_identifier] = evaluate(*variableDeclaration); } void ConstantEvaluator::endVisit(TupleExpression const& _tuple) { if (!_tuple.isInlineArray() && _tuple.components().size() == 1) m_values[&_tuple] = evaluate(*_tuple.components().front()); }
11,598
C++
.cpp
351
30.082621
139
0.709899
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
3,210
DeclarationContainer.cpp
ethereum_solidity/libsolidity/analysis/DeclarationContainer.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 /** * @author Christian <c@ethdev.com> * @date 2014 * Scope - object that holds declaration of names. */ #include <libsolidity/analysis/DeclarationContainer.h> #include <libsolidity/ast/AST.h> #include <libsolutil/StringUtils.h> #include <range/v3/view/filter.hpp> #include <range/v3/range/conversion.hpp> using namespace solidity; using namespace solidity::frontend; Declaration const* DeclarationContainer::conflictingDeclaration( Declaration const& _declaration, ASTString const* _name ) const { if (!_name) _name = &_declaration.name(); solAssert(!_name->empty(), ""); std::vector<Declaration const*> declarations; if (m_declarations.count(*_name)) declarations += m_declarations.at(*_name); if (m_invisibleDeclarations.count(*_name)) declarations += m_invisibleDeclarations.at(*_name); if ( dynamic_cast<FunctionDefinition const*>(&_declaration) || dynamic_cast<EventDefinition const*>(&_declaration) || dynamic_cast<MagicVariableDeclaration const*>(&_declaration) ) { // check that all other declarations are of the same kind (in which // case the type checker will ensure that the signatures are different) for (Declaration const* declaration: declarations) { if ( dynamic_cast<FunctionDefinition const*>(&_declaration) && !dynamic_cast<FunctionDefinition const*>(declaration) ) return declaration; if ( dynamic_cast<EventDefinition const*>(&_declaration) && !dynamic_cast<EventDefinition const*>(declaration) ) return declaration; if ( dynamic_cast<MagicVariableDeclaration const*>(&_declaration) && !dynamic_cast<MagicVariableDeclaration const*>(declaration) ) return declaration; // Or, continue. } } else if (declarations.size() == 1 && declarations.front() == &_declaration) return nullptr; else if (!declarations.empty()) return declarations.front(); return nullptr; } void DeclarationContainer::activateVariable(ASTString const& _name) { solAssert( m_invisibleDeclarations.count(_name) && m_invisibleDeclarations.at(_name).size() == 1, "Tried to activate a non-inactive variable or multiple inactive variables with the same name." ); solAssert(m_declarations.count(_name) == 0 || m_declarations.at(_name).empty(), ""); m_declarations[_name].emplace_back(m_invisibleDeclarations.at(_name).front()); m_invisibleDeclarations.erase(_name); } bool DeclarationContainer::isInvisible(ASTString const& _name) const { return m_invisibleDeclarations.count(_name); } bool DeclarationContainer::registerDeclaration( Declaration const& _declaration, ASTString const* _name, langutil::SourceLocation const* _location, bool _invisible, bool _update ) { if (!_name) _name = &_declaration.name(); if (_name->empty()) return true; if (_update) { solAssert(!dynamic_cast<FunctionDefinition const*>(&_declaration), "Attempt to update function definition."); m_declarations.erase(*_name); m_invisibleDeclarations.erase(*_name); } else { if (conflictingDeclaration(_declaration, _name)) return false; if (m_enclosingContainer && _declaration.isVisibleAsUnqualifiedName()) m_homonymCandidates.emplace_back(*_name, _location ? _location : &_declaration.location()); } std::vector<Declaration const*>& decls = _invisible ? m_invisibleDeclarations[*_name] : m_declarations[*_name]; if (!util::contains(decls, &_declaration)) decls.push_back(&_declaration); return true; } bool DeclarationContainer::registerDeclaration( Declaration const& _declaration, bool _invisible, bool _update ) { return registerDeclaration(_declaration, nullptr, nullptr, _invisible, _update); } std::vector<Declaration const*> DeclarationContainer::resolveName( ASTString const& _name, ResolvingSettings _settings ) const { solAssert(!_name.empty(), "Attempt to resolve empty name."); std::vector<Declaration const*> result; if (m_declarations.count(_name)) { if (_settings.onlyVisibleAsUnqualifiedNames) result += m_declarations.at(_name) | ranges::views::filter(&Declaration::isVisibleAsUnqualifiedName) | ranges::to_vector; else result += m_declarations.at(_name); } if (_settings.alsoInvisible && m_invisibleDeclarations.count(_name)) { if (_settings.onlyVisibleAsUnqualifiedNames) result += m_invisibleDeclarations.at(_name) | ranges::views::filter(&Declaration::isVisibleAsUnqualifiedName) | ranges::to_vector; else result += m_invisibleDeclarations.at(_name); } if (result.empty() && _settings.recursive && m_enclosingContainer) result = m_enclosingContainer->resolveName(_name, _settings); return result; } std::vector<ASTString> DeclarationContainer::similarNames(ASTString const& _name) const { // because the function below has quadratic runtime - it will not magically improve once a better algorithm is discovered ;) // since 80 is the suggested line length limit, we use 80^2 as length threshold static size_t const MAXIMUM_LENGTH_THRESHOLD = 80 * 80; std::vector<ASTString> similar; size_t maximumEditDistance = _name.size() > 3 ? 2 : _name.size() / 2; for (auto const& declaration: m_declarations) { std::string const& declarationName = declaration.first; if (util::stringWithinDistance(_name, declarationName, maximumEditDistance, MAXIMUM_LENGTH_THRESHOLD)) similar.push_back(declarationName); } for (auto const& declaration: m_invisibleDeclarations) { std::string const& declarationName = declaration.first; if (util::stringWithinDistance(_name, declarationName, maximumEditDistance, MAXIMUM_LENGTH_THRESHOLD)) similar.push_back(declarationName); } if (m_enclosingContainer) similar += m_enclosingContainer->similarNames(_name); return similar; } void DeclarationContainer::populateHomonyms(std::back_insert_iterator<Homonyms> _it) const { for (DeclarationContainer const* innerContainer: m_innerContainers) innerContainer->populateHomonyms(_it); for (auto [name, location]: m_homonymCandidates) { ResolvingSettings settings; settings.recursive = true; settings.alsoInvisible = true; std::vector<Declaration const*> const& declarations = m_enclosingContainer->resolveName(name, std::move(settings)); if (!declarations.empty()) _it = make_pair(location, declarations); } }
6,899
C++
.cpp
187
34.42246
133
0.762981
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
3,211
NameAndTypeResolver.cpp
ethereum_solidity/libsolidity/analysis/NameAndTypeResolver.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 /** * @author Christian <c@ethdev.com> * @date 2014 * Parser part that determines the declarations corresponding to names and the types of expressions. */ #include <libsolidity/analysis/NameAndTypeResolver.h> #include <libsolidity/analysis/TypeChecker.h> #include <libsolidity/ast/AST.h> #include <liblangutil/ErrorReporter.h> #include <libsolutil/StringUtils.h> #include <boost/algorithm/string.hpp> #include <unordered_set> using namespace std::string_literals; using namespace solidity::langutil; namespace solidity::frontend { NameAndTypeResolver::NameAndTypeResolver( GlobalContext& _globalContext, langutil::EVMVersion _evmVersion, ErrorReporter& _errorReporter, bool _experimentalSolidity ): m_evmVersion(_evmVersion), m_errorReporter(_errorReporter), m_globalContext(_globalContext), m_experimentalSolidity(_experimentalSolidity) { m_scopes[nullptr] = std::make_shared<DeclarationContainer>(); for (Declaration const* declaration: _globalContext.declarations()) { solAssert(m_scopes[nullptr]->registerDeclaration(*declaration, false, false), "Unable to register global declaration."); } } bool NameAndTypeResolver::registerDeclarations(SourceUnit& _sourceUnit, ASTNode const* _currentScope) { // The helper registers all declarations in m_scopes as a side-effect of its construction. try { DeclarationRegistrationHelper registrar(m_scopes, _sourceUnit, m_errorReporter, m_globalContext, _currentScope); } catch (langutil::FatalError const& error) { solAssert(m_errorReporter.hasErrors(), "Unreported fatal error: "s + error.what()); return false; } return true; } bool NameAndTypeResolver::performImports(SourceUnit& _sourceUnit, std::map<std::string, SourceUnit const*> const& _sourceUnits) { DeclarationContainer& target = *m_scopes.at(&_sourceUnit); bool error = false; for (auto const& node: _sourceUnit.nodes()) if (auto imp = dynamic_cast<ImportDirective const*>(node.get())) { std::string const& path = *imp->annotation().absolutePath; // The import resolution in CompilerStack enforces this. solAssert(_sourceUnits.count(path), ""); auto scope = m_scopes.find(_sourceUnits.at(path)); solAssert(scope != end(m_scopes), ""); if (!imp->symbolAliases().empty()) for (auto const& alias: imp->symbolAliases()) { auto declarations = scope->second->resolveName(alias.symbol->name()); if (declarations.empty()) { m_errorReporter.declarationError( 2904_error, imp->location(), "Declaration \"" + alias.symbol->name() + "\" not found in \"" + path + "\" (referenced as \"" + imp->path() + "\")." ); error = true; } else for (Declaration const* declaration: declarations) if (!DeclarationRegistrationHelper::registerDeclaration( target, *declaration, alias.alias ? alias.alias.get() : &alias.symbol->name(), &alias.location, false, m_errorReporter )) error = true; } else if (imp->name().empty()) for (auto const& nameAndDeclaration: scope->second->declarations()) for (auto const& declaration: nameAndDeclaration.second) if (!DeclarationRegistrationHelper::registerDeclaration( target, *declaration, &nameAndDeclaration.first, &imp->location(), false, m_errorReporter )) error = true; } _sourceUnit.annotation().exportedSymbols = m_scopes[&_sourceUnit]->declarations(); return !error; } bool NameAndTypeResolver::resolveNamesAndTypes(SourceUnit& _source) { try { for (std::shared_ptr<ASTNode> const& node: _source.nodes()) { setScope(&_source); if (!resolveNamesAndTypesInternal(*node, true)) return false; } } catch (langutil::FatalError const& error) { solAssert(m_errorReporter.hasErrors(), "Unreported fatal error: "s + error.what()); return false; } return true; } bool NameAndTypeResolver::updateDeclaration(Declaration const& _declaration) { try { m_scopes[nullptr]->registerDeclaration(_declaration, false, true); solAssert(_declaration.scope() == nullptr, "Updated declaration outside global scope."); } catch (langutil::FatalError const& error) { solAssert(m_errorReporter.hasErrors(), "Unreported fatal error: "s + error.what()); return false; } return true; } void NameAndTypeResolver::activateVariable(std::string const& _name) { solAssert(m_currentScope, ""); // Scoped local variables are invisible before activation. // When a local variable is activated, its name is removed // from a scope's invisible variables. // This is used to avoid activation of variables of same name // in the same scope (an error is returned). if (m_currentScope->isInvisible(_name)) m_currentScope->activateVariable(_name); } std::vector<Declaration const*> NameAndTypeResolver::resolveName(ASTString const& _name, ASTNode const* _scope) const { auto iterator = m_scopes.find(_scope); if (iterator == end(m_scopes)) return std::vector<Declaration const*>({}); return iterator->second->resolveName(_name); } std::vector<Declaration const*> NameAndTypeResolver::nameFromCurrentScope(ASTString const& _name, bool _includeInvisibles) const { ResolvingSettings settings; settings.recursive = true; settings.alsoInvisible = _includeInvisibles; return m_currentScope->resolveName(_name, std::move(settings)); } Declaration const* NameAndTypeResolver::pathFromCurrentScope(std::vector<ASTString> const& _path) const { if (auto declarations = pathFromCurrentScopeWithAllDeclarations(_path); !declarations.empty()) return declarations.back(); return nullptr; } std::vector<Declaration const*> NameAndTypeResolver::pathFromCurrentScopeWithAllDeclarations( std::vector<ASTString> const& _path, bool _includeInvisibles ) const { solAssert(!_path.empty(), ""); std::vector<Declaration const*> pathDeclarations; ResolvingSettings settings; settings.recursive = true; settings.alsoInvisible = _includeInvisibles; settings.onlyVisibleAsUnqualifiedNames = true; std::vector<Declaration const*> candidates = m_currentScope->resolveName(_path.front(), settings); // inside the loop, use default settings, except for alsoInvisible settings.recursive = false; settings.onlyVisibleAsUnqualifiedNames = false; for (size_t i = 1; i < _path.size() && candidates.size() == 1; i++) { if (!m_scopes.count(candidates.front())) return {}; pathDeclarations.push_back(candidates.front()); candidates = m_scopes.at(candidates.front())->resolveName(_path[i], settings); } if (candidates.size() == 1) { pathDeclarations.push_back(candidates.front()); return pathDeclarations; } else return {}; } void NameAndTypeResolver::warnHomonymDeclarations() const { DeclarationContainer::Homonyms homonyms; m_scopes.at(nullptr)->populateHomonyms(back_inserter(homonyms)); for (auto [innerLocation, outerDeclarations]: homonyms) { solAssert(innerLocation && !outerDeclarations.empty(), ""); bool magicShadowed = false; SecondarySourceLocation homonymousLocations; SecondarySourceLocation shadowedLocations; for (Declaration const* outerDeclaration: outerDeclarations) { solAssert(outerDeclaration, ""); if (dynamic_cast<MagicVariableDeclaration const*>(outerDeclaration)) magicShadowed = true; else if (!outerDeclaration->isVisibleInContract()) homonymousLocations.append("The other declaration is here:", outerDeclaration->location()); else shadowedLocations.append("The shadowed declaration is here:", outerDeclaration->location()); } if (magicShadowed) m_errorReporter.warning( 2319_error, *innerLocation, "This declaration shadows a builtin symbol." ); if (!homonymousLocations.infos.empty()) m_errorReporter.warning( 8760_error, *innerLocation, "This declaration has the same name as another declaration.", homonymousLocations ); if (!shadowedLocations.infos.empty()) m_errorReporter.warning( 2519_error, *innerLocation, "This declaration shadows an existing declaration.", shadowedLocations ); } } void NameAndTypeResolver::setScope(ASTNode const* _node) { m_currentScope = m_scopes[_node].get(); } bool NameAndTypeResolver::resolveNamesAndTypesInternal(ASTNode& _node, bool _resolveInsideCode) { if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(&_node)) { bool success = true; setScope(contract->scope()); solAssert(!!m_currentScope, ""); solAssert(_resolveInsideCode, ""); m_globalContext.setCurrentContract(*contract); if (!contract->isLibrary()) updateDeclaration(*m_globalContext.currentSuper()); updateDeclaration(*m_globalContext.currentThis()); for (ASTPointer<InheritanceSpecifier> const& baseContract: contract->baseContracts()) if (!resolveNamesAndTypesInternal(*baseContract, true)) success = false; setScope(contract); if (success) { linearizeBaseContracts(*contract); std::vector<ContractDefinition const*> properBases( ++contract->annotation().linearizedBaseContracts.begin(), contract->annotation().linearizedBaseContracts.end() ); for (ContractDefinition const* base: properBases) importInheritedScope(*base); } // these can contain code, only resolve parameters for now for (ASTPointer<ASTNode> const& node: contract->subNodes()) { setScope(contract); if (!resolveNamesAndTypesInternal(*node, false)) success = false; } if (!success) return false; setScope(contract); // now resolve references inside the code for (ASTPointer<ASTNode> const& node: contract->subNodes()) { setScope(contract); if (!resolveNamesAndTypesInternal(*node, true)) success = false; } // make "this" and "super" invisible. m_scopes[nullptr]->registerDeclaration(*m_globalContext.currentThis(), true, true); m_scopes[nullptr]->registerDeclaration(*m_globalContext.currentSuper(), true, true); m_globalContext.resetCurrentContract(); return success; } else { if (m_scopes.count(&_node)) setScope(&_node); return ReferencesResolver(m_errorReporter, *this, m_evmVersion, _resolveInsideCode).resolve(_node); } } void NameAndTypeResolver::importInheritedScope(ContractDefinition const& _base) { auto iterator = m_scopes.find(&_base); solAssert(iterator != end(m_scopes), ""); for (auto const& nameAndDeclaration: iterator->second->declarations()) for (auto const& declaration: nameAndDeclaration.second) // Import if it was declared in the base, is not the constructor and is visible in derived classes if (declaration->scope() == &_base && declaration->isVisibleInDerivedContracts()) if (!m_currentScope->registerDeclaration(*declaration, false, false)) { SourceLocation firstDeclarationLocation; SourceLocation secondDeclarationLocation; Declaration const* conflictingDeclaration = m_currentScope->conflictingDeclaration(*declaration); solAssert(conflictingDeclaration, ""); // Usual shadowing is not an error if ( dynamic_cast<ModifierDefinition const*>(declaration) && dynamic_cast<ModifierDefinition const*>(conflictingDeclaration) ) continue; // Public state variable can override functions if (auto varDecl = dynamic_cast<VariableDeclaration const*>(conflictingDeclaration)) if ( dynamic_cast<FunctionDefinition const*>(declaration) && varDecl->isStateVariable() && varDecl->isPublic() ) continue; if (declaration->location().start < conflictingDeclaration->location().start) { firstDeclarationLocation = declaration->location(); secondDeclarationLocation = conflictingDeclaration->location(); } else { firstDeclarationLocation = conflictingDeclaration->location(); secondDeclarationLocation = declaration->location(); } m_errorReporter.declarationError( 9097_error, secondDeclarationLocation, SecondarySourceLocation().append("The previous declaration is here:", firstDeclarationLocation), "Identifier already declared." ); } } void NameAndTypeResolver::linearizeBaseContracts(ContractDefinition& _contract) { // order in the lists is from derived to base // list of lists to linearize, the last element is the list of direct bases std::list<std::list<ContractDefinition const*>> input(1, std::list<ContractDefinition const*>{}); for (ASTPointer<InheritanceSpecifier> const& baseSpecifier: _contract.baseContracts()) { IdentifierPath const& baseName = baseSpecifier->name(); auto base = dynamic_cast<ContractDefinition const*>(baseName.annotation().referencedDeclaration); if (!base) m_errorReporter.fatalTypeError(8758_error, baseName.location(), "Contract expected."); // "push_front" has the effect that bases mentioned later can overwrite members of bases // mentioned earlier input.back().push_front(base); std::vector<ContractDefinition const*> const& basesBases = base->annotation().linearizedBaseContracts; if (basesBases.empty()) m_errorReporter.fatalTypeError(2449_error, baseName.location(), "Definition of base has to precede definition of derived contract"); input.push_front(std::list<ContractDefinition const*>(basesBases.begin(), basesBases.end())); } input.back().push_front(&_contract); std::vector<ContractDefinition const*> result = cThreeMerge(input); if (result.empty()) m_errorReporter.fatalTypeError(5005_error, _contract.location(), "Linearization of inheritance graph impossible"); _contract.annotation().linearizedBaseContracts = result; } template <class T> std::vector<T const*> NameAndTypeResolver::cThreeMerge(std::list<std::list<T const*>>& _toMerge) { // returns true iff _candidate appears only as last element of the lists auto appearsOnlyAtHead = [&](T const* _candidate) -> bool { for (std::list<T const*> const& bases: _toMerge) { solAssert(!bases.empty(), ""); if (find(++bases.begin(), bases.end(), _candidate) != bases.end()) return false; } return true; }; // returns the next candidate to append to the linearized list or nullptr on failure auto nextCandidate = [&]() -> T const* { for (std::list<T const*> const& bases: _toMerge) { solAssert(!bases.empty(), ""); if (appearsOnlyAtHead(bases.front())) return bases.front(); } return nullptr; }; // removes the given contract from all lists auto removeCandidate = [&](T const* _candidate) { for (auto it = _toMerge.begin(); it != _toMerge.end();) { it->remove(_candidate); if (it->empty()) it = _toMerge.erase(it); else ++it; } }; _toMerge.remove_if([](std::list<T const*> const& _bases) { return _bases.empty(); }); std::vector<T const*> result; while (!_toMerge.empty()) { T const* candidate = nextCandidate(); if (!candidate) return std::vector<T const*>(); result.push_back(candidate); removeCandidate(candidate); } return result; } std::string NameAndTypeResolver::similarNameSuggestions(ASTString const& _name) const { return util::quotedAlternativesList(m_currentScope->similarNames(_name)); } DeclarationRegistrationHelper::DeclarationRegistrationHelper( std::map<ASTNode const*, std::shared_ptr<DeclarationContainer>>& _scopes, ASTNode& _astRoot, ErrorReporter& _errorReporter, GlobalContext& _globalContext, ASTNode const* _currentScope ): m_scopes(_scopes), m_currentScope(_currentScope), m_errorReporter(_errorReporter), m_globalContext(_globalContext) { _astRoot.accept(*this); solAssert(m_currentScope == _currentScope, "Scopes not correctly closed."); } bool DeclarationRegistrationHelper::registerDeclaration( DeclarationContainer& _container, Declaration const& _declaration, std::string const* _name, SourceLocation const* _errorLocation, bool _inactive, ErrorReporter& _errorReporter ) { if (!_errorLocation) _errorLocation = &_declaration.location(); std::string name = _name ? *_name : _declaration.name(); // We use "invisible" for both inactive variables in blocks and for members invisible in contracts. // They cannot both be true at the same time. solAssert(!(_inactive && !_declaration.isVisibleInContract()), ""); static std::set<std::string> illegalNames{"_", "super", "this"}; if (illegalNames.count(name)) { auto isPublicFunctionOrEvent = [](Declaration const* _d) -> bool { if (auto functionDefinition = dynamic_cast<FunctionDefinition const*>(_d)) { if (!functionDefinition->isFree() && functionDefinition->isPublic()) return true; } else if (dynamic_cast<EventDefinition const*>(_d)) return true; return false; }; // We allow an exception for public functions or events. if (!isPublicFunctionOrEvent(&_declaration)) _errorReporter.declarationError( 3726_error, *_errorLocation, "The name \"" + name + "\" is reserved." ); } if (!_container.registerDeclaration(_declaration, _name, _errorLocation, !_declaration.isVisibleInContract() || _inactive, false)) { SourceLocation firstDeclarationLocation; SourceLocation secondDeclarationLocation; Declaration const* conflictingDeclaration = _container.conflictingDeclaration(_declaration, _name); solAssert(conflictingDeclaration, ""); bool const comparable = _errorLocation->sourceName && conflictingDeclaration->location().sourceName && *_errorLocation->sourceName == *conflictingDeclaration->location().sourceName; if (comparable && _errorLocation->start < conflictingDeclaration->location().start) { firstDeclarationLocation = *_errorLocation; secondDeclarationLocation = conflictingDeclaration->location(); } else { firstDeclarationLocation = conflictingDeclaration->location(); secondDeclarationLocation = *_errorLocation; } _errorReporter.declarationError( 2333_error, secondDeclarationLocation, SecondarySourceLocation().append("The previous declaration is here:", firstDeclarationLocation), "Identifier already declared." ); return false; } return true; } bool DeclarationRegistrationHelper::visit(SourceUnit& _sourceUnit) { if (!m_scopes[&_sourceUnit]) // By importing, it is possible that the container already exists. m_scopes[&_sourceUnit] = std::make_shared<DeclarationContainer>(m_currentScope, m_scopes[m_currentScope].get()); return ASTVisitor::visit(_sourceUnit); } void DeclarationRegistrationHelper::endVisit(SourceUnit& _sourceUnit) { ASTVisitor::endVisit(_sourceUnit); } bool DeclarationRegistrationHelper::visit(ImportDirective& _import) { SourceUnit const* importee = _import.annotation().sourceUnit; solAssert(!!importee, ""); if (!m_scopes[importee]) m_scopes[importee] = std::make_shared<DeclarationContainer>(nullptr, m_scopes[nullptr].get()); m_scopes[&_import] = m_scopes[importee]; ASTVisitor::visit(_import); return false; // Do not recurse into child nodes (Identifier for symbolAliases) } bool DeclarationRegistrationHelper::visit(ContractDefinition& _contract) { m_globalContext.setCurrentContract(_contract); m_scopes[nullptr]->registerDeclaration(*m_globalContext.currentThis(), false, true); m_scopes[nullptr]->registerDeclaration(*m_globalContext.currentSuper(), false, true); m_currentContract = &_contract; return ASTVisitor::visit(_contract); } void DeclarationRegistrationHelper::endVisit(ContractDefinition& _contract) { // make "this" and "super" invisible. m_scopes[nullptr]->registerDeclaration(*m_globalContext.currentThis(), true, true); m_scopes[nullptr]->registerDeclaration(*m_globalContext.currentSuper(), true, true); m_globalContext.resetCurrentContract(); m_currentContract = nullptr; ASTVisitor::endVisit(_contract); } void DeclarationRegistrationHelper::endVisit(VariableDeclarationStatement& _variableDeclarationStatement) { // Register the local variables with the function // This does not fit here perfectly, but it saves us another AST visit. solAssert(m_currentFunction, "Variable declaration without function."); for (ASTPointer<VariableDeclaration> const& var: _variableDeclarationStatement.declarations()) if (var) m_currentFunction->addLocalVariable(*var); ASTVisitor::endVisit(_variableDeclarationStatement); } bool DeclarationRegistrationHelper::visitNode(ASTNode& _node) { if (auto const* scopable = dynamic_cast<Scopable const*>(&_node)) solAssert(scopable->annotation().scope == m_currentScope, ""); if (auto* declaration = dynamic_cast<Declaration*>(&_node)) registerDeclaration(*declaration); if (auto* annotation = dynamic_cast<TypeDeclarationAnnotation*>(&_node.annotation())) { std::string canonicalName = dynamic_cast<Declaration const&>(_node).name(); solAssert(!canonicalName.empty(), ""); for ( ASTNode const* scope = m_currentScope; scope != nullptr; scope = m_scopes[scope]->enclosingNode() ) if (auto decl = dynamic_cast<Declaration const*>(scope)) { solAssert(!decl->name().empty(), ""); canonicalName = decl->name() + "." + canonicalName; } annotation->canonicalName = canonicalName; } if (dynamic_cast<ScopeOpener const*>(&_node)) enterNewSubScope(_node); if (auto* variableScope = dynamic_cast<VariableScope*>(&_node)) m_currentFunction = variableScope; return true; } void DeclarationRegistrationHelper::endVisitNode(ASTNode& _node) { if (dynamic_cast<ScopeOpener const*>(&_node)) closeCurrentScope(); if (dynamic_cast<VariableScope*>(&_node)) m_currentFunction = nullptr; } void DeclarationRegistrationHelper::enterNewSubScope(ASTNode& _subScope) { if (m_scopes.count(&_subScope)) // Source units are the only AST nodes for which containers can be created from multiple places due to imports. solAssert(dynamic_cast<SourceUnit const*>(&_subScope), "Unexpected scope type."); else { bool newlyAdded = m_scopes.emplace( &_subScope, std::make_shared<DeclarationContainer>(m_currentScope, m_scopes[m_currentScope].get()) ).second; solAssert(newlyAdded, "Unable to add new scope."); } m_currentScope = &_subScope; } void DeclarationRegistrationHelper::closeCurrentScope() { solAssert(m_currentScope && m_scopes.count(m_currentScope), "Closed non-existing scope."); m_currentScope = m_scopes[m_currentScope]->enclosingNode(); } void DeclarationRegistrationHelper::registerDeclaration(Declaration& _declaration) { solAssert(m_currentScope && m_scopes.count(m_currentScope), "No current scope."); solAssert(m_currentScope == _declaration.scope(), "Unexpected current scope."); // Functions defined inside quantifiers should be visible in the scope containing the quantifier // TODO: Turn it into a more generic mechanism in the same vein as Scopable and ScopeOpener if // it turns out we need more special-casing here. auto const* quantifier = dynamic_cast<ForAllQuantifier const*>(m_currentScope); auto const* functionDefinition = dynamic_cast<FunctionDefinition const*>(&_declaration); if (quantifier && functionDefinition) { solAssert(quantifier->scope()); solAssert( // forall quantifiers cannot be used in block scope so the declaration is always active. !dynamic_cast<Block const*>(quantifier->scope()) && !dynamic_cast<ForStatement const*>(quantifier->scope()) ); // NOTE: We're registering the function outside of its scope(). This will only affect // name lookups. An more general alternative would be to modify Scoper to simply assign it // that scope in the first place, but this would complicate the AST traversal here, which // currently assumes that scopes follow ScopeOpener nesting. registerDeclaration(*m_scopes.at(quantifier->scope()), _declaration, nullptr, nullptr, false /* inactive */, m_errorReporter); } else { // Register declaration as inactive if we are in block scope. bool inactive = (dynamic_cast<Block const*>(m_currentScope) || dynamic_cast<ForStatement const*>(m_currentScope)); registerDeclaration(*m_scopes[m_currentScope], _declaration, nullptr, nullptr, inactive, m_errorReporter); } solAssert(_declaration.annotation().scope == m_currentScope, ""); solAssert(_declaration.annotation().contract == m_currentContract, ""); } }
24,737
C++
.cpp
653
34.773354
135
0.750875
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
3,212
DeclarationTypeChecker.cpp
ethereum_solidity/libsolidity/analysis/DeclarationTypeChecker.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libsolidity/analysis/DeclarationTypeChecker.h> #include <libsolidity/analysis/ConstantEvaluator.h> #include <libsolidity/ast/TypeProvider.h> #include <liblangutil/ErrorReporter.h> #include <libsolutil/Algorithms.h> #include <libsolutil/Visitor.h> #include <range/v3/view/transform.hpp> using namespace solidity::langutil; using namespace solidity::frontend; bool DeclarationTypeChecker::visit(ElementaryTypeName const& _typeName) { if (_typeName.annotation().type) return false; _typeName.annotation().type = TypeProvider::fromElementaryTypeName(_typeName.typeName()); if (_typeName.stateMutability().has_value()) { // for non-address types this was already caught by the parser solAssert(_typeName.annotation().type->category() == Type::Category::Address, ""); switch (*_typeName.stateMutability()) { case StateMutability::Payable: _typeName.annotation().type = TypeProvider::payableAddress(); break; case StateMutability::NonPayable: _typeName.annotation().type = TypeProvider::address(); break; default: m_errorReporter.typeError( 2311_error, _typeName.location(), "Address types can only be payable or non-payable." ); break; } } return true; } bool DeclarationTypeChecker::visit(EnumDefinition const& _enum) { if (_enum.members().size() > 256) m_errorReporter.declarationError( 1611_error, _enum.location(), "Enum with more than 256 members is not allowed." ); return false; } bool DeclarationTypeChecker::visit(StructDefinition const& _struct) { if (_struct.annotation().recursive.has_value()) { if (!m_currentStructsSeen.empty() && *_struct.annotation().recursive) m_recursiveStructSeen = true; return false; } if (m_currentStructsSeen.count(&_struct)) { _struct.annotation().recursive = true; m_recursiveStructSeen = true; return false; } bool previousRecursiveStructSeen = m_recursiveStructSeen; bool hasRecursiveChild = false; m_currentStructsSeen.insert(&_struct); for (auto const& member: _struct.members()) { m_recursiveStructSeen = false; member->accept(*this); solAssert(member->annotation().type, ""); if (m_recursiveStructSeen) hasRecursiveChild = true; } if (!_struct.annotation().recursive.has_value()) _struct.annotation().recursive = hasRecursiveChild; m_recursiveStructSeen = previousRecursiveStructSeen || *_struct.annotation().recursive; m_currentStructsSeen.erase(&_struct); if (m_currentStructsSeen.empty()) m_recursiveStructSeen = false; // Check direct recursion, fatal error if detected. auto visitor = [&](StructDefinition const& _struct, auto& _cycleDetector, size_t _depth) { if (_depth >= 256) m_errorReporter.fatalDeclarationError( 5651_error, _struct.location(), "Struct definition exhausts cyclic dependency validator." ); for (ASTPointer<VariableDeclaration> const& member: _struct.members()) { Type const* memberType = member->annotation().type; if (auto arrayType = dynamic_cast<ArrayType const*>(memberType)) memberType = arrayType->finalBaseType(true); if (auto structType = dynamic_cast<StructType const*>(memberType)) if (_cycleDetector.run(structType->structDefinition())) return; } }; if (util::CycleDetector<StructDefinition>(visitor).run(_struct)) m_errorReporter.fatalTypeError(2046_error, _struct.location(), "Recursive struct definition."); return false; } void DeclarationTypeChecker::endVisit(UserDefinedValueTypeDefinition const& _userDefined) { TypeName const* typeName = _userDefined.underlyingType(); solAssert(typeName, ""); if (!dynamic_cast<ElementaryTypeName const*>(typeName)) m_errorReporter.fatalTypeError( 8657_error, typeName->location(), "The underlying type for a user defined value type has to be an elementary value type." ); Type const* type = typeName->annotation().type; solAssert(type, ""); solAssert(!dynamic_cast<UserDefinedValueType const*>(type), ""); if (!type->isValueType()) m_errorReporter.typeError( 8129_error, _userDefined.location(), "The underlying type of the user defined value type \"" + _userDefined.name() + "\" is not a value type." ); } void DeclarationTypeChecker::endVisit(UserDefinedTypeName const& _typeName) { if (_typeName.annotation().type) return; Declaration const* declaration = _typeName.pathNode().annotation().referencedDeclaration; solAssert(declaration, ""); if (StructDefinition const* structDef = dynamic_cast<StructDefinition const*>(declaration)) { if (!m_insideFunctionType && !m_currentStructsSeen.empty()) structDef->accept(*this); _typeName.annotation().type = TypeProvider::structType(*structDef, DataLocation::Storage); } else if (EnumDefinition const* enumDef = dynamic_cast<EnumDefinition const*>(declaration)) _typeName.annotation().type = TypeProvider::enumType(*enumDef); else if (ContractDefinition const* contract = dynamic_cast<ContractDefinition const*>(declaration)) _typeName.annotation().type = TypeProvider::contract(*contract); else if (auto userDefinedValueType = dynamic_cast<UserDefinedValueTypeDefinition const*>(declaration)) _typeName.annotation().type = TypeProvider::userDefinedValueType(*userDefinedValueType); else { _typeName.annotation().type = TypeProvider::emptyTuple(); m_errorReporter.fatalTypeError( 5172_error, _typeName.location(), "Name has to refer to a user-defined type." ); } } void DeclarationTypeChecker::endVisit(IdentifierPath const& _path) { Declaration const* declaration = _path.annotation().referencedDeclaration; solAssert(declaration, ""); if (ContractDefinition const* contract = dynamic_cast<ContractDefinition const*>(declaration)) if (contract->isLibrary()) m_errorReporter.typeError(1130_error, _path.location(), "Invalid use of a library name."); } bool DeclarationTypeChecker::visit(FunctionTypeName const& _typeName) { if (_typeName.annotation().type) return false; bool previousInsideFunctionType = m_insideFunctionType; m_insideFunctionType = true; _typeName.parameterTypeList()->accept(*this); _typeName.returnParameterTypeList()->accept(*this); m_insideFunctionType = previousInsideFunctionType; switch (_typeName.visibility()) { case Visibility::Internal: case Visibility::External: break; default: m_errorReporter.fatalTypeError( 6012_error, _typeName.location(), "Invalid visibility, can only be \"external\" or \"internal\"." ); return false; } if (_typeName.isPayable() && _typeName.visibility() != Visibility::External) { m_errorReporter.fatalTypeError( 7415_error, _typeName.location(), "Only external function types can be payable." ); return false; } _typeName.annotation().type = TypeProvider::function(_typeName); return false; } void DeclarationTypeChecker::endVisit(Mapping const& _mapping) { if (_mapping.annotation().type) return; if (auto const* typeName = dynamic_cast<UserDefinedTypeName const*>(&_mapping.keyType())) switch (typeName->annotation().type->category()) { case Type::Category::Enum: case Type::Category::Contract: case Type::Category::UserDefinedValueType: break; default: m_errorReporter.fatalTypeError( 7804_error, typeName->location(), "Only elementary types, user defined value types, contract types or enums are allowed as mapping keys." ); break; } else solAssert(dynamic_cast<ElementaryTypeName const*>(&_mapping.keyType()), ""); Type const* keyType = _mapping.keyType().annotation().type; ASTString keyName = _mapping.keyName(); Type const* valueType = _mapping.valueType().annotation().type; ASTString valueName = _mapping.valueName(); // Convert key type to memory. keyType = TypeProvider::withLocationIfReference(DataLocation::Memory, keyType); // Convert value type to storage reference. valueType = TypeProvider::withLocationIfReference(DataLocation::Storage, valueType); _mapping.annotation().type = TypeProvider::mapping(keyType, keyName, valueType, valueName); // Check if parameter names are conflicting. if (!keyName.empty()) { auto childMappingType = dynamic_cast<MappingType const*>(valueType); ASTString currentValueName = valueName; bool loop = true; while (loop) { bool isError = false; // Value type is a mapping. if (childMappingType) { // Compare top mapping's key name with child mapping's key name. ASTString childKeyName = childMappingType->keyName(); if (keyName == childKeyName) isError = true; auto valueType = childMappingType->valueType(); currentValueName = childMappingType->valueName(); childMappingType = dynamic_cast<MappingType const*>(valueType); } else { // Compare top mapping's key name with the value name. if (keyName == currentValueName) isError = true; loop = false; // We arrived at the end of mapping recursion. } // Report error. if (isError) { m_errorReporter.declarationError( 1809_error, _mapping.location(), "Conflicting parameter name \"" + keyName + "\" in mapping." ); } } } } void DeclarationTypeChecker::endVisit(ArrayTypeName const& _typeName) { if (_typeName.annotation().type) return; Type const* baseType = _typeName.baseType().annotation().type; if (!baseType) { solAssert(m_errorReporter.hasErrors(), ""); return; } if (Expression const* length = _typeName.length()) { std::optional<rational> lengthValue; if (length->annotation().type && length->annotation().type->category() == Type::Category::RationalNumber) lengthValue = dynamic_cast<RationalNumberType const&>(*length->annotation().type).value(); else if (std::optional<ConstantEvaluator::TypedRational> value = ConstantEvaluator::evaluate(m_errorReporter, *length)) lengthValue = value->value; if (!lengthValue) m_errorReporter.typeError( 5462_error, length->location(), "Invalid array length, expected integer literal or constant expression." ); else if (*lengthValue == 0) m_errorReporter.typeError(1406_error, length->location(), "Array with zero length specified."); else if (lengthValue->denominator() != 1) m_errorReporter.typeError(3208_error, length->location(), "Array with fractional length specified."); else if (*lengthValue < 0) m_errorReporter.typeError(3658_error, length->location(), "Array with negative length specified."); else if (lengthValue > TypeProvider::uint256()->max()) m_errorReporter.typeError( 1847_error, length->location(), "Array length too large, maximum is 2**256 - 1." ); _typeName.annotation().type = TypeProvider::array( DataLocation::Storage, baseType, lengthValue ? u256(lengthValue->numerator()) : u256(0) ); } else _typeName.annotation().type = TypeProvider::array(DataLocation::Storage, baseType); } void DeclarationTypeChecker::endVisit(VariableDeclaration const& _variable) { if (_variable.annotation().type) return; if (_variable.isFileLevelVariable() && !_variable.isConstant()) m_errorReporter.declarationError( 8342_error, _variable.location(), "Only constant variables are allowed at file level." ); if (_variable.isConstant() && (!_variable.isStateVariable() && !_variable.isFileLevelVariable())) m_errorReporter.declarationError( 1788_error, _variable.location(), "The \"constant\" keyword can only be used for state variables or variables at file level." ); if (_variable.immutable() && !_variable.isStateVariable()) m_errorReporter.declarationError( 8297_error, _variable.location(), "The \"immutable\" keyword can only be used for state variables." ); using Location = VariableDeclaration::Location; Location varLoc = _variable.referenceLocation(); DataLocation typeLoc = DataLocation::Memory; if (varLoc == VariableDeclaration::Location::Transient && !m_evmVersion.supportsTransientStorage()) m_errorReporter.declarationError( 7985_error, _variable.location(), "Transient storage is not supported by EVM versions older than cancun." ); std::set<Location> allowedDataLocations = _variable.allowedDataLocations(); if (!allowedDataLocations.count(varLoc)) { auto locationToString = [](VariableDeclaration::Location _location) -> std::string { switch (_location) { case Location::Memory: return "\"memory\""; case Location::Storage: return "\"storage\""; case Location::Transient: return "\"transient\""; case Location::CallData: return "\"calldata\""; case Location::Unspecified: return "none"; } return {}; }; std::string errorString; if (!_variable.hasReferenceOrMappingType()) errorString = "Data location can only be specified for array, struct or mapping types"; else { errorString = "Data location must be " + util::joinHumanReadable( allowedDataLocations | ranges::views::transform(locationToString), ", ", " or " ); if (_variable.isConstructorParameter()) errorString += " for constructor parameter"; else if (_variable.isCallableOrCatchParameter()) errorString += " for " + std::string(_variable.isReturnParameter() ? "return " : "") + "parameter in" + std::string(_variable.isExternalCallableParameter() ? " external" : "") + " function"; else errorString += " for variable"; } errorString += ", but " + locationToString(varLoc) + " was given."; m_errorReporter.typeError(6651_error, _variable.location(), errorString); solAssert(!allowedDataLocations.empty(), ""); varLoc = *allowedDataLocations.begin(); } // Find correct data location. if (_variable.isEventOrErrorParameter()) { solAssert(varLoc == Location::Unspecified, ""); typeLoc = DataLocation::Memory; } else if (_variable.isFileLevelVariable()) { solAssert(varLoc == Location::Unspecified, ""); typeLoc = DataLocation::Memory; } else if (_variable.isStateVariable()) { switch (varLoc) { case Location::Unspecified: typeLoc = (_variable.isConstant() || _variable.immutable()) ? DataLocation::Memory : DataLocation::Storage; break; case Location::Transient: if (_variable.isConstant() || _variable.immutable()) m_errorReporter.declarationError( 2197_error, _variable.location(), "Transient cannot be used as data location for constant or immutable variables." ); if (_variable.value()) m_errorReporter.declarationError( 9825_error, _variable.location(), "Initialization of transient storage state variables is not supported." ); typeLoc = DataLocation::Transient; break; default: solAssert(false); break; } } else if ( dynamic_cast<StructDefinition const*>(_variable.scope()) || dynamic_cast<EnumDefinition const*>(_variable.scope()) ) // The actual location will later be changed depending on how the type is used. typeLoc = DataLocation::Storage; else switch (varLoc) { case Location::Memory: typeLoc = DataLocation::Memory; break; case Location::Storage: typeLoc = DataLocation::Storage; break; case Location::CallData: typeLoc = DataLocation::CallData; break; case Location::Transient: solUnimplemented("Transient data location cannot be used in this kind of variable or parameter declaration."); break; case Location::Unspecified: solAssert(!_variable.hasReferenceOrMappingType(), "Data location not properly set."); } Type const* type = _variable.typeName().annotation().type; if (auto ref = dynamic_cast<ReferenceType const*>(type)) { bool isPointer = !_variable.isStateVariable(); type = TypeProvider::withLocation(ref, typeLoc, isPointer); } if (_variable.isConstant() && !type->isValueType()) { bool allowed = false; if (auto arrayType = dynamic_cast<ArrayType const*>(type)) allowed = arrayType->isByteArrayOrString(); if (!allowed) m_errorReporter.fatalTypeError(9259_error, _variable.location(), "Only constants of value type and byte array type are implemented."); } if (!type->isValueType()) solUnimplementedAssert(typeLoc != DataLocation::Transient, "Transient data location is only supported for value types."); _variable.annotation().type = type; } bool DeclarationTypeChecker::visit(UsingForDirective const& _usingFor) { if (_usingFor.usesBraces()) { for (ASTPointer<IdentifierPath> const& function: _usingFor.functionsOrLibrary()) if (auto functionDefinition = dynamic_cast<FunctionDefinition const*>(function->annotation().referencedDeclaration)) { if (!functionDefinition->isFree() && !( dynamic_cast<ContractDefinition const*>(functionDefinition->scope()) && dynamic_cast<ContractDefinition const*>(functionDefinition->scope())->isLibrary() )) m_errorReporter.typeError( 4167_error, function->location(), "Only file-level functions and library functions can be attached to a type in a \"using\" statement" ); } else m_errorReporter.fatalTypeError(8187_error, function->location(), "Expected function name." ); } else { ContractDefinition const* library = dynamic_cast<ContractDefinition const*>( _usingFor.functionsOrLibrary().front()->annotation().referencedDeclaration ); if (!library || !library->isLibrary()) m_errorReporter.fatalTypeError( 4357_error, _usingFor.functionsOrLibrary().front()->location(), "Library name expected. If you want to attach a function, use '{...}'." ); } // We do not visit _usingFor.functions() because it will lead to an error since // library names cannot be mentioned stand-alone. if (_usingFor.typeName()) _usingFor.typeName()->accept(*this); return false; } bool DeclarationTypeChecker::visit(InheritanceSpecifier const& _inheritanceSpecifier) { auto const* contract = dynamic_cast<ContractDefinition const*>(_inheritanceSpecifier.name().annotation().referencedDeclaration); solAssert(contract, ""); if (contract->isLibrary()) { m_errorReporter.typeError( 2571_error, _inheritanceSpecifier.name().location(), "Libraries cannot be inherited from." ); return false; } return true; } bool DeclarationTypeChecker::check(ASTNode const& _node) { auto watcher = m_errorReporter.errorWatcher(); _node.accept(*this); return watcher.ok(); }
18,966
C++
.cpp
533
32.257036
137
0.737284
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
3,213
PostTypeContractLevelChecker.cpp
ethereum_solidity/libsolidity/analysis/PostTypeContractLevelChecker.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 /** * Component that verifies overloads, abstract contracts, function clashes and others * checks at contract or function level. */ #include <libsolidity/analysis/PostTypeContractLevelChecker.h> #include <libsolidity/ast/AST.h> #include <libsolutil/FunctionSelector.h> #include <liblangutil/ErrorReporter.h> using namespace solidity; using namespace solidity::langutil; using namespace solidity::frontend; bool PostTypeContractLevelChecker::check(SourceUnit const& _sourceUnit) { bool noErrors = true; for (auto* contract: ASTNode::filteredNodes<ContractDefinition>(_sourceUnit.nodes())) if (!check(*contract)) noErrors = false; return noErrors; } bool PostTypeContractLevelChecker::check(ContractDefinition const& _contract) { solAssert( _contract.annotation().creationCallGraph.set() && _contract.annotation().deployedCallGraph.set(), "" ); std::map<uint32_t, std::map<std::string, SourceLocation>> errorHashes; for (ErrorDefinition const* error: _contract.interfaceErrors()) { std::string signature = error->functionType(true)->externalSignature(); uint32_t hash = util::selectorFromSignatureU32(signature); // Fail if there is a different signature for the same hash. if (!errorHashes[hash].empty() && !errorHashes[hash].count(signature)) { SourceLocation& otherLocation = errorHashes[hash].begin()->second; m_errorReporter.typeError( 4883_error, error->nameLocation(), SecondarySourceLocation{}.append("This error has a different signature but the same hash: ", otherLocation), "Error signature hash collision for " + error->functionType(true)->externalSignature() ); } else errorHashes[hash][signature] = error->location(); } return !Error::containsErrors(m_errorReporter.errors()); }
2,449
C++
.cpp
61
37.721311
112
0.776283
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
3,214
GlobalContext.cpp
ethereum_solidity/libsolidity/analysis/GlobalContext.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 /** * @author Christian <c@ethdev.com> * @author Gav Wood <g@ethdev.com> * @date 2014 * Container of the (implicit and explicit) global objects. */ #include <libsolidity/analysis/GlobalContext.h> #include <libsolidity/ast/AST.h> #include <libsolidity/ast/TypeProvider.h> #include <libsolidity/ast/Types.h> #include <memory> #include <unordered_map> namespace solidity::frontend { namespace { /// Magic variables get negative ids for easy differentiation int magicVariableToID(std::string const& _name) { static std::unordered_map<std::string, int> const magicVariables = { {"abi", -1}, {"addmod", -2}, {"assert", -3}, {"block", -4}, {"blockhash", -5}, {"ecrecover", -6}, {"gasleft", -7}, {"keccak256", -8}, {"msg", -15}, {"mulmod", -16}, {"now", -17}, {"require", -18}, {"revert", -19}, {"ripemd160", -20}, {"selfdestruct", -21}, {"sha256", -22}, {"sha3", -23}, {"suicide", -24}, {"super", -25}, {"tx", -26}, {"type", -27}, {"this", -28}, {"blobhash", -29} }; if (auto id = magicVariables.find(_name); id != magicVariables.end()) return id->second; solAssert(false, "Unknown magic variable: \"" + _name + "\"."); } inline std::vector<std::shared_ptr<MagicVariableDeclaration const>> constructMagicVariables(langutil::EVMVersion _evmVersion) { static auto const magicVarDecl = [](std::string const& _name, Type const* _type) { return std::make_shared<MagicVariableDeclaration>(magicVariableToID(_name), _name, _type); }; std::vector<std::shared_ptr<MagicVariableDeclaration const>> magicVariableDeclarations = { magicVarDecl("abi", TypeProvider::magic(MagicType::Kind::ABI)), magicVarDecl("addmod", TypeProvider::function(strings{"uint256", "uint256", "uint256"}, strings{"uint256"}, FunctionType::Kind::AddMod, StateMutability::Pure)), magicVarDecl("assert", TypeProvider::function(strings{"bool"}, strings{}, FunctionType::Kind::Assert, StateMutability::Pure)), magicVarDecl("block", TypeProvider::magic(MagicType::Kind::Block)), magicVarDecl("blockhash", TypeProvider::function(strings{"uint256"}, strings{"bytes32"}, FunctionType::Kind::BlockHash, StateMutability::View)), magicVarDecl("ecrecover", TypeProvider::function(strings{"bytes32", "uint8", "bytes32", "bytes32"}, strings{"address"}, FunctionType::Kind::ECRecover, StateMutability::Pure)), magicVarDecl("gasleft", TypeProvider::function(strings(), strings{"uint256"}, FunctionType::Kind::GasLeft, StateMutability::View)), magicVarDecl("keccak256", TypeProvider::function(strings{"bytes memory"}, strings{"bytes32"}, FunctionType::Kind::KECCAK256, StateMutability::Pure)), magicVarDecl("msg", TypeProvider::magic(MagicType::Kind::Message)), magicVarDecl("mulmod", TypeProvider::function(strings{"uint256", "uint256", "uint256"}, strings{"uint256"}, FunctionType::Kind::MulMod, StateMutability::Pure)), magicVarDecl("now", TypeProvider::uint256()), magicVarDecl("require", TypeProvider::function(strings{"bool"}, strings{}, FunctionType::Kind::Require, StateMutability::Pure)), magicVarDecl("require", TypeProvider::function(strings{"bool", "string memory"}, strings{}, FunctionType::Kind::Require, StateMutability::Pure)), magicVarDecl("require", TypeProvider::function(TypePointers{TypeProvider::boolean(), TypeProvider::magic(MagicType::Kind::Error)}, TypePointers{}, strings{2, ""}, strings{}, FunctionType::Kind::Require, StateMutability::Pure)), magicVarDecl("revert", TypeProvider::function(strings(), strings(), FunctionType::Kind::Revert, StateMutability::Pure)), magicVarDecl("revert", TypeProvider::function(strings{"string memory"}, strings(), FunctionType::Kind::Revert, StateMutability::Pure)), magicVarDecl("ripemd160", TypeProvider::function(strings{"bytes memory"}, strings{"bytes20"}, FunctionType::Kind::RIPEMD160, StateMutability::Pure)), magicVarDecl("selfdestruct", TypeProvider::function(strings{"address payable"}, strings{}, FunctionType::Kind::Selfdestruct)), magicVarDecl("sha256", TypeProvider::function(strings{"bytes memory"}, strings{"bytes32"}, FunctionType::Kind::SHA256, StateMutability::Pure)), magicVarDecl("sha3", TypeProvider::function(strings{"bytes memory"}, strings{"bytes32"}, FunctionType::Kind::KECCAK256, StateMutability::Pure)), magicVarDecl("suicide", TypeProvider::function(strings{"address payable"}, strings{}, FunctionType::Kind::Selfdestruct)), magicVarDecl("tx", TypeProvider::magic(MagicType::Kind::Transaction)), // Accepts a MagicType that can be any contract type or an Integer type and returns a // MagicType. The TypeChecker handles the correctness of the input and output types. magicVarDecl("type", TypeProvider::function( strings{}, strings{}, FunctionType::Kind::MetaType, StateMutability::Pure, FunctionType::Options::withArbitraryParameters() )), }; if (_evmVersion >= langutil::EVMVersion::cancun()) magicVariableDeclarations.push_back( magicVarDecl("blobhash", TypeProvider::function(strings{"uint256"}, strings{"bytes32"}, FunctionType::Kind::BlobHash, StateMutability::View)) ); return magicVariableDeclarations; } } GlobalContext::GlobalContext(langutil::EVMVersion _evmVersion): m_magicVariables{constructMagicVariables(_evmVersion)} { } void GlobalContext::setCurrentContract(ContractDefinition const& _contract) { m_currentContract = &_contract; } std::vector<Declaration const*> GlobalContext::declarations() const { std::vector<Declaration const*> declarations; declarations.reserve(m_magicVariables.size()); for (ASTPointer<MagicVariableDeclaration const> const& variable: m_magicVariables) declarations.push_back(variable.get()); return declarations; } MagicVariableDeclaration const* GlobalContext::currentThis() const { if (!m_thisPointer[m_currentContract]) { Type const* type = TypeProvider::emptyTuple(); if (m_currentContract) type = TypeProvider::contract(*m_currentContract); m_thisPointer[m_currentContract] = std::make_shared<MagicVariableDeclaration>(magicVariableToID("this"), "this", type); } return m_thisPointer[m_currentContract].get(); } MagicVariableDeclaration const* GlobalContext::currentSuper() const { if (!m_superPointer[m_currentContract]) { Type const* type = TypeProvider::emptyTuple(); if (m_currentContract) type = TypeProvider::typeType(TypeProvider::contract(*m_currentContract, true)); m_superPointer[m_currentContract] = std::make_shared<MagicVariableDeclaration>(magicVariableToID("super"), "super", type); } return m_superPointer[m_currentContract].get(); } }
7,213
C++
.cpp
148
46.317568
229
0.750745
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,215
FunctionCallGraph.cpp
ethereum_solidity/libsolidity/analysis/FunctionCallGraph.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libsolidity/analysis/FunctionCallGraph.h> #include <libsolutil/StringUtils.h> #include <range/v3/range/conversion.hpp> #include <range/v3/view/reverse.hpp> #include <range/v3/view/transform.hpp> using namespace solidity::frontend; using namespace solidity::util; CallGraph FunctionCallGraphBuilder::buildCreationGraph(ContractDefinition const& _contract) { FunctionCallGraphBuilder builder(_contract); solAssert(builder.m_currentNode == CallGraph::Node(CallGraph::SpecialNode::Entry), ""); // Create graph for constructor, state vars, etc for (ContractDefinition const* base: _contract.annotation().linearizedBaseContracts | ranges::views::reverse) { // The constructor and functions called in state variable initial assignments should have // an edge from Entry builder.m_currentNode = CallGraph::SpecialNode::Entry; for (auto const* stateVar: base->stateVariables()) if (!stateVar->isConstant()) stateVar->accept(builder); if (base->constructor()) { builder.functionReferenced(*base->constructor()); // Constructors and functions called in state variable initializers have an edge either from // the previous class in linearized order or from Entry if there's no class before. builder.m_currentNode = base->constructor(); } // Functions called from the inheritance specifier should have an edge from the constructor // for consistency with functions called from constructor modifiers. for (auto const& inheritanceSpecifier: base->baseContracts()) inheritanceSpecifier->accept(builder); } builder.m_currentNode = CallGraph::SpecialNode::Entry; builder.processQueue(); return std::move(builder.m_graph); } CallGraph FunctionCallGraphBuilder::buildDeployedGraph( ContractDefinition const& _contract, CallGraph const& _creationGraph ) { FunctionCallGraphBuilder builder(_contract); solAssert(builder.m_currentNode == CallGraph::Node(CallGraph::SpecialNode::Entry), ""); auto getSecondElement = [](auto const& _tuple){ return std::get<1>(_tuple); }; // Create graph for all publicly reachable functions for (FunctionTypePointer functionType: _contract.interfaceFunctionList() | ranges::views::transform(getSecondElement)) { auto const* function = dynamic_cast<FunctionDefinition const*>(&functionType->declaration()); auto const* variable = dynamic_cast<VariableDeclaration const*>(&functionType->declaration()); if (function) builder.functionReferenced(*function); else // If it's not a function, it must be a getter of a public variable; we ignore those solAssert(variable, ""); } if (_contract.fallbackFunction()) builder.functionReferenced(*_contract.fallbackFunction()); if (_contract.receiveFunction()) builder.functionReferenced(*_contract.receiveFunction()); // All functions present in internal dispatch at creation time could potentially be pointers // assigned to state variables and as such may be reachable after deployment as well. builder.m_currentNode = CallGraph::SpecialNode::InternalDispatch; std::set<CallGraph::Node, CallGraph::CompareByID> defaultNode; for (CallGraph::Node const& dispatchTarget: util::valueOrDefault(_creationGraph.edges, CallGraph::SpecialNode::InternalDispatch, defaultNode)) { solAssert(!std::holds_alternative<CallGraph::SpecialNode>(dispatchTarget), ""); solAssert(std::get<CallableDeclaration const*>(dispatchTarget) != nullptr, ""); // Visit the callable to add not only it but also everything it calls too builder.functionReferenced(*std::get<CallableDeclaration const*>(dispatchTarget), false); } builder.m_currentNode = CallGraph::SpecialNode::Entry; builder.processQueue(); return std::move(builder.m_graph); } bool FunctionCallGraphBuilder::visit(FunctionCall const& _functionCall) { if (*_functionCall.annotation().kind != FunctionCallKind::FunctionCall) return true; auto const* functionType = dynamic_cast<FunctionType const*>(_functionCall.expression().annotation().type); solAssert(functionType, ""); if (functionType->kind() == FunctionType::Kind::Internal && !_functionCall.expression().annotation().calledDirectly) // If it's not a direct call, we don't really know which function will be called (it may even // change at runtime). All we can do is to add an edge to the dispatch which in turn has // edges to all functions could possibly be called. add(m_currentNode, CallGraph::SpecialNode::InternalDispatch); else if (functionType->kind() == FunctionType::Kind::Error) m_graph.usedErrors.insert(&dynamic_cast<ErrorDefinition const&>(functionType->declaration())); return true; } bool FunctionCallGraphBuilder::visit(EmitStatement const& _emitStatement) { auto const* functionType = dynamic_cast<FunctionType const*>(_emitStatement.eventCall().expression().annotation().type); solAssert(functionType, ""); m_graph.emittedEvents.insert(&dynamic_cast<EventDefinition const&>(functionType->declaration())); return true; } bool FunctionCallGraphBuilder::visit(Identifier const& _identifier) { if (auto const* variable = dynamic_cast<VariableDeclaration const*>(_identifier.annotation().referencedDeclaration)) { if (variable->isConstant()) { solAssert(variable->isStateVariable() || variable->isFileLevelVariable(), ""); variable->accept(*this); } } else if (auto const* callable = dynamic_cast<CallableDeclaration const*>(_identifier.annotation().referencedDeclaration)) { solAssert(*_identifier.annotation().requiredLookup == VirtualLookup::Virtual, ""); auto funType = dynamic_cast<FunctionType const*>(_identifier.annotation().type); // For events kind() == Event, so we have an extra check here if (funType && funType->kind() == FunctionType::Kind::Internal) functionReferenced(callable->resolveVirtual(m_contract), _identifier.annotation().calledDirectly); } return true; } bool FunctionCallGraphBuilder::visit(MemberAccess const& _memberAccess) { Type const* exprType = _memberAccess.expression().annotation().type; ASTString const& memberName = _memberAccess.memberName(); if (auto magicType = dynamic_cast<MagicType const*>(exprType)) if (magicType->kind() == MagicType::Kind::MetaType && ( memberName == "creationCode" || memberName == "runtimeCode" )) { ContractType const& accessedContractType = dynamic_cast<ContractType const&>(*magicType->typeArgument()); m_graph.bytecodeDependency.emplace(&accessedContractType.contractDefinition(), &_memberAccess); } auto functionType = dynamic_cast<FunctionType const*>(_memberAccess.annotation().type); auto functionDef = dynamic_cast<FunctionDefinition const*>(_memberAccess.annotation().referencedDeclaration); if (!functionType || !functionDef || functionType->kind() != FunctionType::Kind::Internal) return true; // Super functions if (*_memberAccess.annotation().requiredLookup == VirtualLookup::Super) { if (auto const* typeType = dynamic_cast<TypeType const*>(exprType)) if (auto const contractType = dynamic_cast<ContractType const*>(typeType->actualType())) { solAssert(contractType->isSuper(), ""); functionDef = &functionDef->resolveVirtual( m_contract, contractType->contractDefinition().superContract(m_contract) ); } } else solAssert(*_memberAccess.annotation().requiredLookup == VirtualLookup::Static, ""); functionReferenced(*functionDef, _memberAccess.annotation().calledDirectly); return true; } bool FunctionCallGraphBuilder::visit(BinaryOperation const& _binaryOperation) { if (*_binaryOperation.annotation().userDefinedFunction != nullptr) functionReferenced(**_binaryOperation.annotation().userDefinedFunction, true /* called directly */); return true; } bool FunctionCallGraphBuilder::visit(UnaryOperation const& _unaryOperation) { if (*_unaryOperation.annotation().userDefinedFunction != nullptr) functionReferenced(**_unaryOperation.annotation().userDefinedFunction, true /* called directly */); return true; } bool FunctionCallGraphBuilder::visit(ModifierInvocation const& _modifierInvocation) { if (auto const* modifier = dynamic_cast<ModifierDefinition const*>(_modifierInvocation.name().annotation().referencedDeclaration)) { VirtualLookup const& requiredLookup = *_modifierInvocation.name().annotation().requiredLookup; if (requiredLookup == VirtualLookup::Virtual) functionReferenced(modifier->resolveVirtual(m_contract)); else { solAssert(requiredLookup == VirtualLookup::Static, ""); functionReferenced(*modifier); } } return true; } bool FunctionCallGraphBuilder::visit(NewExpression const& _newExpression) { if (ContractType const* contractType = dynamic_cast<ContractType const*>(_newExpression.typeName().annotation().type)) m_graph.bytecodeDependency.emplace(&contractType->contractDefinition(), &_newExpression); return true; } void FunctionCallGraphBuilder::enqueueCallable(CallableDeclaration const& _callable) { if (!m_graph.edges.count(&_callable)) { m_visitQueue.push_back(&_callable); // Insert the callable to the graph (with no edges coming out of it) to mark it as visited. m_graph.edges.insert({CallGraph::Node(&_callable), {}}); } } void FunctionCallGraphBuilder::processQueue() { solAssert(m_currentNode == CallGraph::Node(CallGraph::SpecialNode::Entry), "Visit queue is already being processed."); while (!m_visitQueue.empty()) { m_currentNode = m_visitQueue.front(); solAssert(std::holds_alternative<CallableDeclaration const*>(m_currentNode), ""); m_visitQueue.pop_front(); std::get<CallableDeclaration const*>(m_currentNode)->accept(*this); } m_currentNode = CallGraph::SpecialNode::Entry; } void FunctionCallGraphBuilder::add(CallGraph::Node _caller, CallGraph::Node _callee) { m_graph.edges[_caller].insert(_callee); } void FunctionCallGraphBuilder::functionReferenced(CallableDeclaration const& _callable, bool _calledDirectly) { if (_calledDirectly) { solAssert( std::holds_alternative<CallGraph::SpecialNode>(m_currentNode) || m_graph.edges.count(m_currentNode) > 0, "Adding an edge from a node that has not been visited yet." ); add(m_currentNode, &_callable); } else add(CallGraph::SpecialNode::InternalDispatch, &_callable); enqueueCallable(_callable); } std::ostream& solidity::frontend::operator<<(std::ostream& _out, CallGraph::Node const& _node) { if (std::holds_alternative<CallGraph::SpecialNode>(_node)) switch (std::get<CallGraph::SpecialNode>(_node)) { case CallGraph::SpecialNode::InternalDispatch: _out << "InternalDispatch"; break; case CallGraph::SpecialNode::Entry: _out << "Entry"; break; default: solAssert(false, "Invalid SpecialNode type"); } else { solAssert(std::holds_alternative<CallableDeclaration const*>(_node), ""); auto const* callableDeclaration = std::get<CallableDeclaration const*>(_node); solAssert(callableDeclaration, ""); auto const* function = dynamic_cast<FunctionDefinition const *>(callableDeclaration); auto const* event = dynamic_cast<EventDefinition const *>(callableDeclaration); auto const* modifier = dynamic_cast<ModifierDefinition const *>(callableDeclaration); auto typeToString = [](auto const& _var) -> std::string { return _var->type()->toString(true); }; std::vector<std::string> parameters = callableDeclaration->parameters() | ranges::views::transform(typeToString) | ranges::to<std::vector<std::string>>(); std::string scopeName; if (!function || !function->isFree()) { solAssert(callableDeclaration->annotation().scope, ""); auto const* parentContract = dynamic_cast<ContractDefinition const*>(callableDeclaration->annotation().scope); solAssert(parentContract, ""); scopeName = parentContract->name(); } if (function && function->isFree()) _out << "function " << function->name() << "(" << joinHumanReadable(parameters, ",") << ")"; else if (function && function->isConstructor()) _out << "constructor of " << scopeName; else if (function && function->isFallback()) _out << "fallback of " << scopeName; else if (function && function->isReceive()) _out << "receive of " << scopeName; else if (function) _out << "function " << scopeName << "." << function->name() << "(" << joinHumanReadable(parameters, ",") << ")"; else if (event) _out << "event " << scopeName << "." << event->name() << "(" << joinHumanReadable(parameters, ",") << ")"; else if (modifier) _out << "modifier " << scopeName << "." << modifier->name(); else solAssert(false, "Unexpected AST node type in function call graph"); } return _out; }
13,199
C++
.cpp
287
43.317073
156
0.759496
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
3,216
DocStringAnalyser.cpp
ethereum_solidity/libsolidity/analysis/DocStringAnalyser.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 /** * @author Christian <c@ethdev.com> * @date 2015 * Parses and analyses the doc strings. * Stores the parsing results in the AST annotations and reports errors. */ #include <libsolidity/analysis/DocStringAnalyser.h> #include <libsolidity/ast/AST.h> #include <libsolidity/ast/TypeProvider.h> #include <liblangutil/ErrorReporter.h> #include <boost/algorithm/string.hpp> using namespace solidity; using namespace solidity::langutil; using namespace solidity::frontend; namespace { void copyMissingTags(std::set<CallableDeclaration const*> const& _baseFunctions, StructurallyDocumentedAnnotation& _target, FunctionType const* _functionType = nullptr) { // Only copy if there is exactly one direct base function. if (_baseFunctions.size() != 1) return; CallableDeclaration const& baseFunction = **_baseFunctions.begin(); auto& sourceDoc = dynamic_cast<StructurallyDocumentedAnnotation const&>(baseFunction.annotation()); for (auto it = sourceDoc.docTags.begin(); it != sourceDoc.docTags.end();) { std::string const& tag = it->first; // Don't copy tag "inheritdoc", custom tags or already existing tags if (tag == "inheritdoc" || _target.docTags.count(tag) || boost::starts_with(tag, "custom")) { it++; continue; } size_t n = 0; // Iterate over all values of the current tag (it's a multimap) for (auto next = sourceDoc.docTags.upper_bound(tag); it != next; it++, n++) { DocTag content = it->second; // Update the parameter name for @return tags if (_functionType && tag == "return") { size_t docParaNameEndPos = content.content.find_first_of(" \t"); std::string const docParameterName = content.content.substr(0, docParaNameEndPos); if ( _functionType->returnParameterNames().size() > n && docParameterName != _functionType->returnParameterNames().at(n) ) { bool baseHasNoName = baseFunction.returnParameterList() && baseFunction.returnParameters().size() > n && baseFunction.returnParameters().at(n)->name().empty(); std::string paramName = _functionType->returnParameterNames().at(n); content.content = (paramName.empty() ? "" : std::move(paramName) + " ") + ( std::string::npos == docParaNameEndPos || baseHasNoName ? content.content : content.content.substr(docParaNameEndPos + 1) ); } } _target.docTags.emplace(tag, content); } } } CallableDeclaration const* findBaseCallable(std::set<CallableDeclaration const*> const& _baseFunctions, int64_t _contractId) { for (CallableDeclaration const* baseFuncCandidate: _baseFunctions) if (baseFuncCandidate->annotation().contract->id() == _contractId) return baseFuncCandidate; else if (auto callable = findBaseCallable(baseFuncCandidate->annotation().baseFunctions, _contractId)) return callable; return nullptr; } bool parameterNamesEqual(CallableDeclaration const& _a, CallableDeclaration const& _b) { return boost::range::equal(_a.parameters(), _b.parameters(), [](auto const& pa, auto const& pb) { return pa->name() == pb->name(); }); } } bool DocStringAnalyser::analyseDocStrings(SourceUnit const& _sourceUnit) { auto errorWatcher = m_errorReporter.errorWatcher(); _sourceUnit.accept(*this); return errorWatcher.ok(); } bool DocStringAnalyser::visit(FunctionDefinition const& _function) { if (!_function.isConstructor()) handleCallable(_function, _function, _function.annotation(), TypeProvider::function(_function)); return true; } bool DocStringAnalyser::visit(VariableDeclaration const& _variable) { if (!_variable.isStateVariable() && !_variable.isFileLevelVariable()) return false; auto const* getterType = TypeProvider::function(_variable); if (CallableDeclaration const* baseFunction = resolveInheritDoc(_variable.annotation().baseFunctions, _variable, _variable.annotation())) copyMissingTags({baseFunction}, _variable.annotation(), getterType); else if (_variable.annotation().docTags.empty()) copyMissingTags(_variable.annotation().baseFunctions, _variable.annotation(), getterType); return false; } bool DocStringAnalyser::visit(ModifierDefinition const& _modifier) { handleCallable(_modifier, _modifier, _modifier.annotation()); return true; } bool DocStringAnalyser::visit(EventDefinition const& _event) { handleCallable(_event, _event, _event.annotation()); return true; } bool DocStringAnalyser::visit(ErrorDefinition const& _error) { handleCallable(_error, _error, _error.annotation()); return true; } void DocStringAnalyser::handleCallable( CallableDeclaration const& _callable, StructurallyDocumented const& _node, StructurallyDocumentedAnnotation& _annotation, FunctionType const* _functionType ) { if (CallableDeclaration const* baseFunction = resolveInheritDoc(_callable.annotation().baseFunctions, _node, _annotation)) copyMissingTags({baseFunction}, _annotation, _functionType); else if ( _annotation.docTags.empty() && _callable.annotation().baseFunctions.size() == 1 && parameterNamesEqual(_callable, **_callable.annotation().baseFunctions.begin()) ) copyMissingTags(_callable.annotation().baseFunctions, _annotation, _functionType); } CallableDeclaration const* DocStringAnalyser::resolveInheritDoc( std::set<CallableDeclaration const*> const& _baseFuncs, StructurallyDocumented const& _node, StructurallyDocumentedAnnotation& _annotation ) { if (_annotation.inheritdocReference == nullptr) return nullptr; if (auto const callable = findBaseCallable(_baseFuncs, _annotation.inheritdocReference->id())) return callable; m_errorReporter.docstringParsingError( 4682_error, _node.documentation()->location(), "Documentation tag @inheritdoc references contract \"" + _annotation.inheritdocReference->name() + "\", but the contract does not contain a function that is overridden by this function." ); return nullptr; }
6,542
C++
.cpp
165
36.933333
168
0.759899
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
3,217
Common.cpp
ethereum_solidity/libsolidity/experimental/codegen/Common.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libsolidity/experimental/codegen/Common.h> #include <libsolidity/experimental/ast/TypeSystem.h> #include <libsolidity/experimental/ast/TypeSystemHelper.h> #include <libsolutil/CommonIO.h> #include <libyul/AsmPrinter.h> using namespace solidity::langutil; using namespace solidity::frontend; using namespace solidity::util; using namespace solidity::yul; namespace solidity::frontend::experimental { std::string IRNames::function(TypeEnvironment const& _env, FunctionDefinition const& _function, Type _type) { if (_function.isConstructor()) return constructor(*_function.annotation().contract); return "fun_" + _function.name() + "_" + std::to_string(_function.id()) + "$" + TypeEnvironmentHelpers{_env}.canonicalTypeName(_type) + "$"; } std::string IRNames::function(VariableDeclaration const& _varDecl) { return "getter_fun_" + _varDecl.name() + "_" + std::to_string(_varDecl.id()); } std::string IRNames::creationObject(ContractDefinition const& _contract) { return _contract.name() + "_" + toString(_contract.id()); } std::string IRNames::deployedObject(ContractDefinition const& _contract) { return _contract.name() + "_" + toString(_contract.id()) + "_deployed"; } std::string IRNames::constructor(ContractDefinition const& _contract) { return "constructor_" + _contract.name() + "_" + std::to_string(_contract.id()); } std::string IRNames::localVariable(VariableDeclaration const& _declaration) { return "var_" + _declaration.name() + '_' + std::to_string(_declaration.id()); } std::string IRNames::localVariable(Expression const& _expression) { return "expr_" + std::to_string(_expression.id()); } }
2,326
C++
.cpp
56
39.857143
141
0.76032
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,218
IRGenerator.cpp
ethereum_solidity/libsolidity/experimental/codegen/IRGenerator.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libsolidity/experimental/codegen/IRGenerator.h> #include <libsolidity/experimental/codegen/IRGenerationContext.h> #include <libsolidity/experimental/codegen/IRGeneratorForStatements.h> #include <libsolidity/experimental/codegen/Common.h> #include <libsolidity/experimental/analysis/Analysis.h> #include <libsolidity/experimental/analysis/TypeInference.h> #include <libsolidity/experimental/ast/TypeSystemHelper.h> #include <libyul/AsmPrinter.h> #include <libyul/AST.h> #include <libyul/optimiser/ASTCopier.h> #include <liblangutil/SourceReferenceFormatter.h> #include <libsolutil/Whiskers.h> #include <range/v3/view/drop_last.hpp> #include <variant> using namespace solidity; using namespace solidity::frontend::experimental; using namespace solidity::langutil; using namespace solidity::util; IRGenerator::IRGenerator( EVMVersion _evmVersion, std::optional<uint8_t> _eofVersion, frontend::RevertStrings, std::map<std::string, unsigned int>, DebugInfoSelection const&, CharStreamProvider const*, Analysis const& _analysis ): m_evmVersion(_evmVersion), m_eofVersion(_eofVersion), //m_debugInfoSelection(_debugInfoSelection), //m_soliditySourceProvider(_soliditySourceProvider), m_env(_analysis.typeSystem().env().clone()), m_context{_analysis, &m_env, {}, {}} { } std::string IRGenerator::run( ContractDefinition const& _contract, bytes const& /*_cborMetadata*/, std::map<ContractDefinition const*, std::string_view const> const& /*_otherYulSources*/ ) { solUnimplementedAssert(!m_eofVersion.has_value(), "Experimental IRGenerator not implemented for EOF"); Whiskers t(R"( object "<CreationObject>" { code { codecopy(0, dataoffset("<DeployedObject>"), datasize("<DeployedObject>")) return(0, datasize("<DeployedObject>")) } object "<DeployedObject>" { code { <code> } } } )"); t("CreationObject", IRNames::creationObject(_contract)); t("DeployedObject", IRNames::deployedObject(_contract)); t("code", generate(_contract)); return t.render(); } std::string IRGenerator::generate(ContractDefinition const& _contract) { std::stringstream code; code << "{\n"; if (_contract.fallbackFunction()) { auto type = m_context.analysis.annotation<TypeInference>(*_contract.fallbackFunction()).type; solAssert(type); type = m_context.env->resolve(*type); code << IRNames::function(*m_context.env, *_contract.fallbackFunction(), *type) << "()\n"; m_context.enqueueFunctionDefinition(_contract.fallbackFunction(), *type); } code << "revert(0,0)\n"; code << "}\n"; while (!m_context.functionQueue.empty()) { auto queueEntry = m_context.functionQueue.front(); m_context.functionQueue.pop_front(); auto& generatedTypes = m_context.generatedFunctions.insert(std::make_pair(queueEntry.function, std::vector<Type>{})).first->second; if (!util::contains_if(generatedTypes, [&](auto const& _generatedType) { return m_context.env->typeEquals(_generatedType, queueEntry.type); })) { generatedTypes.emplace_back(queueEntry.type); code << generate(*queueEntry.function, queueEntry.type); } } return code.str(); } std::string IRGenerator::generate(FunctionDefinition const& _function, Type _type) { TypeEnvironment newEnv = m_context.env->clone(); ScopedSaveAndRestore envRestore{m_context.env, &newEnv}; auto type = m_context.analysis.annotation<TypeInference>(_function).type; solAssert(type); for (auto err: newEnv.unify(*type, _type)) { TypeEnvironmentHelpers helper{newEnv}; solAssert(false, helper.typeToString(*type) + " <-> " + helper.typeToString(_type)); } std::stringstream code; code << "function " << IRNames::function(newEnv, _function, _type) << "("; if (_function.parameters().size() > 1) for (auto const& arg: _function.parameters() | ranges::views::drop_last(1)) code << IRNames::localVariable(*arg) << ", "; if (!_function.parameters().empty()) code << IRNames::localVariable(*_function.parameters().back()); code << ")"; if (_function.experimentalReturnExpression()) { auto returnType = m_context.analysis.annotation<TypeInference>(*_function.experimentalReturnExpression()).type; solAssert(returnType); if (!m_env.typeEquals(*returnType, m_context.analysis.typeSystem().type(PrimitiveType::Unit, {}))) { // TODO: destructure tuples. code << " -> " << IRNames::localVariable(*_function.experimentalReturnExpression()) << " "; } } code << "{\n"; for (auto _statement: _function.body().statements()) { IRGeneratorForStatements statementGenerator{m_context}; code << statementGenerator.generate(*_statement); } code << "}\n"; return code.str(); }
5,297
C++
.cpp
138
36.065217
145
0.749903
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,219
IRGeneratorForStatements.cpp
ethereum_solidity/libsolidity/experimental/codegen/IRGeneratorForStatements.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libsolidity/experimental/codegen/IRGeneratorForStatements.h> #include <libsolidity/experimental/analysis/Analysis.h> #include <libsolidity/experimental/analysis/TypeClassRegistration.h> #include <libsolidity/experimental/analysis/TypeInference.h> #include <libsolidity/experimental/analysis/TypeRegistration.h> #include <libsolidity/experimental/ast/TypeSystemHelper.h> #include <libyul/AsmPrinter.h> #include <libyul/AST.h> #include <libyul/backends/evm/EVMDialect.h> #include <libyul/optimiser/ASTCopier.h> #include <libsolidity/experimental/codegen/Common.h> #include <range/v3/view/drop_last.hpp> using namespace solidity; using namespace solidity::util; using namespace solidity::frontend; using namespace solidity::frontend::experimental; using namespace std::string_literals; std::string IRGeneratorForStatements::generate(ASTNode const& _node) { _node.accept(*this); return m_code.str(); } namespace { struct CopyTranslate: public yul::ASTCopier { CopyTranslate( IRGenerationContext const& _context, yul::Dialect const& _dialect, std::map<yul::Identifier const*, InlineAssemblyAnnotation::ExternalIdentifierInfo> _references ): m_context(_context), m_dialect(_dialect), m_references(std::move(_references)) {} using ASTCopier::operator(); yul::Expression operator()(yul::Identifier const& _identifier) override { // The operator() function is only called in lvalue context. In rvalue context, // only translate(yul::Identifier) is called. if (m_references.count(&_identifier)) return translateReference(_identifier); else return ASTCopier::operator()(_identifier); } yul::YulName translateIdentifier(yul::YulName _name) override { if (m_dialect.findBuiltin(_name.str())) return _name; else return yul::YulName{"usr$" + _name.str()}; } yul::Identifier translate(yul::Identifier const& _identifier) override { if (!m_references.count(&_identifier)) return ASTCopier::translate(_identifier); yul::Expression translated = translateReference(_identifier); solAssert(std::holds_alternative<yul::Identifier>(translated)); return std::get<yul::Identifier>(std::move(translated)); } private: /// Translates a reference to a local variable, potentially including /// a suffix. Might return a literal, which causes this to be invalid in /// lvalue-context. yul::Expression translateReference(yul::Identifier const& _identifier) { auto const& reference = m_references.at(&_identifier); auto const varDecl = dynamic_cast<VariableDeclaration const*>(reference.declaration); solAssert(varDecl, "External reference in inline assembly to something that is not a variable declaration."); auto type = m_context.analysis.annotation<TypeInference>(*varDecl).type; solAssert(type); solAssert(m_context.env->typeEquals(*type, m_context.analysis.typeSystem().type(PrimitiveType::Word, {}))); std::string value = IRNames::localVariable(*varDecl); return yul::Identifier{_identifier.debugData, yul::YulName{value}}; } IRGenerationContext const& m_context; yul::Dialect const& m_dialect; std::map<yul::Identifier const*, InlineAssemblyAnnotation::ExternalIdentifierInfo> m_references; }; } bool IRGeneratorForStatements::visit(TupleExpression const& _tupleExpression) { std::vector<std::string> components; for (auto const& component: _tupleExpression.components()) { solUnimplementedAssert(component); component->accept(*this); components.emplace_back(IRNames::localVariable(*component)); } solUnimplementedAssert(false, "No support for tuples."); return false; } bool IRGeneratorForStatements::visit(InlineAssembly const& _assembly) { CopyTranslate bodyCopier{m_context, _assembly.dialect(), _assembly.annotation().externalReferences}; yul::Statement modified = bodyCopier(_assembly.operations().root()); solAssert(std::holds_alternative<yul::Block>(modified)); m_code << yul::AsmPrinter(_assembly.dialect())(std::get<yul::Block>(modified)) << "\n"; return false; } bool IRGeneratorForStatements::visit(VariableDeclarationStatement const& _variableDeclarationStatement) { if (_variableDeclarationStatement.initialValue()) _variableDeclarationStatement.initialValue()->accept(*this); solAssert(_variableDeclarationStatement.declarations().size() == 1, "multi variable declarations not supported"); VariableDeclaration const* variableDeclaration = _variableDeclarationStatement.declarations().front().get(); solAssert(variableDeclaration); // TODO: check the type of the variable; register local variable; initialize m_code << "let " << IRNames::localVariable(*variableDeclaration); if (_variableDeclarationStatement.initialValue()) m_code << " := " << IRNames::localVariable(*_variableDeclarationStatement.initialValue()); m_code << "\n"; return false; } bool IRGeneratorForStatements::visit(ExpressionStatement const&) { return true; } bool IRGeneratorForStatements::visit(Identifier const& _identifier) { if (auto const* var = dynamic_cast<VariableDeclaration const*>(_identifier.annotation().referencedDeclaration)) { m_code << "let " << IRNames::localVariable(_identifier) << " := " << IRNames::localVariable(*var) << "\n"; } else if (auto const* function = dynamic_cast<FunctionDefinition const*>(_identifier.annotation().referencedDeclaration)) solAssert(m_expressionDeclaration.emplace(&_identifier, function).second); else if (auto const* typeClass = dynamic_cast<TypeClassDefinition const*>(_identifier.annotation().referencedDeclaration)) solAssert(m_expressionDeclaration.emplace(&_identifier, typeClass).second); else if (auto const* typeDefinition = dynamic_cast<TypeDefinition const*>(_identifier.annotation().referencedDeclaration)) solAssert(m_expressionDeclaration.emplace(&_identifier, typeDefinition).second); else solAssert(false, "Unsupported Identifier"); return false; } void IRGeneratorForStatements::endVisit(Return const& _return) { if (Expression const* value = _return.expression()) { solAssert(_return.annotation().function, "Invalid return."); solAssert(_return.annotation().function->experimentalReturnExpression(), "Invalid return."); m_code << IRNames::localVariable(*_return.annotation().function->experimentalReturnExpression()) << " := " << IRNames::localVariable(*value) << "\n"; } m_code << "leave\n"; } experimental::Type IRGeneratorForStatements::type(ASTNode const& _node) const { auto type = m_context.analysis.annotation<TypeInference>(_node).type; solAssert(type); return *type; } void IRGeneratorForStatements::endVisit(BinaryOperation const& _binaryOperation) { TypeSystemHelpers helper{m_context.analysis.typeSystem()}; Type leftType = type(_binaryOperation.leftExpression()); Type rightType = type(_binaryOperation.rightExpression()); Type resultType = type(_binaryOperation); Type functionType = helper.functionType(helper.tupleType({leftType, rightType}), resultType); auto [typeClass, memberName] = m_context.analysis.annotation<TypeInference>().operators.at(_binaryOperation.getOperator()); auto const& functionDefinition = resolveTypeClassFunction(typeClass, memberName, functionType); // TODO: deduplicate with FunctionCall // TODO: get around resolveRecursive by passing the environment further down? functionType = m_context.env->resolveRecursive(functionType); m_context.enqueueFunctionDefinition(&functionDefinition, functionType); // TODO: account for return stack size m_code << "let " << IRNames::localVariable(_binaryOperation) << " := " << IRNames::function(*m_context.env, functionDefinition, functionType) << "(" << IRNames::localVariable(_binaryOperation.leftExpression()) << ", " << IRNames::localVariable(_binaryOperation.rightExpression()) << ")\n"; } namespace { TypeRegistration::TypeClassInstantiations const& typeClassInstantiations(IRGenerationContext const& _context, TypeClass _class) { auto const* typeClassDeclaration = _context.analysis.typeSystem().typeClassDeclaration(_class); if (typeClassDeclaration) return _context.analysis.annotation<TypeRegistration>(*typeClassDeclaration).instantiations; // TODO: better mechanism than fetching by name. auto& instantiations = _context.analysis.annotation<TypeRegistration>().builtinClassInstantiations; auto& builtinClassesByName = _context.analysis.annotation<TypeInference>().builtinClassesByName; return instantiations.at(builtinClassesByName.at(_context.analysis.typeSystem().typeClassName(_class))); } } FunctionDefinition const& IRGeneratorForStatements::resolveTypeClassFunction(TypeClass _class, std::string _name, Type _type) { TypeSystemHelpers helper{m_context.analysis.typeSystem()}; TypeEnvironment env = m_context.env->clone(); Type genericFunctionType = env.fresh(m_context.analysis.annotation<TypeInference>().typeClassFunctions.at(_class).at(_name)); auto typeVars = TypeEnvironmentHelpers{env}.typeVars(genericFunctionType); solAssert(typeVars.size() == 1); solAssert(env.unify(genericFunctionType, _type).empty()); auto typeClassInstantiation = std::get<0>(helper.destTypeConstant(env.resolve(typeVars.front()))); auto const& instantiations = typeClassInstantiations(m_context, _class); TypeClassInstantiation const* instantiation = instantiations.at(typeClassInstantiation); FunctionDefinition const* functionDefinition = nullptr; for (auto const& node: instantiation->subNodes()) { auto const* def = dynamic_cast<FunctionDefinition const*>(node.get()); solAssert(def); if (def->name() == _name) { functionDefinition = def; break; } } solAssert(functionDefinition); return *functionDefinition; } void IRGeneratorForStatements::endVisit(MemberAccess const& _memberAccess) { TypeSystemHelpers helper{m_context.analysis.typeSystem()}; // TODO: avoid resolve? auto expressionType = m_context.env->resolve(type(_memberAccess.expression())); auto constructor = std::get<0>(helper.destTypeConstant(expressionType)); auto memberAccessType = type(_memberAccess); // TODO: better mechanism if (constructor == m_context.analysis.typeSystem().constructor(PrimitiveType::Bool)) { if (_memberAccess.memberName() == "abs") solAssert(m_expressionDeclaration.emplace(&_memberAccess, Builtins::ToBool).second); else if (_memberAccess.memberName() == "rep") solAssert(m_expressionDeclaration.emplace(&_memberAccess, Builtins::FromBool).second); return; } auto const* declaration = m_context.analysis.typeSystem().constructorInfo(constructor).typeDeclaration; solAssert(declaration); if (auto const* typeClassDefinition = dynamic_cast<TypeClassDefinition const*>(declaration)) { solAssert(m_context.analysis.annotation<TypeClassRegistration>(*typeClassDefinition).typeClass.has_value()); TypeClass typeClass = m_context.analysis.annotation<TypeClassRegistration>(*typeClassDefinition).typeClass.value(); solAssert(m_expressionDeclaration.emplace( &_memberAccess, &resolveTypeClassFunction(typeClass, _memberAccess.memberName(), memberAccessType) ).second); } else if (dynamic_cast<TypeDefinition const*>(declaration)) { if (_memberAccess.memberName() == "abs" || _memberAccess.memberName() == "rep") solAssert(m_expressionDeclaration.emplace(&_memberAccess, Builtins::Identity).second); else solAssert(false); } else solAssert(false); } bool IRGeneratorForStatements::visit(ElementaryTypeNameExpression const&) { // TODO: is this always a no-op? return false; } void IRGeneratorForStatements::endVisit(FunctionCall const& _functionCall) { Type functionType = type(_functionCall.expression()); solUnimplementedAssert(m_expressionDeclaration.count(&_functionCall.expression()) != 0, "No support for calling functions pointers yet."); auto declaration = m_expressionDeclaration.at(&_functionCall.expression()); if (auto builtin = std::get_if<Builtins>(&declaration)) { switch (*builtin) { case Builtins::FromBool: case Builtins::Identity: solAssert(_functionCall.arguments().size() == 1); m_code << "let " << IRNames::localVariable(_functionCall) << " := " << IRNames::localVariable(*_functionCall.arguments().front()) << "\n"; return; case Builtins::ToBool: solAssert(_functionCall.arguments().size() == 1); m_code << "let " << IRNames::localVariable(_functionCall) << " := iszero(iszero(" << IRNames::localVariable(*_functionCall.arguments().front()) << "))\n"; return; } solAssert(false); } FunctionDefinition const* functionDefinition = dynamic_cast<FunctionDefinition const*>(std::get<Declaration const*>(declaration)); solAssert(functionDefinition); // TODO: get around resolveRecursive by passing the environment further down? functionType = m_context.env->resolveRecursive(functionType); m_context.enqueueFunctionDefinition(functionDefinition, functionType); // TODO: account for return stack size solAssert(!functionDefinition->returnParameterList()); if (functionDefinition->experimentalReturnExpression()) m_code << "let " << IRNames::localVariable(_functionCall) << " := "; m_code << IRNames::function(*m_context.env, *functionDefinition, functionType) << "("; auto const& arguments = _functionCall.arguments(); if (arguments.size() > 1) for (auto arg: arguments | ranges::views::drop_last(1)) m_code << IRNames::localVariable(*arg) << ", "; if (!arguments.empty()) m_code << IRNames::localVariable(*arguments.back()); m_code << ")\n"; } bool IRGeneratorForStatements::visit(FunctionCall const&) { return true; } bool IRGeneratorForStatements::visit(Block const& _block) { m_code << "{\n"; solAssert(!_block.unchecked()); for (auto const& statement: _block.statements()) statement->accept(*this); m_code << "}\n"; return false; } bool IRGeneratorForStatements::visit(IfStatement const& _ifStatement) { _ifStatement.condition().accept(*this); if (_ifStatement.falseStatement()) { m_code << "switch " << IRNames::localVariable(_ifStatement.condition()) << " {\n"; m_code << "case 0 {\n"; _ifStatement.falseStatement()->accept(*this); m_code << "}\n"; m_code << "default {\n"; _ifStatement.trueStatement().accept(*this); m_code << "}\n"; } else { m_code << "if " << IRNames::localVariable(_ifStatement.condition()) << " {\n"; _ifStatement.trueStatement().accept(*this); m_code << "}\n"; } return false; } bool IRGeneratorForStatements::visit(Assignment const& _assignment) { _assignment.rightHandSide().accept(*this); auto const* lhs = dynamic_cast<Identifier const*>(&_assignment.leftHandSide()); solAssert(lhs, "Can only assign to identifiers."); auto const* lhsVar = dynamic_cast<VariableDeclaration const*>(lhs->annotation().referencedDeclaration); solAssert(lhsVar, "Can only assign to identifiers referring to variables."); m_code << IRNames::localVariable(*lhsVar) << " := " << IRNames::localVariable(_assignment.rightHandSide()) << "\n"; m_code << "let " << IRNames::localVariable(_assignment) << " := " << IRNames::localVariable(*lhsVar) << "\n"; return false; } bool IRGeneratorForStatements::visitNode(ASTNode const&) { solAssert(false, "Unsupported AST node during statement code generation."); }
15,720
C++
.cpp
345
43.353623
157
0.77158
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,220
FunctionDependencyAnalysis.cpp
ethereum_solidity/libsolidity/experimental/analysis/FunctionDependencyAnalysis.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libsolidity/experimental/analysis/Analysis.h> #include <libsolidity/experimental/analysis/FunctionDependencyAnalysis.h> using namespace solidity::frontend::experimental; using namespace solidity::util; FunctionDependencyAnalysis::FunctionDependencyAnalysis(Analysis& _analysis): m_analysis(_analysis), m_errorReporter(_analysis.errorReporter()) { } bool FunctionDependencyAnalysis::analyze(SourceUnit const& _sourceUnit) { _sourceUnit.accept(*this); return !m_errorReporter.hasErrors(); } bool FunctionDependencyAnalysis::visit(FunctionDefinition const& _functionDefinition) { solAssert(!m_currentFunction); m_currentFunction = &_functionDefinition; // Insert a function definition pointer that maps to an empty set; the pointed to set will later be // populated in ``endVisit(Identifier const& _identifier)`` if ``m_currentFunction`` references another. auto [_, inserted] = annotation().functionCallGraph.edges.try_emplace( m_currentFunction, std::set<FunctionDefinition const*, ASTCompareByID<FunctionDefinition>>{} ); solAssert(inserted); return true; } void FunctionDependencyAnalysis::endVisit(FunctionDefinition const&) { m_currentFunction = nullptr; } void FunctionDependencyAnalysis::endVisit(Identifier const& _identifier) { auto const* callee = dynamic_cast<FunctionDefinition const*>(_identifier.annotation().referencedDeclaration); // Check that the identifier is within a function body and is a function, and add it to the graph // as an ``m_currentFunction`` -> ``callee`` edge. if (m_currentFunction && callee) addEdge(m_currentFunction, callee); } void FunctionDependencyAnalysis::addEdge(FunctionDefinition const* _caller, FunctionDefinition const* _callee) { annotation().functionCallGraph.edges[_caller].insert(_callee); } FunctionDependencyAnalysis::GlobalAnnotation& FunctionDependencyAnalysis::annotation() { return m_analysis.annotation<FunctionDependencyAnalysis>(); }
2,621
C++
.cpp
60
41.916667
110
0.806983
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,221
TypeRegistration.cpp
ethereum_solidity/libsolidity/experimental/analysis/TypeRegistration.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libsolidity/experimental/analysis/TypeRegistration.h> #include <libsolidity/experimental/analysis/Analysis.h> #include <libsolidity/experimental/ast/TypeSystemHelper.h> #include <liblangutil/Exceptions.h> #include <libyul/AsmAnalysis.h> #include <libyul/AsmAnalysisInfo.h> #include <libyul/AST.h> using namespace solidity::frontend; using namespace solidity::frontend::experimental; using namespace solidity::langutil; TypeRegistration::TypeRegistration(Analysis& _analysis): m_analysis(_analysis), m_errorReporter(_analysis.errorReporter()), m_typeSystem(_analysis.typeSystem()) { } bool TypeRegistration::analyze(SourceUnit const& _sourceUnit) { _sourceUnit.accept(*this); return !m_errorReporter.hasErrors(); } bool TypeRegistration::visit(TypeClassDefinition const& _typeClassDefinition) { if (annotation(_typeClassDefinition).typeConstructor) return false; annotation(_typeClassDefinition).typeConstructor = m_typeSystem.declareTypeConstructor( _typeClassDefinition.name(), "t_" + *_typeClassDefinition.annotation().canonicalName + "_" + util::toString(_typeClassDefinition.id()), 0, &_typeClassDefinition ); return true; } bool TypeRegistration::visit(Builtin const& _builtin) { if (annotation(_builtin).typeConstructor) return false; auto primitiveType = [&](std::string _name) -> std::optional<PrimitiveType> { if (_name == "void") return PrimitiveType::Void; if (_name == "fun") return PrimitiveType::Function; if (_name == "unit") return PrimitiveType::Unit; if (_name == "pair") return PrimitiveType::Pair; if (_name == "word") return PrimitiveType::Word; if (_name == "integer") return PrimitiveType::Integer; if (_name == "bool") return PrimitiveType::Bool; return std::nullopt; }(_builtin.nameParameter()); if (!primitiveType.has_value()) m_errorReporter.fatalTypeError( 7758_error, _builtin.location(), "Expected the name of a built-in primitive type." ); annotation(_builtin).typeConstructor = m_typeSystem.constructor(primitiveType.value()); return true; } void TypeRegistration::endVisit(ElementaryTypeNameExpression const & _typeNameExpression) { if (annotation(_typeNameExpression).typeConstructor) return; // TODO: this is not visited in the ElementaryTypeNameExpression visit - is that intentional? _typeNameExpression.type().accept(*this); if (auto constructor = annotation(_typeNameExpression.type()).typeConstructor) annotation(_typeNameExpression).typeConstructor = constructor; else solAssert(m_errorReporter.hasErrors()); } bool TypeRegistration::visit(UserDefinedTypeName const& _userDefinedTypeName) { if (annotation(_userDefinedTypeName).typeConstructor) return false; auto const* declaration = _userDefinedTypeName.pathNode().annotation().referencedDeclaration; if (!declaration) { // TODO: fatal/non-fatal m_errorReporter.fatalTypeError(5096_error, _userDefinedTypeName.pathNode().location(), "Expected declaration."); return false; } declaration->accept(*this); if (!(annotation(_userDefinedTypeName).typeConstructor = annotation(*declaration).typeConstructor)) { // TODO: fatal/non-fatal m_errorReporter.fatalTypeError(9831_error, _userDefinedTypeName.pathNode().location(), "Expected type declaration."); return false; } return true; } bool TypeRegistration::visit(TypeClassInstantiation const& _typeClassInstantiation) { if (annotation(_typeClassInstantiation).typeConstructor) return false; _typeClassInstantiation.typeConstructor().accept(*this); auto typeConstructor = annotation(_typeClassInstantiation.typeConstructor()).typeConstructor; if (!typeConstructor) { m_errorReporter.typeError(5577_error, _typeClassInstantiation.typeConstructor().location(), "Invalid type name."); return false; } auto* instantiations = std::visit(util::GenericVisitor{ [&](ASTPointer<IdentifierPath> _path) -> TypeClassInstantiations* { if (TypeClassDefinition const* classDefinition = dynamic_cast<TypeClassDefinition const*>(_path->annotation().referencedDeclaration)) return &annotation(*classDefinition).instantiations; m_errorReporter.typeError(3570_error, _typeClassInstantiation.typeClass().location(), "Expected a type class."); return nullptr; }, [&](Token _token) -> TypeClassInstantiations* { if (auto typeClass = builtinClassFromToken(_token)) return &annotation().builtinClassInstantiations[*typeClass]; m_errorReporter.typeError(5262_error, _typeClassInstantiation.typeClass().location(), "Expected a type class."); return nullptr; } }, _typeClassInstantiation.typeClass().name()); if (!instantiations) return false; if ( auto [instantiation, newlyInserted] = instantiations->emplace(*typeConstructor, &_typeClassInstantiation); !newlyInserted ) { SecondarySourceLocation ssl; ssl.append("Previous instantiation.", instantiation->second->location()); m_errorReporter.typeError(6620_error, _typeClassInstantiation.location(), ssl, "Duplicate type class instantiation."); } return true; } bool TypeRegistration::visit(TypeDefinition const& _typeDefinition) { return !annotation(_typeDefinition).typeConstructor.has_value(); } void TypeRegistration::endVisit(TypeDefinition const& _typeDefinition) { if (annotation(_typeDefinition).typeConstructor.has_value()) return; if (auto const* builtin = dynamic_cast<Builtin const*>(_typeDefinition.typeExpression())) { auto [previousDefinitionIt, inserted] = annotation().builtinTypeDefinitions.try_emplace( builtin->nameParameter(), &_typeDefinition ); if (inserted) annotation(_typeDefinition).typeConstructor = annotation(*builtin).typeConstructor; else { auto const& [builtinName, previousDefinition] = *previousDefinitionIt; m_errorReporter.typeError( 9609_error, _typeDefinition.location(), SecondarySourceLocation{}.append("Previous definition:", previousDefinition->location()), "Duplicate builtin type definition." ); } } else annotation(_typeDefinition).typeConstructor = m_typeSystem.declareTypeConstructor( _typeDefinition.name(), "t_" + *_typeDefinition.annotation().canonicalName + "_" + util::toString(_typeDefinition.id()), _typeDefinition.arguments() ? _typeDefinition.arguments()->parameters().size() : 0, &_typeDefinition ); } TypeRegistration::Annotation& TypeRegistration::annotation(ASTNode const& _node) { return m_analysis.annotation<TypeRegistration>(_node); } TypeRegistration::GlobalAnnotation& TypeRegistration::annotation() { return m_analysis.annotation<TypeRegistration>(); }
7,234
C++
.cpp
184
36.842391
136
0.781005
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,222
Analysis.cpp
ethereum_solidity/libsolidity/experimental/analysis/Analysis.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libsolidity/experimental/analysis/Analysis.h> #include <libsolidity/experimental/analysis/DebugWarner.h> #include <libsolidity/experimental/analysis/FunctionDependencyAnalysis.h> #include <libsolidity/experimental/analysis/SyntaxRestrictor.h> #include <libsolidity/experimental/analysis/TypeClassRegistration.h> #include <libsolidity/experimental/analysis/TypeInference.h> #include <libsolidity/experimental/analysis/TypeRegistration.h> using namespace solidity::langutil; using namespace solidity::frontend::experimental; // TODO: creating all of them for all nodes up front may be wasteful, we should improve the mechanism. struct Analysis::AnnotationContainer { TypeClassRegistration::Annotation typeClassRegistrationAnnotation; TypeRegistration::Annotation typeRegistrationAnnotation; TypeInference::Annotation typeInferenceAnnotation; }; struct Analysis::GlobalAnnotationContainer { FunctionDependencyAnalysis::GlobalAnnotation functionDependencyGraphAnnotation; TypeClassRegistration::GlobalAnnotation typeClassRegistrationAnnotation; TypeRegistration::GlobalAnnotation typeRegistrationAnnotation; TypeInference::GlobalAnnotation typeInferenceAnnotation; }; template<> TypeClassRegistration::Annotation& solidity::frontend::experimental::detail::AnnotationFetcher<TypeClassRegistration>::get(ASTNode const& _node) { return analysis.annotationContainer(_node).typeClassRegistrationAnnotation; } template<> TypeClassRegistration::GlobalAnnotation const& solidity::frontend::experimental::detail::ConstAnnotationFetcher<TypeClassRegistration>::get() const { return analysis.annotationContainer().typeClassRegistrationAnnotation; } template<> TypeClassRegistration::GlobalAnnotation& solidity::frontend::experimental::detail::AnnotationFetcher<TypeClassRegistration>::get() { return analysis.annotationContainer().typeClassRegistrationAnnotation; } template<> TypeClassRegistration::Annotation const& solidity::frontend::experimental::detail::ConstAnnotationFetcher<TypeClassRegistration>::get(ASTNode const& _node) const { return analysis.annotationContainer(_node).typeClassRegistrationAnnotation; } template<> FunctionDependencyAnalysis::GlobalAnnotation const& solidity::frontend::experimental::detail::ConstAnnotationFetcher<FunctionDependencyAnalysis>::get() const { return analysis.annotationContainer().functionDependencyGraphAnnotation; } template<> FunctionDependencyAnalysis::GlobalAnnotation& solidity::frontend::experimental::detail::AnnotationFetcher<FunctionDependencyAnalysis>::get() { return analysis.annotationContainer().functionDependencyGraphAnnotation; } template<> TypeRegistration::Annotation& solidity::frontend::experimental::detail::AnnotationFetcher<TypeRegistration>::get(ASTNode const& _node) { return analysis.annotationContainer(_node).typeRegistrationAnnotation; } template<> TypeRegistration::GlobalAnnotation const& solidity::frontend::experimental::detail::ConstAnnotationFetcher<TypeRegistration>::get() const { return analysis.annotationContainer().typeRegistrationAnnotation; } template<> TypeRegistration::GlobalAnnotation& solidity::frontend::experimental::detail::AnnotationFetcher<TypeRegistration>::get() { return analysis.annotationContainer().typeRegistrationAnnotation; } template<> TypeRegistration::Annotation const& solidity::frontend::experimental::detail::ConstAnnotationFetcher<TypeRegistration>::get(ASTNode const& _node) const { return analysis.annotationContainer(_node).typeRegistrationAnnotation; } template<> TypeInference::Annotation& solidity::frontend::experimental::detail::AnnotationFetcher<TypeInference>::get(ASTNode const& _node) { return analysis.annotationContainer(_node).typeInferenceAnnotation; } template<> TypeInference::Annotation const& solidity::frontend::experimental::detail::ConstAnnotationFetcher<TypeInference>::get(ASTNode const& _node) const { return analysis.annotationContainer(_node).typeInferenceAnnotation; } template<> TypeInference::GlobalAnnotation const& solidity::frontend::experimental::detail::ConstAnnotationFetcher<TypeInference>::get() const { return analysis.annotationContainer().typeInferenceAnnotation; } template<> TypeInference::GlobalAnnotation& solidity::frontend::experimental::detail::AnnotationFetcher<TypeInference>::get() { return analysis.annotationContainer().typeInferenceAnnotation; } Analysis::AnnotationContainer& Analysis::annotationContainer(ASTNode const& _node) { solAssert(_node.id() > 0); size_t id = static_cast<size_t>(_node.id()); solAssert(id <= m_maxAstId); return m_annotations[id]; } Analysis::AnnotationContainer const& Analysis::annotationContainer(ASTNode const& _node) const { solAssert(_node.id() > 0); size_t id = static_cast<size_t>(_node.id()); solAssert(id <= m_maxAstId); return m_annotations[id]; } Analysis::Analysis(langutil::ErrorReporter& _errorReporter, uint64_t _maxAstId): m_errorReporter(_errorReporter), m_maxAstId(_maxAstId), m_annotations(std::make_unique<AnnotationContainer[]>(static_cast<size_t>(_maxAstId + 1))), m_globalAnnotation(std::make_unique<GlobalAnnotationContainer>()) { } Analysis::~Analysis() {} template<size_t... Is> std::tuple<std::integral_constant<size_t, Is>...> makeIndexTuple(std::index_sequence<Is...>) { return std::make_tuple( std::integral_constant<size_t, Is>{}...); } bool Analysis::check(std::vector<std::shared_ptr<SourceUnit const>> const& _sourceUnits) { using AnalysisSteps = std::tuple< SyntaxRestrictor, TypeClassRegistration, TypeRegistration, // TODO move after step introduced in https://github.com/ethereum/solidity/pull/14578, but before TypeInference FunctionDependencyAnalysis, TypeInference, DebugWarner >; return std::apply([&](auto... _indexTuple) { return ([&](auto&& _step) { for (auto source: _sourceUnits) if (!_step.analyze(*source)) return false; return true; }(std::tuple_element_t<decltype(_indexTuple)::value, AnalysisSteps>{*this}) && ...); }, makeIndexTuple(std::make_index_sequence<std::tuple_size_v<AnalysisSteps>>{})); /* { SyntaxRestrictor syntaxRestrictor{*this}; for (auto source: _sourceUnits) if (!syntaxRestrictor.analyze(*source)) return false; } { TypeRegistration typeRegistration{*this}; for (auto source: _sourceUnits) if (!typeRegistration.analyze(*source)) return false; } { TypeInference typeInference{*this}; for (auto source: _sourceUnits) if (!typeInference.analyze(*source)) return false; } return true; */ }
7,176
C++
.cpp
175
39.137143
161
0.815835
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,223
TypeInference.cpp
ethereum_solidity/libsolidity/experimental/analysis/TypeInference.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libsolidity/experimental/analysis/TypeInference.h> #include <libsolidity/experimental/analysis/TypeClassRegistration.h> #include <libsolidity/experimental/analysis/TypeRegistration.h> #include <libsolidity/experimental/analysis/Analysis.h> #include <libsolidity/experimental/ast/TypeSystemHelper.h> #include <libsolutil/Numeric.h> #include <libsolutil/StringUtils.h> #include <liblangutil/Exceptions.h> #include <libyul/AsmAnalysis.h> #include <libyul/AsmAnalysisInfo.h> #include <libyul/AST.h> #include <boost/algorithm/string.hpp> #include <range/v3/view/transform.hpp> using namespace solidity; using namespace solidity::frontend; using namespace solidity::frontend::experimental; using namespace solidity::langutil; TypeInference::TypeInference(Analysis& _analysis): m_analysis(_analysis), m_errorReporter(_analysis.errorReporter()), m_typeSystem(_analysis.typeSystem()), m_env(&m_typeSystem.env()), m_voidType(m_typeSystem.type(PrimitiveType::Void, {})), m_wordType(m_typeSystem.type(PrimitiveType::Word, {})), m_integerType(m_typeSystem.type(PrimitiveType::Integer, {})), m_unitType(m_typeSystem.type(PrimitiveType::Unit, {})), m_boolType(m_typeSystem.type(PrimitiveType::Bool, {})) { TypeSystemHelpers helper{m_typeSystem}; auto declareBuiltinClass = [&](std::string _name, BuiltinClass _class) -> TypeClass { auto result = m_typeSystem.declareTypeClass(_name, nullptr); if (auto error = std::get_if<std::string>(&result)) solAssert(!error, *error); TypeClass declaredClass = std::get<TypeClass>(result); // TODO: validation? solAssert(annotation().builtinClassesByName.emplace(_name, _class).second); return annotation().builtinClasses.emplace(_class, declaredClass).first->second; }; auto registeredTypeClass = [&](BuiltinClass _builtinClass) -> TypeClass { return annotation().builtinClasses.at(_builtinClass); }; auto defineConversion = [&](BuiltinClass _builtinClass, PrimitiveType _fromType, std::string _functionName) { annotation().typeClassFunctions[registeredTypeClass(_builtinClass)] = {{ std::move(_functionName), helper.functionType( m_typeSystem.type(_fromType, {}), m_typeSystem.typeClassInfo(registeredTypeClass(_builtinClass)).typeVariable ), }}; }; auto defineBinaryMonoidalOperator = [&](BuiltinClass _builtinClass, Token _token, std::string _functionName) { Type typeVar = m_typeSystem.typeClassInfo(registeredTypeClass(_builtinClass)).typeVariable; annotation().operators.emplace(_token, std::make_tuple(registeredTypeClass(_builtinClass), _functionName)); annotation().typeClassFunctions[registeredTypeClass(_builtinClass)] = {{ std::move(_functionName), helper.functionType( helper.tupleType({typeVar, typeVar}), typeVar ) }}; }; auto defineBinaryCompareOperator = [&](BuiltinClass _builtinClass, Token _token, std::string _functionName) { Type typeVar = m_typeSystem.typeClassInfo(registeredTypeClass(_builtinClass)).typeVariable; annotation().operators.emplace(_token, std::make_tuple(registeredTypeClass(_builtinClass), _functionName)); annotation().typeClassFunctions[registeredTypeClass(_builtinClass)] = {{ std::move(_functionName), helper.functionType( helper.tupleType({typeVar, typeVar}), m_typeSystem.type(PrimitiveType::Bool, {}) ) }}; }; declareBuiltinClass("integer", BuiltinClass::Integer); declareBuiltinClass("*", BuiltinClass::Mul); declareBuiltinClass("+", BuiltinClass::Add); declareBuiltinClass("==", BuiltinClass::Equal); declareBuiltinClass("<", BuiltinClass::Less); declareBuiltinClass("<=", BuiltinClass::LessOrEqual); declareBuiltinClass(">", BuiltinClass::Greater); declareBuiltinClass(">=", BuiltinClass::GreaterOrEqual); defineConversion(BuiltinClass::Integer, PrimitiveType::Integer, "fromInteger"); defineBinaryMonoidalOperator(BuiltinClass::Mul, Token::Mul, "mul"); defineBinaryMonoidalOperator(BuiltinClass::Add, Token::Add, "add"); defineBinaryCompareOperator(BuiltinClass::Equal, Token::Equal, "eq"); defineBinaryCompareOperator(BuiltinClass::Less, Token::LessThan, "lt"); defineBinaryCompareOperator(BuiltinClass::LessOrEqual, Token::LessThanOrEqual, "leq"); defineBinaryCompareOperator(BuiltinClass::Greater, Token::GreaterThan, "gt"); defineBinaryCompareOperator(BuiltinClass::GreaterOrEqual, Token::GreaterThanOrEqual, "geq"); } bool TypeInference::analyze(SourceUnit const& _sourceUnit) { _sourceUnit.accept(*this); return !m_errorReporter.hasErrors(); } bool TypeInference::visit(ForAllQuantifier const& _quantifier) { solAssert(m_expressionContext == ExpressionContext::Term); { ScopedSaveAndRestore expressionContext{m_expressionContext, ExpressionContext::Type}; _quantifier.typeVariableDeclarations().accept(*this); } _quantifier.quantifiedDeclaration().accept(*this); return false; } bool TypeInference::visit(FunctionDefinition const& _functionDefinition) { solAssert(m_expressionContext == ExpressionContext::Term); auto& functionAnnotation = annotation(_functionDefinition); if (functionAnnotation.type) return false; ScopedSaveAndRestore signatureRestore(m_currentFunctionType, std::nullopt); Type argumentsType = m_typeSystem.freshTypeVariable({}); Type returnType = m_typeSystem.freshTypeVariable({}); Type functionType = TypeSystemHelpers{m_typeSystem}.functionType(argumentsType, returnType); m_currentFunctionType = functionType; functionAnnotation.type = functionType; _functionDefinition.parameterList().accept(*this); unify(argumentsType, type(_functionDefinition.parameterList()), _functionDefinition.parameterList().location()); if (_functionDefinition.experimentalReturnExpression()) { ScopedSaveAndRestore expressionContext{m_expressionContext, ExpressionContext::Type}; _functionDefinition.experimentalReturnExpression()->accept(*this); unify( returnType, type(*_functionDefinition.experimentalReturnExpression()), _functionDefinition.experimentalReturnExpression()->location() ); } else unify(returnType, m_unitType, _functionDefinition.location()); if (_functionDefinition.isImplemented()) _functionDefinition.body().accept(*this); return false; } void TypeInference::endVisit(FunctionDefinition const& _functionDefinition) { solAssert(m_expressionContext == ExpressionContext::Term); m_env->fixTypeVars(TypeEnvironmentHelpers{*m_env}.typeVars(type(_functionDefinition))); } void TypeInference::endVisit(Return const& _return) { solAssert(m_currentFunctionType); Type functionReturnType = std::get<1>(TypeSystemHelpers{m_typeSystem}.destFunctionType(*m_currentFunctionType)); if (_return.expression()) unify(functionReturnType, type(*_return.expression()), _return.location()); else unify(functionReturnType, m_unitType, _return.location()); } void TypeInference::endVisit(ParameterList const& _parameterList) { auto& listAnnotation = annotation(_parameterList); solAssert(!listAnnotation.type); listAnnotation.type = TypeSystemHelpers{m_typeSystem}.tupleType( _parameterList.parameters() | ranges::views::transform([&](auto _arg) { return type(*_arg); }) | ranges::to<std::vector<Type>> ); } bool TypeInference::visit(TypeClassDefinition const& _typeClassDefinition) { solAssert(m_expressionContext == ExpressionContext::Term); auto& typeClassDefinitionAnnotation = annotation(_typeClassDefinition); if (typeClassDefinitionAnnotation.type) return false; typeClassDefinitionAnnotation.type = type(&_typeClassDefinition, {}); { ScopedSaveAndRestore expressionContext{m_expressionContext, ExpressionContext::Type}; _typeClassDefinition.typeVariable().accept(*this); } std::map<std::string, Type> functionTypes; solAssert(m_analysis.annotation<TypeClassRegistration>(_typeClassDefinition).typeClass.has_value()); TypeClass typeClass = m_analysis.annotation<TypeClassRegistration>(_typeClassDefinition).typeClass.value(); Type typeVar = m_typeSystem.typeClassVariable(typeClass); unify(type(_typeClassDefinition.typeVariable()), typeVar, _typeClassDefinition.location()); auto& typeMembersAnnotation = annotation().members[typeConstructor(&_typeClassDefinition)]; for (auto subNode: _typeClassDefinition.subNodes()) { subNode->accept(*this); auto const* functionDefinition = dynamic_cast<FunctionDefinition const*>(subNode.get()); solAssert(functionDefinition); auto functionType = type(*functionDefinition); if (!functionTypes.emplace(functionDefinition->name(), functionType).second) m_errorReporter.fatalTypeError(3195_error, functionDefinition->location(), "Function in type class declared multiple times."); auto typeVars = TypeEnvironmentHelpers{*m_env}.typeVars(functionType); if (typeVars.size() != 1) m_errorReporter.fatalTypeError(8379_error, functionDefinition->location(), "Function in type class may only depend on the type class variable."); unify(typeVars.front(), typeVar, functionDefinition->location()); typeMembersAnnotation[functionDefinition->name()] = TypeMember{functionType}; } annotation().typeClassFunctions[typeClass] = std::move(functionTypes); for (auto [functionName, functionType]: functionTypes) { TypeEnvironmentHelpers helper{*m_env}; auto typeVars = helper.typeVars(functionType); if (typeVars.empty()) m_errorReporter.typeError(1723_error, _typeClassDefinition.location(), "Function " + functionName + " does not depend on class variable."); if (typeVars.size() > 2) m_errorReporter.typeError(6387_error, _typeClassDefinition.location(), "Function " + functionName + " depends on multiple type variables."); if (!m_env->typeEquals(typeVars.front(), typeVar)) m_errorReporter.typeError(1807_error, _typeClassDefinition.location(), "Function " + functionName + " depends on invalid type variable."); } for (auto instantiation: m_analysis.annotation<TypeRegistration>(_typeClassDefinition).instantiations | ranges::views::values) // TODO: recursion-safety? Order of instantiation? instantiation->accept(*this); return false; } bool TypeInference::visit(InlineAssembly const& _inlineAssembly) { // External references have already been resolved in a prior stage and stored in the annotation. // We run the resolve step again regardless. yul::ExternalIdentifierAccess::Resolver identifierAccess = [&]( yul::Identifier const& _identifier, yul::IdentifierContext _context, bool ) -> bool { if (_context == yul::IdentifierContext::NonExternal) { // TODO: do we need this? // Hack until we can disallow any shadowing: If we found an internal reference, // clear the external references, so that codegen does not use it. _inlineAssembly.annotation().externalReferences.erase(& _identifier); return false; } InlineAssemblyAnnotation::ExternalIdentifierInfo* identifierInfo = util::valueOrNullptr(_inlineAssembly.annotation().externalReferences, &_identifier); if (!identifierInfo) return false; Declaration const* declaration = identifierInfo->declaration; solAssert(!!declaration, ""); solAssert(identifierInfo->suffix == "", ""); unify(type(*declaration), m_wordType, originLocationOf(_identifier)); identifierInfo->valueSize = 1; return true; }; solAssert(!_inlineAssembly.annotation().analysisInfo, ""); _inlineAssembly.annotation().analysisInfo = std::make_shared<yul::AsmAnalysisInfo>(); yul::AsmAnalyzer analyzer( *_inlineAssembly.annotation().analysisInfo, m_errorReporter, _inlineAssembly.dialect(), identifierAccess ); if (!analyzer.analyze(_inlineAssembly.operations().root())) solAssert(m_errorReporter.hasErrors()); return false; } bool TypeInference::visit(BinaryOperation const& _binaryOperation) { auto& operationAnnotation = annotation(_binaryOperation); solAssert(!operationAnnotation.type); TypeSystemHelpers helper{m_typeSystem}; switch (m_expressionContext) { case ExpressionContext::Term: if (auto* operatorInfo = util::valueOrNullptr(annotation().operators, _binaryOperation.getOperator())) { auto [typeClass, functionName] = *operatorInfo; // TODO: error robustness? Type functionType = m_env->fresh(annotation().typeClassFunctions.at(typeClass).at(functionName)); _binaryOperation.leftExpression().accept(*this); _binaryOperation.rightExpression().accept(*this); Type argTuple = helper.tupleType({type(_binaryOperation.leftExpression()), type(_binaryOperation.rightExpression())}); Type resultType = m_typeSystem.freshTypeVariable({}); Type genericFunctionType = helper.functionType(argTuple, resultType); unify(functionType, genericFunctionType, _binaryOperation.location()); operationAnnotation.type = resultType; } else if (_binaryOperation.getOperator() == Token::Colon) { _binaryOperation.leftExpression().accept(*this); { ScopedSaveAndRestore expressionContext{m_expressionContext, ExpressionContext::Type}; _binaryOperation.rightExpression().accept(*this); } Type leftType = type(_binaryOperation.leftExpression()); unify(leftType, type(_binaryOperation.rightExpression()), _binaryOperation.location()); operationAnnotation.type = leftType; } else { m_errorReporter.typeError(4504_error, _binaryOperation.location(), "Binary operation in term context not yet supported."); operationAnnotation.type = m_typeSystem.freshTypeVariable({}); } return false; case ExpressionContext::Type: if (_binaryOperation.getOperator() == Token::Colon) { _binaryOperation.leftExpression().accept(*this); { ScopedSaveAndRestore expressionContext{m_expressionContext, ExpressionContext::Sort}; _binaryOperation.rightExpression().accept(*this); } Type leftType = type(_binaryOperation.leftExpression()); unify(leftType, type(_binaryOperation.rightExpression()), _binaryOperation.location()); operationAnnotation.type = leftType; } else if (_binaryOperation.getOperator() == Token::RightArrow) { _binaryOperation.leftExpression().accept(*this); _binaryOperation.rightExpression().accept(*this); operationAnnotation.type = helper.functionType(type(_binaryOperation.leftExpression()), type(_binaryOperation.rightExpression())); } else if (_binaryOperation.getOperator() == Token::BitOr) { _binaryOperation.leftExpression().accept(*this); _binaryOperation.rightExpression().accept(*this); operationAnnotation.type = helper.sumType({type(_binaryOperation.leftExpression()), type(_binaryOperation.rightExpression())}); } else { m_errorReporter.typeError(1439_error, _binaryOperation.location(), "Invalid binary operations in type context."); operationAnnotation.type = m_typeSystem.freshTypeVariable({}); } return false; case ExpressionContext::Sort: m_errorReporter.typeError(1017_error, _binaryOperation.location(), "Invalid binary operation in sort context."); operationAnnotation.type = m_typeSystem.freshTypeVariable({}); return false; } return false; } void TypeInference::endVisit(VariableDeclarationStatement const& _variableDeclarationStatement) { solAssert(m_expressionContext == ExpressionContext::Term); if (_variableDeclarationStatement.declarations().size () != 1) { m_errorReporter.typeError(2655_error, _variableDeclarationStatement.location(), "Multi variable declaration not supported."); return; } Type variableType = type(*_variableDeclarationStatement.declarations().front()); if (_variableDeclarationStatement.initialValue()) unify(variableType, type(*_variableDeclarationStatement.initialValue()), _variableDeclarationStatement.location()); } bool TypeInference::visit(VariableDeclaration const& _variableDeclaration) { solAssert(!_variableDeclaration.value()); auto& variableAnnotation = annotation(_variableDeclaration); solAssert(!variableAnnotation.type); switch (m_expressionContext) { case ExpressionContext::Term: if (_variableDeclaration.typeExpression()) { ScopedSaveAndRestore expressionContext{m_expressionContext, ExpressionContext::Type}; _variableDeclaration.typeExpression()->accept(*this); variableAnnotation.type = type(*_variableDeclaration.typeExpression()); return false; } variableAnnotation.type = m_typeSystem.freshTypeVariable({}); return false; case ExpressionContext::Type: variableAnnotation.type = m_typeSystem.freshTypeVariable({}); if (_variableDeclaration.typeExpression()) { ScopedSaveAndRestore expressionContext{m_expressionContext, ExpressionContext::Sort}; _variableDeclaration.typeExpression()->accept(*this); unify(*variableAnnotation.type, type(*_variableDeclaration.typeExpression()), _variableDeclaration.typeExpression()->location()); } return false; case ExpressionContext::Sort: m_errorReporter.typeError(2399_error, _variableDeclaration.location(), "Variable declaration in sort context."); variableAnnotation.type = m_typeSystem.freshTypeVariable({}); return false; } util::unreachable(); } void TypeInference::endVisit(IfStatement const& _ifStatement) { auto& ifAnnotation = annotation(_ifStatement); solAssert(!ifAnnotation.type); if (m_expressionContext != ExpressionContext::Term) { m_errorReporter.typeError(2015_error, _ifStatement.location(), "If statement outside term context."); ifAnnotation.type = m_typeSystem.freshTypeVariable({}); return; } unify(type(_ifStatement.condition()), m_boolType, _ifStatement.condition().location()); ifAnnotation.type = m_unitType; } void TypeInference::endVisit(Assignment const& _assignment) { auto& assignmentAnnotation = annotation(_assignment); solAssert(!assignmentAnnotation.type); if (m_expressionContext != ExpressionContext::Term) { m_errorReporter.typeError(4337_error, _assignment.location(), "Assignment outside term context."); assignmentAnnotation.type = m_typeSystem.freshTypeVariable({}); return; } Type leftType = type(_assignment.leftHandSide()); unify(leftType, type(_assignment.rightHandSide()), _assignment.location()); assignmentAnnotation.type = leftType; } experimental::Type TypeInference::handleIdentifierByReferencedDeclaration(langutil::SourceLocation _location, Declaration const& _declaration) { switch (m_expressionContext) { case ExpressionContext::Term: { if ( !dynamic_cast<FunctionDefinition const*>(&_declaration) && !dynamic_cast<VariableDeclaration const*>(&_declaration) && !dynamic_cast<TypeClassDefinition const*>(&_declaration) && !dynamic_cast<TypeDefinition const*>(&_declaration) ) { SecondarySourceLocation ssl; ssl.append("Referenced node.", _declaration.location()); m_errorReporter.fatalTypeError(3101_error, _location, ssl, "Attempt to type identifier referring to unexpected node."); } auto& declarationAnnotation = annotation(_declaration); if (!declarationAnnotation.type) _declaration.accept(*this); solAssert(declarationAnnotation.type); if (dynamic_cast<VariableDeclaration const*>(&_declaration)) return *declarationAnnotation.type; else if (dynamic_cast<FunctionDefinition const*>(&_declaration)) return polymorphicInstance(*declarationAnnotation.type); else if (dynamic_cast<TypeClassDefinition const*>(&_declaration)) { solAssert(TypeEnvironmentHelpers{*m_env}.typeVars(*declarationAnnotation.type).empty()); return *declarationAnnotation.type; } else if (dynamic_cast<TypeDefinition const*>(&_declaration)) { // TODO: can we avoid this? Type type = *declarationAnnotation.type; if (TypeSystemHelpers{m_typeSystem}.isTypeFunctionType(type)) type = std::get<1>(TypeSystemHelpers{m_typeSystem}.destTypeFunctionType(type)); return polymorphicInstance(type); } else solAssert(false); break; } case ExpressionContext::Type: { if ( !dynamic_cast<VariableDeclaration const*>(&_declaration) && !dynamic_cast<TypeDefinition const*>(&_declaration) ) { SecondarySourceLocation ssl; ssl.append("Referenced node.", _declaration.location()); m_errorReporter.fatalTypeError(2217_error, _location, ssl, "Attempt to type identifier referring to unexpected node."); } // TODO: Assert that this is a type class variable declaration? auto& declarationAnnotation = annotation(_declaration); if (!declarationAnnotation.type) _declaration.accept(*this); solAssert(declarationAnnotation.type); if (dynamic_cast<VariableDeclaration const*>(&_declaration)) return *declarationAnnotation.type; else if (dynamic_cast<TypeDefinition const*>(&_declaration)) return polymorphicInstance(*declarationAnnotation.type); else solAssert(false); break; } case ExpressionContext::Sort: { if (auto const* typeClassDefinition = dynamic_cast<TypeClassDefinition const*>(&_declaration)) { ScopedSaveAndRestore expressionContext{m_expressionContext, ExpressionContext::Term}; typeClassDefinition->accept(*this); solAssert(m_analysis.annotation<TypeClassRegistration>(*typeClassDefinition).typeClass.has_value()); TypeClass typeClass = m_analysis.annotation<TypeClassRegistration>(*typeClassDefinition).typeClass.value(); return m_typeSystem.freshTypeVariable(Sort{{typeClass}}); } else { m_errorReporter.typeError(2599_error, _location, "Expected type class."); return m_typeSystem.freshTypeVariable({}); } break; } } util::unreachable(); } bool TypeInference::visit(Identifier const& _identifier) { auto& identifierAnnotation = annotation(_identifier); solAssert(!identifierAnnotation.type); if (auto const* referencedDeclaration = _identifier.annotation().referencedDeclaration) { identifierAnnotation.type = handleIdentifierByReferencedDeclaration(_identifier.location(), *referencedDeclaration); return false; } switch (m_expressionContext) { case ExpressionContext::Term: // TODO: error handling solAssert(false); break; case ExpressionContext::Type: m_errorReporter.typeError(5934_error, _identifier.location(), "Undeclared type variable."); // Assign it a fresh variable anyway just so that we can continue analysis. identifierAnnotation.type = m_typeSystem.freshTypeVariable({}); break; case ExpressionContext::Sort: // TODO: error handling solAssert(false); break; } return false; } void TypeInference::endVisit(TupleExpression const& _tupleExpression) { auto& expressionAnnotation = annotation(_tupleExpression); solAssert(!expressionAnnotation.type); TypeSystemHelpers helper{m_typeSystem}; auto componentTypes = _tupleExpression.components() | ranges::views::transform([&](auto _expr) -> Type { auto& componentAnnotation = annotation(*_expr); solAssert(componentAnnotation.type); return *componentAnnotation.type; }) | ranges::to<std::vector<Type>>; switch (m_expressionContext) { case ExpressionContext::Term: case ExpressionContext::Type: expressionAnnotation.type = helper.tupleType(componentTypes); break; case ExpressionContext::Sort: { Type type = m_typeSystem.freshTypeVariable({}); for (auto componentType: componentTypes) unify(type, componentType, _tupleExpression.location()); expressionAnnotation.type = type; break; } } } bool TypeInference::visit(IdentifierPath const& _identifierPath) { auto& identifierAnnotation = annotation(_identifierPath); solAssert(!identifierAnnotation.type); if (auto const* referencedDeclaration = _identifierPath.annotation().referencedDeclaration) { identifierAnnotation.type = handleIdentifierByReferencedDeclaration(_identifierPath.location(), *referencedDeclaration); return false; } // TODO: error handling solAssert(false); } bool TypeInference::visit(TypeClassInstantiation const& _typeClassInstantiation) { ScopedSaveAndRestore activeInstantiations{m_activeInstantiations, m_activeInstantiations + std::set<TypeClassInstantiation const*>{&_typeClassInstantiation}}; // Note: recursion is resolved due to special handling during unification. auto& instantiationAnnotation = annotation(_typeClassInstantiation); if (instantiationAnnotation.type) return false; instantiationAnnotation.type = m_voidType; TypeClass typeClass = std::visit(util::GenericVisitor{ [&](ASTPointer<IdentifierPath> _typeClassName) -> TypeClass { auto const* typeClassDefinition = dynamic_cast<TypeClassDefinition const*>(_typeClassName->annotation().referencedDeclaration); solAssert(typeClassDefinition); // visiting the type class will re-visit this instantiation typeClassDefinition->accept(*this); // TODO: more error handling? Should be covered by the visit above. solAssert(m_analysis.annotation<TypeClassRegistration>(*typeClassDefinition).typeClass.has_value()); return m_analysis.annotation<TypeClassRegistration>(*typeClassDefinition).typeClass.value(); }, [&](Token _token) -> TypeClass { std::optional<BuiltinClass> builtinClass = builtinClassFromToken(_token); solAssert(builtinClass.has_value()); solAssert(annotation().builtinClasses.count(*builtinClass) != 0); return annotation().builtinClasses.at(*builtinClass); } }, _typeClassInstantiation.typeClass().name()); // TODO: _typeClassInstantiation.typeConstructor().accept(*this); ? auto typeConstructor = m_analysis.annotation<TypeRegistration>(_typeClassInstantiation.typeConstructor()).typeConstructor; solAssert(typeConstructor); std::vector<Type> arguments; Arity arity{ {}, typeClass }; { ScopedSaveAndRestore expressionContext{m_expressionContext, ExpressionContext::Type}; if (_typeClassInstantiation.argumentSorts()) { _typeClassInstantiation.argumentSorts()->accept(*this); auto& argumentSortAnnotation = annotation(*_typeClassInstantiation.argumentSorts()); solAssert(argumentSortAnnotation.type); arguments = TypeSystemHelpers{m_typeSystem}.destTupleType(*argumentSortAnnotation.type); arity.argumentSorts = arguments | ranges::views::transform([&](Type _type) { return m_env->sort(_type); }) | ranges::to<std::vector<Sort>>; } } m_env->fixTypeVars(arguments); Type instanceType{TypeConstant{*typeConstructor, arguments}}; std::map<std::string, Type> functionTypes; for (auto subNode: _typeClassInstantiation.subNodes()) { auto const* functionDefinition = dynamic_cast<FunctionDefinition const*>(subNode.get()); solAssert(functionDefinition); subNode->accept(*this); if (!functionTypes.emplace(functionDefinition->name(), type(*functionDefinition)).second) m_errorReporter.typeError(3654_error, subNode->location(), "Duplicate definition of function " + functionDefinition->name() + " during type class instantiation."); } if (auto error = m_typeSystem.instantiateClass(instanceType, arity)) m_errorReporter.typeError(5094_error, _typeClassInstantiation.location(), *error); auto const& classFunctions = annotation().typeClassFunctions.at(typeClass); solAssert(std::holds_alternative<TypeVariable>(m_typeSystem.typeClassVariable(typeClass))); TypeVariable classVar = std::get<TypeVariable>(m_typeSystem.typeClassVariable(typeClass)); for (auto [name, classFunctionType]: classFunctions) { if (!functionTypes.count(name)) { m_errorReporter.typeError(6948_error, _typeClassInstantiation.location(), "Missing function: " + name); continue; } Type instantiatedClassFunctionType = TypeEnvironmentHelpers{*m_env}.substitute(classFunctionType, classVar, instanceType); Type instanceFunctionType = functionTypes.at(name); functionTypes.erase(name); if (!m_env->typeEquals(instanceFunctionType, instantiatedClassFunctionType)) m_errorReporter.typeError( 7428_error, _typeClassInstantiation.location(), fmt::format( "Instantiation function '{}' does not match the declaration in the type class ({} != {}).", name, TypeEnvironmentHelpers{*m_env}.typeToString(instanceFunctionType), TypeEnvironmentHelpers{*m_env}.typeToString(instantiatedClassFunctionType) ) ); } if (!functionTypes.empty()) m_errorReporter.typeError(4873_error, _typeClassInstantiation.location(), "Additional functions in class instantiation."); return false; } bool TypeInference::visit(MemberAccess const& _memberAccess) { if (m_expressionContext != ExpressionContext::Term) { m_errorReporter.typeError(5195_error, _memberAccess.location(), "Member access outside term context."); annotation(_memberAccess).type = m_typeSystem.freshTypeVariable({}); return false; } return true; } experimental::Type TypeInference::memberType(Type _type, std::string _memberName, langutil::SourceLocation _location) { Type resolvedType = m_env->resolve(_type); TypeSystemHelpers helper{m_typeSystem}; if (helper.isTypeConstant(resolvedType)) { auto constructor = std::get<0>(helper.destTypeConstant(resolvedType)); if (auto* typeMember = util::valueOrNullptr(annotation().members.at(constructor), _memberName)) return polymorphicInstance(typeMember->type); else { m_errorReporter.typeError(5755_error, _location, fmt::format("Member {} not found in type {}.", _memberName, TypeEnvironmentHelpers{*m_env}.typeToString(_type))); return m_typeSystem.freshTypeVariable({}); } } else { m_errorReporter.typeError(5104_error, _location, "Unsupported member access expression."); return m_typeSystem.freshTypeVariable({}); } } void TypeInference::endVisit(MemberAccess const& _memberAccess) { auto& memberAccessAnnotation = annotation(_memberAccess); solAssert(!memberAccessAnnotation.type); Type expressionType = type(_memberAccess.expression()); memberAccessAnnotation.type = memberType(expressionType, _memberAccess.memberName(), _memberAccess.location()); } bool TypeInference::visit(TypeDefinition const& _typeDefinition) { bool isBuiltIn = dynamic_cast<Builtin const*>(_typeDefinition.typeExpression()); TypeSystemHelpers helper{m_typeSystem}; auto& typeDefinitionAnnotation = annotation(_typeDefinition); if (typeDefinitionAnnotation.type) return false; if (_typeDefinition.arguments()) { ScopedSaveAndRestore expressionContext{m_expressionContext, ExpressionContext::Type}; _typeDefinition.arguments()->accept(*this); } std::vector<Type> arguments; if (_typeDefinition.arguments()) for (ASTPointer<VariableDeclaration> argumentDeclaration: _typeDefinition.arguments()->parameters()) { solAssert(argumentDeclaration); Type typeVar = type(*argumentDeclaration); solAssert(std::holds_alternative<TypeVariable>(typeVar)); arguments.emplace_back(typeVar); } m_env->fixTypeVars(arguments); Type definedType = type(&_typeDefinition, arguments); if (arguments.empty()) typeDefinitionAnnotation.type = definedType; else typeDefinitionAnnotation.type = helper.typeFunctionType(helper.tupleType(arguments), definedType); std::optional<Type> underlyingType; if (isBuiltIn) // TODO: This special case should eventually become user-definable. underlyingType = m_wordType; else if (_typeDefinition.typeExpression()) { ScopedSaveAndRestore expressionContext{m_expressionContext, ExpressionContext::Type}; _typeDefinition.typeExpression()->accept(*this); underlyingType = annotation(*_typeDefinition.typeExpression()).type; } TypeConstructor constructor = typeConstructor(&_typeDefinition); auto [members, newlyInserted] = annotation().members.emplace(constructor, std::map<std::string, TypeMember>{}); solAssert(newlyInserted, fmt::format("Members of type '{}' are already defined.", m_typeSystem.constructorInfo(constructor).name)); if (underlyingType) { // Undeclared type variables are not allowed in type definitions and we fixed all the declared ones. solAssert(!TypeEnvironmentHelpers{*m_env}.hasGenericTypeVars(*underlyingType)); members->second.emplace("abs", TypeMember{helper.functionType(*underlyingType, definedType)}); members->second.emplace("rep", TypeMember{helper.functionType(definedType, *underlyingType)}); } if (helper.isPrimitiveType(definedType, PrimitiveType::Pair)) { solAssert(isBuiltIn); solAssert(arguments.size() == 2); members->second.emplace("first", TypeMember{helper.functionType(definedType, arguments[0])}); members->second.emplace("second", TypeMember{helper.functionType(definedType, arguments[1])}); } return false; } bool TypeInference::visit(FunctionCall const&) { return true; } void TypeInference::endVisit(FunctionCall const& _functionCall) { auto& functionCallAnnotation = annotation(_functionCall); solAssert(!functionCallAnnotation.type); Type functionType = type(_functionCall.expression()); TypeSystemHelpers helper{m_typeSystem}; std::vector<Type> argTypes; for (auto arg: _functionCall.arguments()) { switch (m_expressionContext) { case ExpressionContext::Term: case ExpressionContext::Type: argTypes.emplace_back(type(*arg)); break; case ExpressionContext::Sort: m_errorReporter.typeError(9173_error, _functionCall.location(), "Function call in sort context."); functionCallAnnotation.type = m_typeSystem.freshTypeVariable({}); break; } } switch (m_expressionContext) { case ExpressionContext::Term: { Type argTuple = helper.tupleType(argTypes); Type resultType = m_typeSystem.freshTypeVariable({}); Type genericFunctionType = helper.functionType(argTuple, resultType); unify(functionType, genericFunctionType, _functionCall.location()); functionCallAnnotation.type = resultType; break; } case ExpressionContext::Type: { Type argTuple = helper.tupleType(argTypes); Type resultType = m_typeSystem.freshTypeVariable({}); Type genericFunctionType = helper.typeFunctionType(argTuple, resultType); unify(functionType, genericFunctionType, _functionCall.location()); functionCallAnnotation.type = resultType; break; } case ExpressionContext::Sort: solAssert(false); } } // TODO: clean up rational parsing namespace { std::optional<rational> parseRational(std::string const& _value) { rational value; try { auto radixPoint = find(_value.begin(), _value.end(), '.'); if (radixPoint != _value.end()) { if ( !all_of(radixPoint + 1, _value.end(), util::isDigit) || !all_of(_value.begin(), radixPoint, util::isDigit) ) return std::nullopt; // Only decimal notation allowed here, leading zeros would switch to octal. auto fractionalBegin = find_if_not( radixPoint + 1, _value.end(), [](char const& a) { return a == '0'; } ); rational numerator; rational denominator(1); denominator = bigint(std::string(fractionalBegin, _value.end())); denominator /= boost::multiprecision::pow( bigint(10), static_cast<unsigned>(distance(radixPoint + 1, _value.end())) ); numerator = bigint(std::string(_value.begin(), radixPoint)); value = numerator + denominator; } else value = bigint(_value); return value; } catch (...) { return std::nullopt; } } /// Checks whether _mantissa * (10 ** _expBase10) fits into 4096 bits. bool fitsPrecisionBase10(bigint const& _mantissa, uint32_t _expBase10) { double const log2Of10AwayFromZero = 3.3219280948873624; return fitsPrecisionBaseX(_mantissa, log2Of10AwayFromZero, _expBase10); } std::optional<rational> rationalValue(Literal const& _literal) { rational value; try { ASTString valueString = _literal.valueWithoutUnderscores(); auto expPoint = find(valueString.begin(), valueString.end(), 'e'); if (expPoint == valueString.end()) expPoint = find(valueString.begin(), valueString.end(), 'E'); if (boost::starts_with(valueString, "0x")) { // process as hex value = bigint(valueString); } else if (expPoint != valueString.end()) { // Parse mantissa and exponent. Checks numeric limit. std::optional<rational> mantissa = parseRational(std::string(valueString.begin(), expPoint)); if (!mantissa) return std::nullopt; value = *mantissa; // 0E... is always zero. if (value == 0) return std::nullopt; bigint exp = bigint(std::string(expPoint + 1, valueString.end())); if (exp > std::numeric_limits<int32_t>::max() || exp < std::numeric_limits<int32_t>::min()) return std::nullopt; uint32_t expAbs = bigint(abs(exp)).convert_to<uint32_t>(); if (exp < 0) { if (!fitsPrecisionBase10(abs(value.denominator()), expAbs)) return std::nullopt; value /= boost::multiprecision::pow( bigint(10), expAbs ); } else if (exp > 0) { if (!fitsPrecisionBase10(abs(value.numerator()), expAbs)) return std::nullopt; value *= boost::multiprecision::pow( bigint(10), expAbs ); } } else { // parse as rational number std::optional<rational> tmp = parseRational(valueString); if (!tmp) return std::nullopt; value = *tmp; } } catch (...) { return std::nullopt; } switch (_literal.subDenomination()) { case Literal::SubDenomination::None: case Literal::SubDenomination::Wei: case Literal::SubDenomination::Second: break; case Literal::SubDenomination::Gwei: value *= bigint("1000000000"); break; case Literal::SubDenomination::Ether: value *= bigint("1000000000000000000"); break; case Literal::SubDenomination::Minute: value *= bigint("60"); break; case Literal::SubDenomination::Hour: value *= bigint("3600"); break; case Literal::SubDenomination::Day: value *= bigint("86400"); break; case Literal::SubDenomination::Week: value *= bigint("604800"); break; case Literal::SubDenomination::Year: value *= bigint("31536000"); break; } return value; } } bool TypeInference::visit(Literal const& _literal) { auto& literalAnnotation = annotation(_literal); if (_literal.token() != Token::Number) { m_errorReporter.typeError(4316_error, _literal.location(), "Only number literals are supported."); return false; } std::optional<rational> value = rationalValue(_literal); if (!value) { m_errorReporter.typeError(6739_error, _literal.location(), "Invalid number literals."); return false; } if (value->denominator() != 1) { m_errorReporter.typeError(2345_error, _literal.location(), "Only integers are supported."); return false; } literalAnnotation.type = m_typeSystem.freshTypeVariable(Sort{{annotation().builtinClasses.at(BuiltinClass::Integer)}}); return false; } namespace { // TODO: put at a nice place to deduplicate. TypeRegistration::TypeClassInstantiations const& typeClassInstantiations(Analysis const& _analysis, TypeClass _class) { auto const* typeClassDeclaration = _analysis.typeSystem().typeClassDeclaration(_class); if (typeClassDeclaration) return _analysis.annotation<TypeRegistration>(*typeClassDeclaration).instantiations; // TODO: better mechanism than fetching by name. auto const& annotation = _analysis.annotation<TypeRegistration>(); auto const& inferenceAnnotation = _analysis.annotation<TypeInference>(); return annotation.builtinClassInstantiations.at( inferenceAnnotation.builtinClassesByName.at( _analysis.typeSystem().typeClassName(_class) ) ); } } experimental::Type TypeInference::polymorphicInstance(Type const& _scheme) { return m_env->fresh(_scheme); } void TypeInference::unify(Type _a, Type _b, langutil::SourceLocation _location) { TypeSystemHelpers helper{m_typeSystem}; auto unificationFailures = m_env->unify(_a, _b); if (!m_activeInstantiations.empty()) { // TODO: This entire logic is superfluous - I thought mutually recursive dependencies between // class instantiations are a problem, but in fact they're not, they just resolve to mutually recursive // functions that are fine. So instead, all instantiations can be registered with the type system directly // when visiting the type class (assuming that they all work out) - and then all instantiations can be checked // individually, which should still catch all actual issues (while allowing recursions). // Original comment: Attempt to resolve interdependencies between type class instantiations. std::vector<TypeClassInstantiation const*> missingInstantiations; bool recursion = false; bool onlyMissingInstantiations = [&]() { for (auto failure: unificationFailures) { if (auto* sortMismatch = std::get_if<TypeEnvironment::SortMismatch>(&failure)) if (helper.isTypeConstant(sortMismatch->type)) { TypeConstructor constructor = std::get<0>(helper.destTypeConstant(sortMismatch->type)); for (auto typeClass: sortMismatch->sort.classes) { if (auto const* instantiation = util::valueOrDefault(typeClassInstantiations(m_analysis, typeClass), constructor, nullptr)) { if (m_activeInstantiations.count(instantiation)) { langutil::SecondarySourceLocation ssl; for (auto activeInstantiation: m_activeInstantiations) ssl.append("Involved instantiation", activeInstantiation->location()); m_errorReporter.typeError( 3573_error, _location, ssl, "Recursion during type class instantiation." ); recursion = true; return false; } missingInstantiations.emplace_back(instantiation); } else return false; } continue; } return false; } return true; }(); if (recursion) return; if (onlyMissingInstantiations) { for (auto instantiation: missingInstantiations) instantiation->accept(*this); unificationFailures = m_env->unify(_a, _b); } } for (auto failure: unificationFailures) { TypeEnvironmentHelpers envHelper{*m_env}; std::visit(util::GenericVisitor{ [&](TypeEnvironment::TypeMismatch _typeMismatch) { m_errorReporter.typeError( 8456_error, _location, fmt::format( "Cannot unify {} and {}.", envHelper.typeToString(_typeMismatch.a), envHelper.typeToString(_typeMismatch.b) ) ); }, [&](TypeEnvironment::SortMismatch _sortMismatch) { m_errorReporter.typeError(3111_error, _location, fmt::format( "{} does not have sort {}", envHelper.typeToString(_sortMismatch.type), TypeSystemHelpers{m_typeSystem}.sortToString(_sortMismatch.sort) )); }, [&](TypeEnvironment::RecursiveUnification _recursiveUnification) { m_errorReporter.typeError( 6460_error, _location, fmt::format( "Recursive unification: {} occurs in {}.", envHelper.typeToString(_recursiveUnification.var), envHelper.typeToString(_recursiveUnification.type) ) ); } }, failure); } } experimental::Type TypeInference::type(ASTNode const& _node) const { auto result = annotation(_node).type; solAssert(result); return *result; } TypeConstructor TypeInference::typeConstructor(Declaration const* _type) const { if (auto const& constructor = m_analysis.annotation<TypeRegistration>(*_type).typeConstructor) return *constructor; m_errorReporter.fatalTypeError(5904_error, _type->location(), "Unregistered type."); util::unreachable(); } experimental::Type TypeInference::type(Declaration const* _type, std::vector<Type> _arguments) const { return m_typeSystem.type(typeConstructor(_type), std::move(_arguments)); } bool TypeInference::visitNode(ASTNode const& _node) { m_errorReporter.fatalTypeError(5348_error, _node.location(), "Unsupported AST node during type inference."); return false; } TypeInference::Annotation& TypeInference::annotation(ASTNode const& _node) { return m_analysis.annotation<TypeInference>(_node); } TypeInference::Annotation const& TypeInference::annotation(ASTNode const& _node) const { return m_analysis.annotation<TypeInference>(_node); } TypeInference::GlobalAnnotation& TypeInference::annotation() { return m_analysis.annotation<TypeInference>(); }
44,009
C++
.cpp
1,095
37.180822
166
0.769209
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,224
SyntaxRestrictor.cpp
ethereum_solidity/libsolidity/experimental/analysis/SyntaxRestrictor.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libsolidity/experimental/analysis/SyntaxRestrictor.h> #include <libsolidity/experimental/analysis/Analysis.h> #include <liblangutil/Exceptions.h> using namespace solidity::frontend; using namespace solidity::frontend::experimental; using namespace solidity::langutil; SyntaxRestrictor::SyntaxRestrictor(Analysis& _analysis): m_errorReporter(_analysis.errorReporter()) {} bool SyntaxRestrictor::analyze(ASTNode const& _astRoot) { _astRoot.accept(*this); return !Error::containsErrors(m_errorReporter.errors()); } bool SyntaxRestrictor::visitNode(ASTNode const& _node) { if (!_node.experimentalSolidityOnly()) m_errorReporter.syntaxError(9282_error, _node.location(), "Unsupported AST node."); return false; } bool SyntaxRestrictor::visit(ContractDefinition const& _contractDefinition) { if (_contractDefinition.contractKind() != ContractKind::Contract) m_errorReporter.syntaxError(9159_error, _contractDefinition.location(), "Only contracts are supported."); if (!_contractDefinition.baseContracts().empty()) m_errorReporter.syntaxError(5731_error, _contractDefinition.location(), "Inheritance unsupported."); return true; } bool SyntaxRestrictor::visit(FunctionDefinition const& _functionDefinition) { if (!_functionDefinition.isImplemented()) m_errorReporter.syntaxError(1741_error, _functionDefinition.location(), "Functions must be implemented."); if (!_functionDefinition.modifiers().empty()) m_errorReporter.syntaxError(9988_error, _functionDefinition.location(), "Function may not have modifiers."); if (_functionDefinition.overrides()) m_errorReporter.syntaxError(5044_error, _functionDefinition.location(), "Function may not have override specifiers."); solAssert(!_functionDefinition.returnParameterList()); if (_functionDefinition.isFree()) { if (_functionDefinition.stateMutability() != StateMutability::NonPayable) m_errorReporter.syntaxError(5714_error, _functionDefinition.location(), "Free functions may not have a mutability."); } else { if (_functionDefinition.isFallback()) { if (_functionDefinition.visibility() != Visibility::External) m_errorReporter.syntaxError(7341_error, _functionDefinition.location(), "Fallback function must be external."); } else m_errorReporter.syntaxError(4496_error, _functionDefinition.location(), "Only fallback functions are supported in contracts."); } return true; } bool SyntaxRestrictor::visit(VariableDeclarationStatement const& _variableDeclarationStatement) { if (_variableDeclarationStatement.declarations().size() == 1) { if (!_variableDeclarationStatement.declarations().front()) m_errorReporter.syntaxError(9658_error, _variableDeclarationStatement.initialValue()->location(), "Variable declaration has to declare a single variable."); } else m_errorReporter.syntaxError(3520_error, _variableDeclarationStatement.initialValue()->location(), "Variable declarations can only declare a single variable."); return true; } bool SyntaxRestrictor::visit(VariableDeclaration const& _variableDeclaration) { if (_variableDeclaration.value()) m_errorReporter.syntaxError(1801_error, _variableDeclaration.value()->location(), "Variable declarations with initial value not supported."); if (_variableDeclaration.isStateVariable()) m_errorReporter.syntaxError(6388_error, _variableDeclaration.location(), "State variables are not supported."); if (!_variableDeclaration.isLocalVariable()) m_errorReporter.syntaxError(8953_error, _variableDeclaration.location(), "Only local variables are supported."); if (_variableDeclaration.mutability() != VariableDeclaration::Mutability::Mutable) m_errorReporter.syntaxError(2934_error, _variableDeclaration.location(), "Only mutable variables are supported."); if (_variableDeclaration.isIndexed()) m_errorReporter.syntaxError(9603_error, _variableDeclaration.location(), "Indexed variables are not supported."); if (!_variableDeclaration.noVisibilitySpecified()) m_errorReporter.syntaxError(8809_error, _variableDeclaration.location(), "Variables with visibility not supported."); if (_variableDeclaration.overrides()) m_errorReporter.syntaxError(6175_error, _variableDeclaration.location(), "Variables with override specifier not supported."); if (_variableDeclaration.referenceLocation() != VariableDeclaration::Location::Unspecified) m_errorReporter.syntaxError(5360_error, _variableDeclaration.location(), "Variables with reference location not supported."); return true; }
5,163
C++
.cpp
98
50.5
161
0.799406
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,225
TypeClassRegistration.cpp
ethereum_solidity/libsolidity/experimental/analysis/TypeClassRegistration.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libsolidity/experimental/analysis/TypeClassRegistration.h> #include <libsolidity/experimental/analysis/Analysis.h> #include <liblangutil/ErrorReporter.h> #include <liblangutil/Exceptions.h> using namespace solidity::frontend::experimental; using namespace solidity::langutil; TypeClassRegistration::TypeClassRegistration(Analysis& _analysis): m_analysis(_analysis), m_errorReporter(_analysis.errorReporter()), m_typeSystem(_analysis.typeSystem()) { } bool TypeClassRegistration::analyze(SourceUnit const& _sourceUnit) { _sourceUnit.accept(*this); return !m_errorReporter.hasErrors(); } bool TypeClassRegistration::visit(TypeClassDefinition const& _typeClassDefinition) { std::variant<TypeClass, std::string> typeClassOrError = m_typeSystem.declareTypeClass( _typeClassDefinition.name(), &_typeClassDefinition ); m_analysis.annotation<TypeClassRegistration>(_typeClassDefinition).typeClass = std::visit( util::GenericVisitor{ [](TypeClass _class) -> TypeClass { return _class; }, [&](std::string _error) -> TypeClass { m_errorReporter.fatalTypeError(4767_error, _typeClassDefinition.location(), _error); util::unreachable(); } }, typeClassOrError ); return true; }
1,906
C++
.cpp
49
36.653061
91
0.791215
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,226
DebugWarner.cpp
ethereum_solidity/libsolidity/experimental/analysis/DebugWarner.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libsolidity/experimental/analysis/DebugWarner.h> #include <libsolidity/experimental/analysis/Analysis.h> #include <libsolidity/experimental/analysis/TypeInference.h> #include <libsolidity/experimental/ast/TypeSystemHelper.h> #include <liblangutil/Exceptions.h> using namespace solidity::frontend; using namespace solidity::frontend::experimental; using namespace solidity::langutil; DebugWarner::DebugWarner(Analysis& _analysis): m_analysis(_analysis), m_errorReporter(_analysis.errorReporter()) {} bool DebugWarner::analyze(ASTNode const& _astRoot) { _astRoot.accept(*this); return !Error::containsErrors(m_errorReporter.errors()); } bool DebugWarner::visitNode(ASTNode const& _node) { std::optional<Type> const& inferredType = m_analysis.annotation<TypeInference>(_node).type; if (inferredType.has_value()) m_errorReporter.info( 4164_error, _node.location(), "Inferred type: " + TypeEnvironmentHelpers{m_analysis.typeSystem().env()}.typeToString(*inferredType) ); return true; }
1,701
C++
.cpp
40
40.55
112
0.795276
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,227
Type.cpp
ethereum_solidity/libsolidity/experimental/ast/Type.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libsolidity/experimental/ast/Type.h> #include <libsolidity/ast/AST.h> #include <libsolutil/Visitor.h> #include <range/v3/view/drop_last.hpp> #include <range/v3/view/zip.hpp> #include <sstream> using namespace solidity; using namespace solidity::frontend::experimental; bool Sort::operator==(Sort const& _rhs) const { if (classes.size() != _rhs.classes.size()) return false; for (auto [lhs, rhs]: ranges::zip_view(classes, _rhs.classes)) if (lhs != rhs) return false; return true; } bool Sort::operator<=(Sort const& _rhs) const { for (auto c: classes) if (!_rhs.classes.count(c)) return false; return true; } Sort Sort::operator+(Sort const& _rhs) const { Sort result { classes }; result.classes += _rhs.classes; return result; } Sort Sort::operator-(Sort const& _rhs) const { Sort result { classes }; result.classes -= _rhs.classes; return result; }
1,578
C++
.cpp
50
29.64
69
0.755937
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,228
TypeSystem.cpp
ethereum_solidity/libsolidity/experimental/ast/TypeSystem.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libsolidity/experimental/ast/TypeSystem.h> #include <libsolidity/experimental/ast/TypeSystemHelper.h> #include <libsolidity/ast/AST.h> #include <liblangutil/Exceptions.h> #include <libsolutil/Visitor.h> #include <range/v3/to_container.hpp> #include <range/v3/view/drop_exactly.hpp> #include <range/v3/view/drop_last.hpp> #include <range/v3/view/reverse.hpp> #include <range/v3/view/zip.hpp> #include <fmt/format.h> #include <unordered_map> using namespace solidity; using namespace solidity::frontend; using namespace solidity::frontend::experimental; std::vector<TypeEnvironment::UnificationFailure> TypeEnvironment::unify(Type _a, Type _b) { std::vector<UnificationFailure> failures; auto unificationFailure = [&]() { failures.emplace_back(UnificationFailure{TypeMismatch{_a, _b}}); }; _a = resolve(_a); _b = resolve(_b); std::visit(util::GenericVisitor{ [&](TypeVariable _left, TypeVariable _right) { if (_left.index() == _right.index()) solAssert(_left.sort() == _right.sort()); else if (isFixedTypeVar(_left) && isFixedTypeVar(_right)) unificationFailure(); else if (isFixedTypeVar(_left)) failures += instantiate(_right, _left); else if (isFixedTypeVar(_right)) failures += instantiate(_left, _right); else if (_left.sort() <= _right.sort()) failures += instantiate(_left, _right); else if (_right.sort() <= _left.sort()) failures += instantiate(_right, _left); else { Type newVar = m_typeSystem.freshVariable(_left.sort() + _right.sort()); failures += instantiate(_left, newVar); failures += instantiate(_right, newVar); } }, [&](TypeVariable _var, auto) { failures += instantiate(_var, _b); }, [&](auto, TypeVariable _var) { failures += instantiate(_var, _a); }, [&](TypeConstant _left, TypeConstant _right) { if (_left.constructor != _right.constructor) return unificationFailure(); if (_left.arguments.size() != _right.arguments.size()) return unificationFailure(); for (auto&& [left, right]: ranges::zip_view(_left.arguments, _right.arguments)) failures += unify(left, right); }, [&](auto, auto) { unificationFailure(); } }, _a, _b); return failures; } bool TypeEnvironment::typeEquals(Type _lhs, Type _rhs) const { return std::visit(util::GenericVisitor{ [&](TypeVariable _left, TypeVariable _right) { if (_left.index() == _right.index()) { solAssert(_left.sort() == _right.sort()); return true; } return false; }, [&](TypeConstant _left, TypeConstant _right) { if (_left.constructor != _right.constructor) return false; if (_left.arguments.size() != _right.arguments.size()) return false; for (auto&& [left, right]: ranges::zip_view(_left.arguments, _right.arguments)) if (!typeEquals(left, right)) return false; return true; }, [&](auto, auto) { return false; } }, resolve(_lhs), resolve(_rhs)); } bool TypeEnvironment::isFixedTypeVar(Type const& _typeVar) const { return std::holds_alternative<TypeVariable>(_typeVar) && m_fixedTypeVariables.count(std::get<TypeVariable>(_typeVar).index()) != 0; } void TypeEnvironment::fixTypeVars(std::vector<Type> const& _typeVars) { for (Type const& typeVar: _typeVars) { solAssert(std::holds_alternative<TypeVariable>(typeVar)); m_fixedTypeVariables.insert(std::get<TypeVariable>(typeVar).index()); } } TypeEnvironment TypeEnvironment::clone() const { TypeEnvironment result{m_typeSystem}; result.m_typeVariables = m_typeVariables; return result; } TypeSystem::TypeSystem() { auto declarePrimitiveClass = [&](std::string _name) { return std::visit(util::GenericVisitor{ [](std::string _error) -> TypeClass { solAssert(false, _error); }, [](TypeClass _class) -> TypeClass { return _class; } }, declareTypeClass(_name, nullptr, true /* _primitive */)); }; m_primitiveTypeClasses.emplace(PrimitiveClass::Type, declarePrimitiveClass("type")); for (auto [type, name, arity]: std::initializer_list<std::tuple<PrimitiveType, char const*, size_t>>{ {PrimitiveType::TypeFunction, "tfun", 2}, {PrimitiveType::Function, "fun", 2}, {PrimitiveType::Itself, "itself", 1}, {PrimitiveType::Void, "void", 0}, {PrimitiveType::Unit, "unit", 0}, {PrimitiveType::Pair, "pair", 2}, {PrimitiveType::Sum, "sum", 2}, {PrimitiveType::Word, "word", 0}, {PrimitiveType::Integer, "integer", 0}, {PrimitiveType::Bool, "bool", 0}, }) m_primitiveTypeConstructors.emplace(type, declareTypeConstructor(name, name, arity, nullptr)); TypeClass classType = primitiveClass(PrimitiveClass::Type); //TypeClass classKind = primitiveClass(PrimitiveClass::Kind); Sort typeSort{{classType}}; m_typeConstructors.at(m_primitiveTypeConstructors.at(PrimitiveType::TypeFunction).m_index).arities = {Arity{std::vector<Sort>{{typeSort},{typeSort}}, classType}}; m_typeConstructors.at(m_primitiveTypeConstructors.at(PrimitiveType::Function).m_index).arities = {Arity{std::vector<Sort>{{typeSort, typeSort}}, classType}}; m_typeConstructors.at(m_primitiveTypeConstructors.at(PrimitiveType::Itself).m_index).arities = {Arity{std::vector<Sort>{{typeSort, typeSort}}, classType}}; } experimental::Type TypeSystem::freshVariable(Sort _sort) { size_t index = m_numTypeVariables++; return TypeVariable(index, std::move(_sort)); } experimental::Type TypeSystem::freshTypeVariable(Sort _sort) { _sort.classes.emplace(primitiveClass(PrimitiveClass::Type)); return freshVariable(_sort); } std::vector<TypeEnvironment::UnificationFailure> TypeEnvironment::instantiate(TypeVariable _variable, Type _type) { for (auto const& maybeTypeVar: TypeEnvironmentHelpers{*this}.typeVars(_type)) if (auto const* typeVar = std::get_if<TypeVariable>(&maybeTypeVar)) if (typeVar->index() == _variable.index()) return {UnificationFailure{RecursiveUnification{_variable, _type}}}; Sort typeSort = sort(_type); if (!(_variable.sort() <= typeSort)) { return {UnificationFailure{SortMismatch{_type, _variable.sort() - typeSort}}}; } solAssert(m_typeVariables.emplace(_variable.index(), _type).second); return {}; } experimental::Type TypeEnvironment::resolve(Type _type) const { Type result = _type; while (auto const* var = std::get_if<TypeVariable>(&result)) if (Type const* resolvedType = util::valueOrNullptr(m_typeVariables, var->index())) result = *resolvedType; else break; return result; } experimental::Type TypeEnvironment::resolveRecursive(Type _type) const { return std::visit(util::GenericVisitor{ [&](TypeConstant const& _typeConstant) -> Type { return TypeConstant{ _typeConstant.constructor, _typeConstant.arguments | ranges::views::transform([&](Type const& _argType) { return resolveRecursive(_argType); }) | ranges::to<std::vector<Type>> }; }, [](TypeVariable const& _typeVar) -> Type { return _typeVar; }, [](std::monostate _nothing) -> Type { return _nothing; } }, resolve(_type)); } Sort TypeEnvironment::sort(Type _type) const { return std::visit(util::GenericVisitor{ [&](TypeConstant const& _expression) -> Sort { auto const& constructorInfo = m_typeSystem.constructorInfo(_expression.constructor); auto argumentSorts = _expression.arguments | ranges::views::transform([&](Type _argumentType) { return sort(resolve(_argumentType)); }) | ranges::to<std::vector<Sort>>; Sort sort; for (auto const& arity: constructorInfo.arities) { solAssert(arity.argumentSorts.size() == argumentSorts.size()); bool hasArity = true; for (auto&& [argumentSort, arityArgumentSort]: ranges::zip_view(argumentSorts, arity.argumentSorts)) { if (!(arityArgumentSort <= argumentSort)) { hasArity = false; break; } } if (hasArity) sort.classes.insert(arity.typeClass); } return sort; }, [](TypeVariable const& _variable) -> Sort { return _variable.sort(); }, [](std::monostate) -> Sort { solAssert(false); } }, _type); } TypeConstructor TypeSystem::declareTypeConstructor(std::string _name, std::string _canonicalName, size_t _arguments, Declaration const* _declaration) { solAssert(m_canonicalTypeNames.insert(_canonicalName).second, "Duplicate canonical type name."); Sort baseSort{{primitiveClass(PrimitiveClass::Type)}}; size_t index = m_typeConstructors.size(); m_typeConstructors.emplace_back(TypeConstructorInfo{ _name, _canonicalName, {Arity{std::vector<Sort>{_arguments, baseSort}, primitiveClass(PrimitiveClass::Type)}}, _declaration }); TypeConstructor constructor{index}; if (_arguments) { std::vector<Sort> argumentSorts; std::generate_n(std::back_inserter(argumentSorts), _arguments, [&](){ return Sort{{primitiveClass(PrimitiveClass::Type)}}; }); std::vector<Type> argumentTypes; std::generate_n(std::back_inserter(argumentTypes), _arguments, [&](){ return freshVariable({}); }); m_globalTypeEnvironment.fixTypeVars(argumentTypes); auto error = instantiateClass(type(constructor, argumentTypes), Arity{argumentSorts, primitiveClass(PrimitiveClass::Type)}); solAssert(!error, *error); } else { auto error = instantiateClass(type(constructor, {}), Arity{{}, primitiveClass(PrimitiveClass::Type)}); solAssert(!error, *error); } return constructor; } std::variant<TypeClass, std::string> TypeSystem::declareTypeClass(std::string _name, Declaration const* _declaration, bool _primitive) { TypeClass typeClass{m_typeClasses.size()}; Type typeVariable = (_primitive ? freshVariable({{typeClass}}) : freshTypeVariable({{typeClass}})); solAssert(std::holds_alternative<TypeVariable>(typeVariable)); m_globalTypeEnvironment.fixTypeVars({typeVariable}); m_typeClasses.emplace_back(TypeClassInfo{ typeVariable, _name, _declaration }); return typeClass; } experimental::Type TypeSystem::type(TypeConstructor _constructor, std::vector<Type> _arguments) const { // TODO: proper error handling auto const& info = m_typeConstructors.at(_constructor.m_index); solAssert( info.arguments() == _arguments.size(), fmt::format("Type constructor '{}' accepts {} type arguments (got {}).", constructorInfo(_constructor).name, info.arguments(), _arguments.size()) ); return TypeConstant{_constructor, _arguments}; } experimental::Type TypeEnvironment::fresh(Type _type) { std::unordered_map<size_t, Type> mapping; auto freshImpl = [&](Type _type, auto _recurse) -> Type { return std::visit(util::GenericVisitor{ [&](TypeConstant const& _type) -> Type { return TypeConstant{ _type.constructor, _type.arguments | ranges::views::transform([&](Type _argType) { return _recurse(_argType, _recurse); }) | ranges::to<std::vector<Type>> }; }, [&](TypeVariable const& _var) -> Type { if (auto* mapped = util::valueOrNullptr(mapping, _var.index())) { auto* typeVariable = std::get_if<TypeVariable>(mapped); solAssert(typeVariable); // TODO: can there be a mismatch? solAssert(typeVariable->sort() == _var.sort()); return *mapped; } return mapping[_var.index()] = m_typeSystem.freshTypeVariable(_var.sort()); }, [](std::monostate) -> Type { solAssert(false); } }, resolve(_type)); }; return freshImpl(_type, freshImpl); } std::optional<std::string> TypeSystem::instantiateClass(Type _instanceVariable, Arity _arity) { if (!TypeSystemHelpers{*this}.isTypeConstant(_instanceVariable)) return "Invalid instance variable."; auto [typeConstructor, typeArguments] = TypeSystemHelpers{*this}.destTypeConstant(_instanceVariable); auto& typeConstructorInfo = m_typeConstructors.at(typeConstructor.m_index); if (_arity.argumentSorts.size() != typeConstructorInfo.arguments()) return "Invalid arity."; if (typeArguments.size() != typeConstructorInfo.arguments()) return "Invalid arity."; typeConstructorInfo.arities.emplace_back(_arity); return std::nullopt; }
12,520
C++
.cpp
333
34.666667
163
0.723128
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,229
TypeSystemHelper.cpp
ethereum_solidity/libsolidity/experimental/ast/TypeSystemHelper.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libsolidity/experimental/ast/TypeSystemHelper.h> #include <libsolidity/ast/AST.h> #include <libsolidity/experimental/analysis/Analysis.h> #include <libsolidity/experimental/analysis/TypeRegistration.h> #include <libsolutil/Visitor.h> #include <range/v3/algorithm/any_of.hpp> #include <range/v3/to_container.hpp> #include <range/v3/view/drop_exactly.hpp> #include <range/v3/view/drop_last.hpp> #include <range/v3/view/reverse.hpp> #include <fmt/format.h> using namespace solidity::langutil; using namespace solidity::frontend; using namespace solidity::frontend::experimental; /*std::optional<TypeConstructor> experimental::typeConstructorFromTypeName(Analysis const& _analysis, TypeName const& _typeName) { if (auto const* elementaryTypeName = dynamic_cast<ElementaryTypeName const*>(&_typeName)) { if (auto constructor = typeConstructorFromToken(_analysis, elementaryTypeName->typeName().token())) return *constructor; } else if (auto const* userDefinedType = dynamic_cast<UserDefinedTypeName const*>(&_typeName)) { if (auto const* referencedDeclaration = userDefinedType->pathNode().annotation().referencedDeclaration) return _analysis.annotation<TypeRegistration>(*referencedDeclaration).typeConstructor; } return nullopt; }*/ /* std::optional<TypeConstructor> experimental::typeConstructorFromToken(Analysis const& _analysis, langutil::Token _token) { TypeSystem const& typeSystem = _analysis.typeSystem(); switch (_token) { case Token::Void: return typeSystem.builtinConstructor(BuiltinType::Void); case Token::Fun: return typeSystem.builtinConstructor(BuiltinType::Function); case Token::Unit: return typeSystem.builtinConstructor(BuiltinType::Unit); case Token::Pair: return typeSystem.builtinConstructor(BuiltinType::Pair); case Token::Word: return typeSystem.builtinConstructor(BuiltinType::Word); case Token::IntegerType: return typeSystem.builtinConstructor(BuiltinType::Integer); case Token::Bool: return typeSystem.builtinConstructor(BuiltinType::Bool); default: return nullopt; } }*/ std::optional<BuiltinClass> experimental::builtinClassFromToken(langutil::Token _token) { switch (_token) { case Token::Integer: return BuiltinClass::Integer; case Token::Mul: return BuiltinClass::Mul; case Token::Add: return BuiltinClass::Add; case Token::Equal: return BuiltinClass::Equal; case Token::LessThan: return BuiltinClass::Less; case Token::LessThanOrEqual: return BuiltinClass::LessOrEqual; case Token::GreaterThan: return BuiltinClass::Greater; case Token::GreaterThanOrEqual: return BuiltinClass::GreaterOrEqual; default: return std::nullopt; } } /* std::optional<TypeClass> experimental::typeClassFromTypeClassName(TypeClassName const& _typeClass) { return std::visit(util::GenericVisitor{ [&](ASTPointer<IdentifierPath> _path) -> optional<TypeClass> { auto classDefinition = dynamic_cast<TypeClassDefinition const*>(_path->annotation().referencedDeclaration); if (!classDefinition) return nullopt; return TypeClass{classDefinition}; }, [&](Token _token) -> optional<TypeClass> { return typeClassFromToken(_token); } }, _typeClass.name()); } */ experimental::Type TypeSystemHelpers::tupleType(std::vector<Type> _elements) const { if (_elements.empty()) return typeSystem.type(PrimitiveType::Unit, {}); if (_elements.size() == 1) return _elements.front(); Type result = _elements.back(); for (Type type: _elements | ranges::views::reverse | ranges::views::drop_exactly(1)) result = typeSystem.type(PrimitiveType::Pair, {type, result}); return result; } std::vector<experimental::Type> TypeSystemHelpers::destTupleType(Type _tupleType) const { if (!isTypeConstant(_tupleType)) return {_tupleType}; TypeConstructor pairConstructor = typeSystem.constructor(PrimitiveType::Pair); auto [constructor, arguments] = destTypeConstant(_tupleType); if (constructor == typeSystem.constructor(PrimitiveType::Unit)) return {}; if (constructor != pairConstructor) return {_tupleType}; solAssert(arguments.size() == 2); std::vector<Type> result; result.emplace_back(arguments.front()); Type tail = arguments.back(); while (true) { if (!isTypeConstant(tail)) break; auto [tailConstructor, tailArguments] = destTypeConstant(tail); if (tailConstructor != pairConstructor) break; solAssert(tailArguments.size() == 2); result.emplace_back(tailArguments.front()); tail = tailArguments.back(); } result.emplace_back(tail); return result; } experimental::Type TypeSystemHelpers::sumType(std::vector<Type> _elements) const { if (_elements.empty()) return typeSystem.type(PrimitiveType::Void, {}); if (_elements.size() == 1) return _elements.front(); Type result = _elements.back(); for (Type type: _elements | ranges::views::reverse | ranges::views::drop_exactly(1)) result = typeSystem.type(PrimitiveType::Sum, {type, result}); return result; } std::vector<experimental::Type> TypeSystemHelpers::destSumType(Type _tupleType) const { if (!isTypeConstant(_tupleType)) return {_tupleType}; TypeConstructor sumConstructor = typeSystem.constructor(PrimitiveType::Sum); auto [constructor, arguments] = destTypeConstant(_tupleType); if (constructor == typeSystem.constructor(PrimitiveType::Void)) return {}; if (constructor != sumConstructor) return {_tupleType}; solAssert(arguments.size() == 2); std::vector<Type> result; result.emplace_back(arguments.front()); Type tail = arguments.back(); while (true) { if (!isTypeConstant(tail)) break; auto [tailConstructor, tailArguments] = destTypeConstant(tail); if (tailConstructor != sumConstructor) break; solAssert(tailArguments.size() == 2); result.emplace_back(tailArguments.front()); tail = tailArguments.back(); } result.emplace_back(tail); return result; } std::tuple<TypeConstructor, std::vector<experimental::Type>> TypeSystemHelpers::destTypeConstant(Type _type) const { using ResultType = std::tuple<TypeConstructor, std::vector<Type>>; return std::visit(util::GenericVisitor{ [&](TypeConstant const& _type) -> ResultType { return std::make_tuple(_type.constructor, _type.arguments); }, [](auto const&) -> ResultType { solAssert(false); } }, _type); } bool TypeSystemHelpers::isTypeConstant(Type _type) const { return std::visit(util::GenericVisitor{ [&](TypeConstant const&) -> bool { return true; }, [](auto const&) -> bool { return false; } }, _type); } bool TypeSystemHelpers::isPrimitiveType(Type _type, PrimitiveType _primitiveType) const { if (!isTypeConstant(_type)) return false; auto constructor = std::get<0>(destTypeConstant(_type)); return constructor == typeSystem.constructor(_primitiveType); } experimental::Type TypeSystemHelpers::functionType(experimental::Type _argType, experimental::Type _resultType) const { return typeSystem.type(PrimitiveType::Function, {_argType, _resultType}); } std::tuple<experimental::Type, experimental::Type> TypeSystemHelpers::destFunctionType(Type _functionType) const { auto [constructor, arguments] = destTypeConstant(_functionType); solAssert(constructor == typeSystem.constructor(PrimitiveType::Function)); solAssert(arguments.size() == 2); return std::make_tuple(arguments.front(), arguments.back()); } bool TypeSystemHelpers::isFunctionType(Type _type) const { return isPrimitiveType(_type, PrimitiveType::Function); } experimental::Type TypeSystemHelpers::typeFunctionType(experimental::Type _argType, experimental::Type _resultType) const { return typeSystem.type(PrimitiveType::TypeFunction, {_argType, _resultType}); } std::tuple<experimental::Type, experimental::Type> TypeSystemHelpers::destTypeFunctionType(Type _functionType) const { auto [constructor, arguments] = destTypeConstant(_functionType); solAssert(constructor == typeSystem.constructor(PrimitiveType::TypeFunction)); solAssert(arguments.size() == 2); return std::make_tuple(arguments.front(), arguments.back()); } bool TypeSystemHelpers::isTypeFunctionType(Type _type) const { return isPrimitiveType(_type, PrimitiveType::TypeFunction); } std::vector<experimental::Type> TypeEnvironmentHelpers::typeVars(Type _type) const { std::set<size_t> indices; std::vector<Type> typeVars; auto typeVarsImpl = [&](Type _type, auto _recurse) -> void { std::visit(util::GenericVisitor{ [&](TypeConstant const& _type) { for (auto arg: _type.arguments) _recurse(arg, _recurse); }, [&](TypeVariable const& _var) { if (indices.emplace(_var.index()).second) typeVars.emplace_back(_var); }, [](std::monostate) { solAssert(false); } }, env.resolve(_type)); }; typeVarsImpl(_type, typeVarsImpl); return typeVars; } bool TypeEnvironmentHelpers::hasGenericTypeVars(Type const& _type) const { return ranges::any_of( TypeEnvironmentHelpers{*this}.typeVars(_type), [&](Type const& _maybeTypeVar) { solAssert(std::holds_alternative<TypeVariable>(_maybeTypeVar)); return !env.isFixedTypeVar(_maybeTypeVar); } ); } experimental::Type TypeEnvironmentHelpers::substitute( Type const& _type, Type const& _partToReplace, Type const& _replacement ) const { using ranges::views::transform; using ranges::to; if (env.typeEquals(_type, _partToReplace)) return _replacement; auto recurse = [&](Type const& _t) { return substitute(_t, _partToReplace, _replacement); }; return visit(util::GenericVisitor{ [&](TypeConstant const& _typeConstant) -> Type { return TypeConstant{ _typeConstant.constructor, _typeConstant.arguments | transform(recurse) | to<std::vector<Type>>, }; }, [&](auto const& _type) -> Type { return _type; }, }, env.resolve(_type)); } std::string TypeSystemHelpers::sortToString(Sort _sort) const { switch (_sort.classes.size()) { case 0: return "()"; case 1: return typeSystem.typeClassName(*_sort.classes.begin()); default: { std::stringstream stream; stream << "("; for (auto typeClass: _sort.classes | ranges::views::drop_last(1)) stream << typeSystem.typeClassName(typeClass) << ", "; stream << typeSystem.typeClassName(*_sort.classes.rbegin()) << ")"; return stream.str(); } } } std::string TypeEnvironmentHelpers::canonicalTypeName(Type _type) const { return visit(util::GenericVisitor{ [&](TypeConstant _type) -> std::string { std::stringstream stream; stream << env.typeSystem().constructorInfo(_type.constructor).canonicalName; if (!_type.arguments.empty()) { stream << "$"; for (auto type: _type.arguments | ranges::views::drop_last(1)) stream << canonicalTypeName(type) << "$"; stream << canonicalTypeName(_type.arguments.back()); stream << "$"; } return stream.str(); }, [](TypeVariable) -> std::string { solAssert(false); }, [](std::monostate) -> std::string { solAssert(false); }, }, env.resolve(_type)); } std::string TypeEnvironmentHelpers::typeToString(Type const& _type) const { std::map<TypeConstructor, std::function<std::string(std::vector<Type>)>> formatters{ {env.typeSystem().constructor(PrimitiveType::Function), [&](auto const& _args) { solAssert(_args.size() == 2); return fmt::format("{} -> {}", typeToString(_args.front()), typeToString(_args.back())); }}, {env.typeSystem().constructor(PrimitiveType::Unit), [&](auto const& _args) { solAssert(_args.size() == 0); return "()"; }}, {env.typeSystem().constructor(PrimitiveType::Pair), [&](auto const& _arguments) { auto tupleTypes = TypeSystemHelpers{env.typeSystem()}.destTupleType(_arguments.back()); std::string result = "("; result += typeToString(_arguments.front()); for (auto type: tupleTypes) result += ", " + typeToString(type); result += ")"; return result; }}, }; return std::visit(util::GenericVisitor{ [&](TypeConstant const& _type) { if (auto* formatter = util::valueOrNullptr(formatters, _type.constructor)) return (*formatter)(_type.arguments); std::stringstream stream; stream << env.typeSystem().constructorInfo(_type.constructor).name; if (!_type.arguments.empty()) { stream << "("; for (auto type: _type.arguments | ranges::views::drop_last(1)) stream << typeToString(type) << ", "; stream << typeToString(_type.arguments.back()); stream << ")"; } return stream.str(); }, [&](TypeVariable const& _type) { std::stringstream stream; std::string varName; size_t index = _type.index(); varName += static_cast<char>('a' + (index%26)); while (index /= 26) varName += static_cast<char>('a' + (index%26)); reverse(varName.begin(), varName.end()); stream << (env.isFixedTypeVar(_type) ? "'" : "?") << varName; switch (_type.sort().classes.size()) { case 0: break; case 1: stream << ":" << env.typeSystem().typeClassName(*_type.sort().classes.begin()); break; default: stream << ":("; for (auto typeClass: _type.sort().classes | ranges::views::drop_last(1)) stream << env.typeSystem().typeClassName(typeClass) << ", "; stream << env.typeSystem().typeClassName(*_type.sort().classes.rbegin()); stream << ")"; break; } return stream.str(); }, [](std::monostate) -> std::string { solAssert(false); } }, env.resolve(_type)); }
13,896
C++
.cpp
406
31.596059
128
0.733908
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,230
Version.cpp
ethereum_solidity/libsolidity/interface/Version.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 /** * @author Christian <c@ethdev.com> * @date 2015 * Versioning. */ #include <libsolidity/interface/Version.h> #include <solidity/BuildInfo.h> char const* solidity::frontend::VersionNumber = ETH_PROJECT_VERSION; std::string const solidity::frontend::VersionString = std::string(solidity::frontend::VersionNumber) + (std::string(SOL_VERSION_PRERELEASE).empty() ? "" : "-" + std::string(SOL_VERSION_PRERELEASE)) + (std::string(SOL_VERSION_BUILDINFO).empty() ? "" : "+" + std::string(SOL_VERSION_BUILDINFO)); std::string const solidity::frontend::VersionStringStrict = std::string(solidity::frontend::VersionNumber) + (std::string(SOL_VERSION_PRERELEASE).empty() ? "" : "-" + std::string(SOL_VERSION_PRERELEASE)) + (std::string(SOL_VERSION_COMMIT).empty() ? "" : "+" + std::string(SOL_VERSION_COMMIT)); solidity::bytes const solidity::frontend::VersionCompactBytes = { ETH_PROJECT_VERSION_MAJOR, ETH_PROJECT_VERSION_MINOR, ETH_PROJECT_VERSION_PATCH }; bool const solidity::frontend::VersionIsRelease = std::string(SOL_VERSION_PRERELEASE).empty();
1,750
C++
.cpp
36
46.666667
97
0.756455
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
3,231
FileReader.cpp
ethereum_solidity/libsolidity/interface/FileReader.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libsolidity/interface/FileReader.h> #include <liblangutil/Exceptions.h> #include <libsolutil/CommonIO.h> #include <libsolutil/Exceptions.h> #include <libsolutil/StringUtils.h> #include <boost/algorithm/string/predicate.hpp> #include <range/v3/view/transform.hpp> #include <range/v3/range/conversion.hpp> #include <functional> using solidity::frontend::ReadCallback; using solidity::util::errinfo_comment; using solidity::util::readFileAsString; using solidity::util::joinHumanReadable; namespace solidity::frontend { FileReader::FileReader( boost::filesystem::path _basePath, std::vector<boost::filesystem::path> const& _includePaths, FileSystemPathSet _allowedDirectories ): m_allowedDirectories(std::move(_allowedDirectories)), m_sourceCodes() { setBasePath(_basePath); for (boost::filesystem::path const& includePath: _includePaths) addIncludePath(includePath); for (boost::filesystem::path const& allowedDir: m_allowedDirectories) solAssert(!allowedDir.empty(), ""); } void FileReader::setBasePath(boost::filesystem::path const& _path) { if (_path.empty()) { // Empty base path is a special case that does not make sense when include paths are used. solAssert(m_includePaths.empty(), ""); m_basePath = ""; } else m_basePath = normalizeCLIPathForVFS(_path); } void FileReader::addIncludePath(boost::filesystem::path const& _path) { solAssert(!m_basePath.empty(), ""); solAssert(!_path.empty(), ""); m_includePaths.push_back(normalizeCLIPathForVFS(_path)); } void FileReader::allowDirectory(boost::filesystem::path _path) { solAssert(!_path.empty(), ""); m_allowedDirectories.insert(std::move(_path)); } void FileReader::addOrUpdateFile(boost::filesystem::path const& _path, SourceCode _source) { m_sourceCodes[cliPathToSourceUnitName(_path)] = std::move(_source); } void FileReader::setStdin(SourceCode _source) { m_sourceCodes["<stdin>"] = std::move(_source); } void FileReader::setSourceUnits(StringMap _sources) { m_sourceCodes = std::move(_sources); } ReadCallback::Result FileReader::readFile(std::string const& _kind, std::string const& _sourceUnitName) { try { if (_kind != ReadCallback::kindString(ReadCallback::Kind::ReadFile)) solAssert(false, "ReadFile callback used as callback kind " + _kind); std::string strippedSourceUnitName = _sourceUnitName; if (strippedSourceUnitName.find("file://") == 0) strippedSourceUnitName.erase(0, 7); std::vector<boost::filesystem::path> candidates; std::vector<std::reference_wrapper<boost::filesystem::path>> prefixes = {m_basePath}; prefixes += (m_includePaths | ranges::to<std::vector<std::reference_wrapper<boost::filesystem::path>>>); for (auto const& prefix: prefixes) { boost::filesystem::path canonicalPath = normalizeCLIPathForVFS(prefix / strippedSourceUnitName, SymlinkResolution::Enabled); if (boost::filesystem::exists(canonicalPath)) candidates.push_back(std::move(canonicalPath)); } auto pathToQuotedString = [](boost::filesystem::path const& _path){ return "\"" + _path.string() + "\""; }; if (candidates.empty()) return ReadCallback::Result{ false, "File not found. Searched the following locations: " + joinHumanReadable(prefixes | ranges::views::transform(pathToQuotedString), ", ") + "." }; if (candidates.size() >= 2) return ReadCallback::Result{ false, "Ambiguous import. " "Multiple matching files found inside base path and/or include paths: " + joinHumanReadable(candidates | ranges::views::transform(pathToQuotedString), ", ") + "." }; FileSystemPathSet allowedPaths = m_allowedDirectories + decltype(allowedPaths){m_basePath.empty() ? "." : m_basePath} + m_includePaths; bool isAllowed = false; for (boost::filesystem::path const& allowedDir: allowedPaths) if (isPathPrefix(normalizeCLIPathForVFS(allowedDir, SymlinkResolution::Enabled), candidates[0])) { isAllowed = true; break; } if (!isAllowed) return ReadCallback::Result{ false, "File outside of allowed directories. The following are allowed: " + joinHumanReadable(allowedPaths | ranges::views::transform(pathToQuotedString), ", ") + "." }; if (!boost::filesystem::is_regular_file(candidates[0])) return ReadCallback::Result{false, "Not a valid file."}; // NOTE: we ignore the FileNotFound exception as we manually check above auto contents = readFileAsString(candidates[0]); solAssert(m_sourceCodes.count(_sourceUnitName) == 0, ""); m_sourceCodes[_sourceUnitName] = contents; return ReadCallback::Result{true, contents}; } catch (...) { return ReadCallback::Result{false, "Exception in read callback: " + boost::current_exception_diagnostic_information()}; } } std::string FileReader::cliPathToSourceUnitName(boost::filesystem::path const& _cliPath) const { std::vector<boost::filesystem::path> prefixes = {m_basePath.empty() ? normalizeCLIPathForVFS(".") : m_basePath}; prefixes += m_includePaths; boost::filesystem::path normalizedPath = normalizeCLIPathForVFS(_cliPath); for (boost::filesystem::path const& prefix: prefixes) if (isPathPrefix(prefix, normalizedPath)) { // Multiple prefixes can potentially match the path. We take the first one. normalizedPath = stripPrefixIfPresent(prefix, normalizedPath); break; } return normalizedPath.generic_string(); } std::map<std::string, FileReader::FileSystemPathSet> FileReader::detectSourceUnitNameCollisions(FileSystemPathSet const& _cliPaths) const { std::map<std::string, FileReader::FileSystemPathSet> nameToPaths; for (boost::filesystem::path const& cliPath: _cliPaths) { std::string sourceUnitName = cliPathToSourceUnitName(cliPath); boost::filesystem::path normalizedPath = normalizeCLIPathForVFS(cliPath); nameToPaths[sourceUnitName].insert(normalizedPath); } std::map<std::string, FileReader::FileSystemPathSet> collisions; for (auto&& [sourceUnitName, cliPaths]: nameToPaths) if (cliPaths.size() >= 2) collisions[sourceUnitName] = std::move(cliPaths); return collisions; } boost::filesystem::path FileReader::normalizeCLIPathForVFS( boost::filesystem::path const& _path, SymlinkResolution _symlinkResolution ) { // Detailed normalization rules: // - Makes the path either be absolute or have slash as root (note that on Windows paths with // slash as root are not considered absolute by Boost). If it is empty, it becomes // the current working directory. // - Collapses redundant . and .. segments. // - Removes leading .. segments from an absolute path (i.e. /../../ becomes just /). // - Squashes sequences of multiple path separators into one. // - Ensures that forward slashes are used as path separators on all platforms. // - Removes the root name (e.g. drive letter on Windows) when it matches the root name in the // path to the current working directory. // // Also note that this function: // - Does NOT resolve symlinks (except for symlinks in the path to the current working directory) // unless explicitly requested. // - Does NOT check if the path refers to a file or a directory. If the path ends with a slash, // the slash is preserved even if it's a file. // - The only exception are paths where the file name is a dot (e.g. '.' or 'a/b/.'). These // always have a trailing slash after normalization. // - Preserves case. Even if the filesystem is case-insensitive but case-preserving and the // case differs, the actual case from disk is NOT detected. boost::filesystem::path canonicalWorkDir = boost::filesystem::weakly_canonical(boost::filesystem::current_path()); // NOTE: On UNIX systems the path returned from current_path() has symlinks resolved while on // Windows it does not. To get consistent results we resolve them on all platforms. boost::filesystem::path absolutePath = boost::filesystem::absolute(_path, canonicalWorkDir); boost::filesystem::path normalizedPath; if (_symlinkResolution == SymlinkResolution::Enabled) { // NOTE: weakly_canonical() will not convert a relative path into an absolute one if no // directory included in the path actually exists. normalizedPath = boost::filesystem::weakly_canonical(absolutePath); // The three corner cases in which lexically_normal() includes a trailing slash in the // normalized path but weakly_canonical() does not. Note that the trailing slash is not // ignored when comparing paths with ==. if ((_path == "." || _path == "./" || _path == "../") && !boost::ends_with(normalizedPath.generic_string(), "/")) normalizedPath = normalizedPath.parent_path() / (normalizedPath.filename().string() + "/"); } else { solAssert(_symlinkResolution == SymlinkResolution::Disabled, ""); // NOTE: boost path preserves certain differences that are ignored by its operator ==. // E.g. "a//b" vs "a/b" or "a/b/" vs "a/b/.". lexically_normal() does remove these differences. normalizedPath = absolutePath.lexically_normal(); } solAssert(normalizedPath.is_absolute() || normalizedPath.root_path() == "/", ""); // If the path is on the same drive as the working dir, for portability we prefer not to // include the root name. Do this only for non-UNC paths - my experiments show that on Windows // when the working dir is an UNC path, / does not actually refer to the root of the UNC path. boost::filesystem::path normalizedRootPath = normalizeCLIRootPathForVFS(normalizedPath, canonicalWorkDir); // lexically_normal() will not squash paths like "/../../" into "/". We have to do it manually. boost::filesystem::path dotDotPrefix = absoluteDotDotPrefix(normalizedPath); boost::filesystem::path normalizedPathNoDotDot = normalizedPath; if (dotDotPrefix.empty()) normalizedPathNoDotDot = normalizedRootPath / normalizedPath.relative_path(); else normalizedPathNoDotDot = normalizedRootPath / normalizedPath.lexically_relative(normalizedPath.root_path() / dotDotPrefix); solAssert(!hasDotDotSegments(normalizedPathNoDotDot), ""); // NOTE: On Windows lexically_normal() converts all separators to forward slashes. Convert them back. // Separators do not affect path comparison but remain in internal representation returned by native(). // This will also normalize the root name to start with // in UNC paths. normalizedPathNoDotDot = normalizedPathNoDotDot.generic_string(); // For some reason boost considers "/." different than "/" even though for other directories // the trailing dot is ignored. if (normalizedPathNoDotDot == "/.") return "/"; return normalizedPathNoDotDot; } boost::filesystem::path FileReader::normalizeCLIRootPathForVFS( boost::filesystem::path const& _path, boost::filesystem::path const& _workDir ) { solAssert(_workDir.is_absolute(), ""); boost::filesystem::path absolutePath = boost::filesystem::absolute(_path, _workDir); boost::filesystem::path rootPath = absolutePath.root_path(); boost::filesystem::path baseRootPath = _workDir.root_path(); if (isUNCPath(absolutePath)) return rootPath; // Ignore drive letter case on Windows (C:\ <=> c:\). if (boost::filesystem::equivalent(rootPath, baseRootPath)) return "/"; return rootPath; } bool FileReader::isPathPrefix(boost::filesystem::path const& _prefix, boost::filesystem::path const& _path) { solAssert(!_prefix.empty() && !_path.empty(), ""); // NOTE: On Windows paths starting with a slash (rather than a drive letter) are considered relative by boost. solAssert(_prefix.is_absolute() || isUNCPath(_prefix) || _prefix.root_path() == "/", ""); solAssert(_path.is_absolute() || isUNCPath(_path) || _path.root_path() == "/", ""); // NOTE: On Windows before Boost 1.78 lexically_normal() would not replace the `//` UNC prefix with `\\\\`. // Later versions do. Use generic_path() to normalize all slashes to `/` and ignore that difference. // This does not make the assert weaker because == ignores slash type anyway. solAssert(_prefix == _prefix.lexically_normal().generic_string() && _path == _path.lexically_normal().generic_string(), ""); solAssert(!hasDotDotSegments(_prefix) && !hasDotDotSegments(_path), ""); boost::filesystem::path strippedPath = _path.lexically_relative( // Before 1.72.0 lexically_relative() was not handling paths with empty, dot and dot dot segments // correctly (see https://github.com/boostorg/filesystem/issues/76). The only case where this // is possible after our normalization is a directory name ending in a slash (filename is a dot). _prefix.filename_is_dot() ? _prefix.parent_path() : _prefix ); return !strippedPath.empty() && *strippedPath.begin() != ".."; } boost::filesystem::path FileReader::stripPrefixIfPresent(boost::filesystem::path const& _prefix, boost::filesystem::path const& _path) { if (!isPathPrefix(_prefix, _path)) return _path; boost::filesystem::path strippedPath = _path.lexically_relative( _prefix.filename_is_dot() ? _prefix.parent_path() : _prefix ); solAssert(strippedPath.empty() || *strippedPath.begin() != "..", ""); return strippedPath; } boost::filesystem::path FileReader::absoluteDotDotPrefix(boost::filesystem::path const& _path) { solAssert(_path.is_absolute() || _path.root_path() == "/", ""); boost::filesystem::path _pathWithoutRoot = _path.relative_path(); boost::filesystem::path prefix; for (boost::filesystem::path const& segment: _pathWithoutRoot) if (segment.filename_is_dot_dot()) prefix /= segment; return prefix; } bool FileReader::hasDotDotSegments(boost::filesystem::path const& _path) { for (boost::filesystem::path const& segment: _path) if (segment.filename_is_dot_dot()) return true; return false; } bool FileReader::isUNCPath(boost::filesystem::path const& _path) { std::string rootName = _path.root_name().string(); return ( rootName.size() == 2 || (rootName.size() > 2 && rootName[2] != rootName[1]) ) && ( (rootName[0] == '/' && rootName[1] == '/') #if defined(_WIN32) || (rootName[0] == '\\' && rootName[1] == '\\') #endif ); } }
14,623
C++
.cpp
318
43.512579
137
0.741854
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
3,232
CompilerStack.cpp
ethereum_solidity/libsolidity/interface/CompilerStack.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 /** * @author Christian <c@ethdev.com> * @author Gav Wood <g@ethdev.com> * @date 2014 * Full-stack compiler that converts a source code string to bytecode. */ #include <libsolidity/interface/CompilerStack.h> #include <libsolidity/interface/ImportRemapper.h> #include <libsolidity/analysis/ControlFlowAnalyzer.h> #include <libsolidity/analysis/ControlFlowGraph.h> #include <libsolidity/analysis/ControlFlowRevertPruner.h> #include <libsolidity/analysis/ContractLevelChecker.h> #include <libsolidity/analysis/DeclarationTypeChecker.h> #include <libsolidity/analysis/DocStringAnalyser.h> #include <libsolidity/analysis/DocStringTagParser.h> #include <libsolidity/analysis/GlobalContext.h> #include <libsolidity/analysis/NameAndTypeResolver.h> #include <libsolidity/analysis/PostTypeChecker.h> #include <libsolidity/analysis/PostTypeContractLevelChecker.h> #include <libsolidity/analysis/StaticAnalyzer.h> #include <libsolidity/analysis/SyntaxChecker.h> #include <libsolidity/analysis/Scoper.h> #include <libsolidity/analysis/TypeChecker.h> #include <libsolidity/analysis/ViewPureChecker.h> #include <libsolidity/analysis/ImmutableValidator.h> #include <libsolidity/ast/AST.h> #include <libsolidity/ast/TypeProvider.h> #include <libsolidity/ast/ASTJsonImporter.h> #include <libsolidity/codegen/Compiler.h> #include <libsolidity/formal/ModelChecker.h> #include <libsolidity/interface/ABI.h> #include <libsolidity/interface/Natspec.h> #include <libsolidity/interface/GasEstimator.h> #include <libsolidity/interface/StorageLayout.h> #include <libsolidity/interface/UniversalCallback.h> #include <libsolidity/interface/Version.h> #include <libsolidity/parsing/Parser.h> #include <libsolidity/experimental/analysis/Analysis.h> #include <libsolidity/experimental/analysis/FunctionDependencyAnalysis.h> #include <libsolidity/experimental/codegen/IRGenerator.h> #include <libsolidity/codegen/ir/Common.h> #include <libsolidity/codegen/ir/IRGenerator.h> #include <libstdlib/stdlib.h> #include <libyul/YulName.h> #include <libyul/AsmPrinter.h> #include <libyul/AsmJsonConverter.h> #include <libyul/YulStack.h> #include <libyul/AST.h> #include <libyul/AsmParser.h> #include <libyul/optimiser/Suite.h> #include <liblangutil/Scanner.h> #include <liblangutil/SemVerHandler.h> #include <liblangutil/SourceReferenceFormatter.h> #include <libsolutil/SwarmHash.h> #include <libsolutil/IpfsHash.h> #include <libsolutil/JSON.h> #include <libsolutil/Algorithms.h> #include <libsolutil/FunctionSelector.h> #include <boost/algorithm/string/replace.hpp> #include <range/v3/algorithm/all_of.hpp> #include <range/v3/view/concat.hpp> #include <range/v3/view/map.hpp> #include <fmt/format.h> #include <utility> #include <map> #include <limits> #include <string> using namespace solidity; using namespace solidity::langutil; using namespace solidity::frontend; using namespace solidity::stdlib; using namespace solidity::yul; using namespace std::string_literals; using solidity::util::errinfo_comment; static int g_compilerStackCounts = 0; CompilerStack::CompilerStack(ReadCallback::Callback _readFile): m_readFile{std::move(_readFile)}, m_objectOptimizer(std::make_shared<yul::ObjectOptimizer>()), m_errorReporter{m_errorList} { // Because TypeProvider is currently a singleton API, we must ensure that // no more than one entity is actually using it at a time. solAssert(g_compilerStackCounts == 0, "You shall not have another CompilerStack aside me."); ++g_compilerStackCounts; } CompilerStack::~CompilerStack() { --g_compilerStackCounts; TypeProvider::reset(); } void CompilerStack::createAndAssignCallGraphs() { for (Source const* source: m_sourceOrder) { if (!source->ast) continue; for (ContractDefinition const* contract: ASTNode::filteredNodes<ContractDefinition>(source->ast->nodes())) { ContractDefinitionAnnotation& annotation = m_contracts.at(contract->fullyQualifiedName()).contract->annotation(); annotation.creationCallGraph = std::make_unique<CallGraph>( FunctionCallGraphBuilder::buildCreationGraph(*contract) ); annotation.deployedCallGraph = std::make_unique<CallGraph>( FunctionCallGraphBuilder::buildDeployedGraph( *contract, **annotation.creationCallGraph ) ); solAssert(annotation.contractDependencies.empty(), "contractDependencies expected to be empty?!"); annotation.contractDependencies = annotation.creationCallGraph->get()->bytecodeDependency; for (auto const& [dependencyContract, referencee]: annotation.deployedCallGraph->get()->bytecodeDependency) annotation.contractDependencies.emplace(dependencyContract, referencee); } } } void CompilerStack::findAndReportCyclicContractDependencies() { // Cycles we found, used to avoid duplicate reports for the same reference std::set<ASTNode const*, ASTNode::CompareByID> foundCycles; for (Source const* source: m_sourceOrder) { if (!source->ast) continue; for (ContractDefinition const* contractDefinition: ASTNode::filteredNodes<ContractDefinition>(source->ast->nodes())) { util::CycleDetector<ContractDefinition> cycleDetector{[&]( ContractDefinition const& _contract, util::CycleDetector<ContractDefinition>& _cycleDetector, size_t _depth ) { // No specific reason for exactly that number, just a limit we're unlikely to hit. if (_depth >= 256) m_errorReporter.fatalTypeError( 7864_error, _contract.location(), "Contract dependencies exhausting cyclic dependency validator" ); for (auto& [dependencyContract, referencee]: _contract.annotation().contractDependencies) if (_cycleDetector.run(*dependencyContract)) return; }}; ContractDefinition const* cycle = cycleDetector.run(*contractDefinition); if (!cycle) continue; ASTNode const* referencee = contractDefinition->annotation().contractDependencies.at(cycle); if (foundCycles.find(referencee) != foundCycles.end()) continue; SecondarySourceLocation secondaryLocation{}; secondaryLocation.append("Referenced contract is here:"s, cycle->location()); m_errorReporter.typeError( 7813_error, referencee->location(), secondaryLocation, "Circular reference to contract bytecode either via \"new\" or \"type(...).creationCode\" / \"type(...).runtimeCode\"." ); foundCycles.emplace(referencee); } } } void CompilerStack::setRemappings(std::vector<ImportRemapper::Remapping> _remappings) { solAssert(m_stackState < ParsedAndImported, "Must set remappings before parsing."); for (auto const& remapping: _remappings) solAssert(!remapping.prefix.empty(), ""); m_importRemapper.setRemappings(std::move(_remappings)); } void CompilerStack::setViaIR(bool _viaIR) { solAssert(m_stackState < ParsedAndImported, "Must set viaIR before parsing."); m_viaIR = _viaIR; } void CompilerStack::setEVMVersion(langutil::EVMVersion _version) { solAssert(m_stackState < ParsedAndImported, "Must set EVM version before parsing."); m_evmVersion = _version; // GlobalContext depends on evmVersion since the Cancun hardfork. // Therefore, we reset it whenever we set a new EVM version, ensuring that the context is never reused with a mismatched version. m_globalContext.reset(); } void CompilerStack::setEOFVersion(std::optional<uint8_t> _version) { solAssert(m_stackState < CompilationSuccessful, "Must set EOF version before compiling."); solAssert(!_version || _version == 1, "Invalid EOF version."); m_eofVersion = _version; } void CompilerStack::setModelCheckerSettings(ModelCheckerSettings _settings) { solAssert(m_stackState < ParsedAndImported, "Must set model checking settings before parsing."); m_modelCheckerSettings = _settings; } void CompilerStack::selectContracts(ContractSelection const& _selectedContracts) { solAssert(m_stackState < ParsedAndImported, "Must request outputs before parsing."); m_selectedContracts = _selectedContracts; } void CompilerStack::setLibraries(std::map<std::string, util::h160> const& _libraries) { solAssert(m_stackState < ParsedAndImported, "Must set libraries before parsing."); m_libraries = _libraries; } void CompilerStack::setOptimiserSettings(bool _optimize, size_t _runs) { OptimiserSettings settings = _optimize ? OptimiserSettings::standard() : OptimiserSettings::minimal(); settings.expectedExecutionsPerDeployment = _runs; setOptimiserSettings(std::move(settings)); } void CompilerStack::setOptimiserSettings(OptimiserSettings _settings) { solAssert(m_stackState < ParsedAndImported, "Must set optimiser settings before parsing."); m_optimiserSettings = std::move(_settings); } void CompilerStack::setRevertStringBehaviour(RevertStrings _revertStrings) { solAssert(m_stackState < ParsedAndImported, "Must set revert string settings before parsing."); solUnimplementedAssert(_revertStrings != RevertStrings::VerboseDebug); m_revertStrings = _revertStrings; } void CompilerStack::useMetadataLiteralSources(bool _metadataLiteralSources) { solAssert(m_stackState < ParsedAndImported, "Must set use literal sources before parsing."); m_metadataLiteralSources = _metadataLiteralSources; } void CompilerStack::setMetadataHash(MetadataHash _metadataHash) { solAssert(m_stackState < ParsedAndImported, "Must set metadata hash before parsing."); m_metadataHash = _metadataHash; } void CompilerStack::selectDebugInfo(DebugInfoSelection _debugInfoSelection) { solAssert(m_stackState < CompilationSuccessful, "Must select debug info components before compilation."); m_debugInfoSelection = _debugInfoSelection; } void CompilerStack::addSMTLib2Response(h256 const& _hash, std::string const& _response) { solAssert(m_stackState < ParsedAndImported, "Must add SMTLib2 responses before parsing."); m_smtlib2Responses[_hash] = _response; } void CompilerStack::reset(bool _keepSettings) { m_stackState = Empty; m_sources.clear(); m_maxAstId.reset(); m_smtlib2Responses.clear(); m_unhandledSMTLib2Queries.clear(); if (!_keepSettings) { m_importRemapper.clear(); m_libraries.clear(); m_viaIR = false; m_evmVersion = langutil::EVMVersion(); m_eofVersion.reset(); m_modelCheckerSettings = ModelCheckerSettings{}; m_selectedContracts.clear(); m_revertStrings = RevertStrings::Default; m_optimiserSettings = OptimiserSettings::minimal(); m_metadataLiteralSources = false; m_metadataFormat = defaultMetadataFormat(); m_metadataHash = MetadataHash::IPFS; m_stopAfter = State::CompilationSuccessful; m_compilationSourceType = CompilationSourceType::Solidity; } m_experimentalAnalysis.reset(); m_globalContext.reset(); m_sourceOrder.clear(); m_contracts.clear(); m_errorReporter.clear(); TypeProvider::reset(); } void CompilerStack::setSources(StringMap _sources) { solAssert(m_stackState != SourcesSet, "Cannot change sources once set."); solAssert(m_stackState == Empty, "Must set sources before parsing."); for (auto source: _sources) m_sources[source.first].charStream = std::make_unique<CharStream>(/*content*/std::move(source.second), /*name*/source.first); m_stackState = SourcesSet; } bool CompilerStack::parse() { solAssert(m_stackState == SourcesSet, "Must call parse only after the SourcesSet state."); m_errorReporter.clear(); if (SemVerVersion{std::string(VersionString)}.isPrerelease()) m_errorReporter.warning(3805_error, "This is a pre-release compiler version, please do not use it in production."); try { Parser parser{m_errorReporter, m_evmVersion, m_eofVersion}; std::vector<std::string> sourcesToParse; for (auto const& s: m_sources) sourcesToParse.push_back(s.first); for (size_t i = 0; i < sourcesToParse.size(); ++i) { std::string const& path = sourcesToParse[i]; Source& source = m_sources[path]; source.ast = parser.parse(*source.charStream); if (!source.ast) solAssert(Error::containsErrors(m_errorReporter.errors()), "Parser returned null but did not report error."); else { source.ast->annotation().path = path; for (auto const& import: ASTNode::filteredNodes<ImportDirective>(source.ast->nodes())) { solAssert(!import->path().empty(), "Import path cannot be empty."); // Check whether the import directive is for the standard library, // and if yes, add specified file to source units to be parsed. auto it = stdlib::sources.find(import->path()); if (it != stdlib::sources.end()) { auto [name, content] = *it; m_sources[name].charStream = std::make_unique<CharStream>(content, name); sourcesToParse.push_back(name); } // The current value of `path` is the absolute path as seen from this source file. // We first have to apply remappings before we can store the actual absolute path // as seen globally. import->annotation().absolutePath = applyRemapping(util::absolutePath( import->path(), path ), path); } if (m_stopAfter >= ParsedAndImported) for (auto const& newSource: loadMissingSources(*source.ast)) { std::string const& newPath = newSource.first; std::string const& newContents = newSource.second; m_sources[newPath].charStream = std::make_shared<CharStream>(newContents, newPath); sourcesToParse.push_back(newPath); } } } if (Error::containsErrors(m_errorReporter.errors())) return false; m_stackState = (m_stopAfter <= Parsed ? Parsed : ParsedAndImported); storeContractDefinitions(); solAssert(!m_maxAstId.has_value()); m_maxAstId = parser.maxID(); } catch (UnimplementedFeatureError const& _error) { reportUnimplementedFeatureError(_error); } return true; } void CompilerStack::importASTs(std::map<std::string, Json> const& _sources) { solAssert(m_stackState == Empty, "Must call importASTs only before the SourcesSet state."); std::map<std::string, ASTPointer<SourceUnit>> reconstructedSources = ASTJsonImporter(m_evmVersion, m_eofVersion).jsonToSourceUnit(_sources); for (auto& src: reconstructedSources) { solUnimplementedAssert(!src.second->experimentalSolidity()); std::string const& path = src.first; Source source; source.ast = src.second; source.charStream = std::make_shared<CharStream>( util::jsonCompactPrint(_sources.at(src.first)), src.first, true // imported from AST ); m_sources[path] = std::move(source); } m_stackState = ParsedAndImported; m_compilationSourceType = CompilationSourceType::SolidityAST; storeContractDefinitions(); } bool CompilerStack::analyze() { solAssert(m_stackState == ParsedAndImported, "Must call analyze only after parsing was successful."); if (!resolveImports()) return false; for (Source const* source: m_sourceOrder) if (source->ast) Scoper::assignScopes(*source->ast); bool noErrors = true; try { bool experimentalSolidity = isExperimentalSolidity(); SyntaxChecker syntaxChecker(m_errorReporter, m_optimiserSettings.runYulOptimiser); for (Source const* source: m_sourceOrder) if (source->ast && !syntaxChecker.checkSyntax(*source->ast)) noErrors = false; m_globalContext = std::make_shared<GlobalContext>(m_evmVersion); // We need to keep the same resolver during the whole process. NameAndTypeResolver resolver(*m_globalContext, m_evmVersion, m_errorReporter, experimentalSolidity); for (Source const* source: m_sourceOrder) if (source->ast && !resolver.registerDeclarations(*source->ast)) return false; std::map<std::string, SourceUnit const*> sourceUnitsByName; for (auto& source: m_sources) sourceUnitsByName[source.first] = source.second.ast.get(); for (Source const* source: m_sourceOrder) if (source->ast && !resolver.performImports(*source->ast, sourceUnitsByName)) return false; resolver.warnHomonymDeclarations(); { DocStringTagParser docStringTagParser(m_errorReporter); for (Source const* source: m_sourceOrder) if (source->ast && !docStringTagParser.parseDocStrings(*source->ast)) noErrors = false; } // Requires DocStringTagParser for (Source const* source: m_sourceOrder) if (source->ast && !resolver.resolveNamesAndTypes(*source->ast)) return false; if (experimentalSolidity) { if (!analyzeExperimental()) noErrors = false; } else if (!analyzeLegacy(noErrors)) noErrors = false; } catch (FatalError const& error) { solAssert(m_errorReporter.hasErrors(), "Unreported fatal error: "s + error.what()); noErrors = false; } catch (UnimplementedFeatureError const& _error) { reportUnimplementedFeatureError(_error); noErrors = false; } if (!noErrors) return false; m_stackState = AnalysisSuccessful; return true; } bool CompilerStack::analyzeLegacy(bool _noErrorsSoFar) { bool noErrors = _noErrorsSoFar; DeclarationTypeChecker declarationTypeChecker(m_errorReporter, m_evmVersion); for (Source const* source: m_sourceOrder) if (source->ast && !declarationTypeChecker.check(*source->ast)) return false; // Requires DeclarationTypeChecker to have run DocStringTagParser docStringTagParser(m_errorReporter); for (Source const* source: m_sourceOrder) if (source->ast && !docStringTagParser.validateDocStringsUsingTypes(*source->ast)) noErrors = false; // Next, we check inheritance, overrides, function collisions and other things at // contract or function level. // This also calculates whether a contract is abstract, which is needed by the // type checker. ContractLevelChecker contractLevelChecker(m_errorReporter); for (Source const* source: m_sourceOrder) if (auto sourceAst = source->ast) noErrors = contractLevelChecker.check(*sourceAst); // Now we run full type checks that go down to the expression level. This // cannot be done earlier, because we need cross-contract types and information // about whether a contract is abstract for the `new` expression. // This populates the `type` annotation for all expressions. // // Note: this does not resolve overloaded functions. In order to do that, types of arguments are needed, // which is only done one step later. TypeChecker typeChecker(m_evmVersion, m_errorReporter); for (Source const* source: m_sourceOrder) if (source->ast && !typeChecker.checkTypeRequirements(*source->ast)) noErrors = false; if (noErrors) { // Requires ContractLevelChecker and TypeChecker DocStringAnalyser docStringAnalyser(m_errorReporter); for (Source const* source: m_sourceOrder) if (source->ast && !docStringAnalyser.analyseDocStrings(*source->ast)) noErrors = false; } if (noErrors) { // Checks that can only be done when all types of all AST nodes are known. PostTypeChecker postTypeChecker(m_errorReporter); for (Source const* source: m_sourceOrder) if (source->ast && !postTypeChecker.check(*source->ast)) noErrors = false; if (!postTypeChecker.finalize()) noErrors = false; } // Create & assign callgraphs and check for contract dependency cycles if (noErrors) { createAndAssignCallGraphs(); annotateInternalFunctionIDs(); findAndReportCyclicContractDependencies(); } if (noErrors) for (Source const* source: m_sourceOrder) if (source->ast && !PostTypeContractLevelChecker{m_errorReporter}.check(*source->ast)) noErrors = false; // Check that immutable variables are never read in c'tors and assigned // exactly once if (noErrors) for (Source const* source: m_sourceOrder) if (source->ast) for (ASTPointer<ASTNode> const& node: source->ast->nodes()) if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get())) ImmutableValidator(m_errorReporter, *contract).analyze(); if (noErrors) { // Control flow graph generator and analyzer. It can check for issues such as // variable is used before it is assigned to. CFG cfg(m_errorReporter); for (Source const* source: m_sourceOrder) if (source->ast && !cfg.constructFlow(*source->ast)) noErrors = false; if (noErrors) { ControlFlowRevertPruner pruner(cfg); pruner.run(); ControlFlowAnalyzer controlFlowAnalyzer(cfg, m_errorReporter); if (!controlFlowAnalyzer.run()) noErrors = false; } } if (noErrors) { // Checks for common mistakes. Only generates warnings. StaticAnalyzer staticAnalyzer(m_errorReporter); for (Source const* source: m_sourceOrder) if (source->ast && !staticAnalyzer.analyze(*source->ast)) noErrors = false; } if (noErrors) { // Check for state mutability in every function. std::vector<ASTPointer<ASTNode>> ast; for (Source const* source: m_sourceOrder) if (source->ast) ast.push_back(source->ast); if (!ViewPureChecker(ast, m_errorReporter).check()) noErrors = false; } if (noErrors) { // Run SMTChecker auto allSources = util::applyMap(m_sourceOrder, [](Source const* _source) { return _source->ast; }); if (ModelChecker::isPragmaPresent(allSources)) m_modelCheckerSettings.engine = ModelCheckerEngine::All(); // m_modelCheckerSettings is spread to engines and solver interfaces, // so we need to check whether the enabled ones are available before building the classes. if (m_modelCheckerSettings.engine.any()) m_modelCheckerSettings.solvers = ModelChecker::checkRequestedSolvers(m_modelCheckerSettings.solvers, m_errorReporter); ModelChecker modelChecker(m_errorReporter, *this, m_smtlib2Responses, m_modelCheckerSettings, m_readFile); modelChecker.checkRequestedSourcesAndContracts(allSources); for (Source const* source: m_sourceOrder) if (source->ast) modelChecker.analyze(*source->ast); m_unhandledSMTLib2Queries += modelChecker.unhandledQueries(); } return noErrors; } bool CompilerStack::analyzeExperimental() { solAssert(!m_experimentalAnalysis); solAssert(m_maxAstId && *m_maxAstId >= 0); m_experimentalAnalysis = std::make_unique<experimental::Analysis>(m_errorReporter, static_cast<std::uint64_t>(*m_maxAstId)); std::vector<std::shared_ptr<SourceUnit const>> sourceAsts; for (Source const* source: m_sourceOrder) if (source->ast) sourceAsts.emplace_back(source->ast); return m_experimentalAnalysis->check(sourceAsts); } bool CompilerStack::parseAndAnalyze(State _stopAfter) { m_stopAfter = _stopAfter; bool success = parse(); if (m_stackState >= m_stopAfter) return success; if (success) success = analyze(); return success; } bool CompilerStack::isRequestedSource(std::string const& _sourceName) const { return m_selectedContracts.empty() || m_selectedContracts.count("") || m_selectedContracts.count(_sourceName); } bool CompilerStack::isRequestedContract(ContractDefinition const& _contract) const { /// In case nothing was specified in selectedContracts. if (m_selectedContracts.empty()) return true; for (auto const& key: std::vector<std::string>{"", _contract.sourceUnitName()}) { auto const& it = m_selectedContracts.find(key); if (it != m_selectedContracts.end()) if (it->second.count(_contract.name()) || it->second.count("")) return true; } return false; } CompilerStack::PipelineConfig CompilerStack::requestedPipelineConfig(ContractDefinition const& _contract) const { static PipelineConfig constexpr defaultPipelineConfig = PipelineConfig{ false, // irCodegen false, // irOptimization true, // bytecode }; // If nothing was explicitly selected, all contracts are selected by default. if (m_selectedContracts.empty()) return defaultPipelineConfig; PipelineConfig combinedConfig; for (std::string const& sourceUnitName: {""s, _contract.sourceUnitName()}) if (m_selectedContracts.count(sourceUnitName) != 0) for (std::string const& contractName: {""s, _contract.name()}) if (m_selectedContracts.at(sourceUnitName).count(contractName) != 0) combinedConfig = combinedConfig | m_selectedContracts.at(sourceUnitName).at(contractName); return combinedConfig; } bool CompilerStack::compile(State _stopAfter) { m_stopAfter = _stopAfter; if (m_stackState < AnalysisSuccessful) if (!parseAndAnalyze(_stopAfter)) return false; if (m_stackState >= m_stopAfter) return true; // Only compile contracts individually which have been requested. std::map<ContractDefinition const*, std::shared_ptr<Compiler const>> otherCompilers; for (Source const* source: m_sourceOrder) for (ASTPointer<ASTNode> const& node: source->ast->nodes()) if (auto contract = dynamic_cast<ContractDefinition const*>(node.get())) if (isRequestedContract(*contract)) { PipelineConfig pipelineConfig = requestedPipelineConfig(*contract); try { if (pipelineConfig.needIR(m_viaIR)) generateIR(*contract, pipelineConfig.needIRCodegenOnly(m_viaIR)); if (pipelineConfig.needBytecode()) { if (m_viaIR) generateEVMFromIR(*contract); else { if (m_experimentalAnalysis) solThrow(CompilerError, "Legacy codegen after experimental analysis is unsupported."); compileContract(*contract, otherCompilers); } } } catch (Error const& _error) { // Since codegen has no access to the error reporter, the only way for it to // report an error is to throw. In most cases it uses dedicated exceptions, // but CodeGenerationError is one case where someone decided to just throw Error. solAssert(_error.type() == Error::Type::CodeGenerationError); m_errorReporter.error(_error.errorId(), _error.type(), SourceLocation(), _error.what()); return false; } catch (UnimplementedFeatureError const& _error) { reportUnimplementedFeatureError(_error); return false; } } m_stackState = CompilationSuccessful; this->link(); return true; } void CompilerStack::link() { solAssert(m_stackState >= CompilationSuccessful, ""); for (auto& contract: m_contracts) { contract.second.object.link(m_libraries); contract.second.runtimeObject.link(m_libraries); } } YulStack CompilerStack::loadGeneratedIR(std::string const& _ir) const { YulStack stack( m_evmVersion, m_eofVersion, YulStack::Language::StrictAssembly, m_optimiserSettings, m_debugInfoSelection, this, // _soliditySourceProvider m_objectOptimizer ); bool yulAnalysisSuccessful = stack.parseAndAnalyze("", _ir); solAssert( yulAnalysisSuccessful, _ir + "\n\n" "Invalid IR generated:\n" + SourceReferenceFormatter::formatErrorInformation(stack.errors(), stack) + "\n" ); return stack; } std::vector<std::string> CompilerStack::contractNames() const { solAssert(m_stackState >= Parsed, "Parsing was not successful."); std::vector<std::string> contractNames; for (auto const& contract: m_contracts) contractNames.push_back(contract.first); return contractNames; } std::string const CompilerStack::lastContractName(std::optional<std::string> const& _sourceName) const { solAssert(m_stackState >= AnalysisSuccessful, "Parsing was not successful."); // try to find some user-supplied contract std::string contractName; for (auto const& it: m_sources) if (_sourceName.value_or(it.first) == it.first) for (auto const* contract: ASTNode::filteredNodes<ContractDefinition>(it.second.ast->nodes())) contractName = contract->fullyQualifiedName(); return contractName; } evmasm::AssemblyItems const* CompilerStack::assemblyItems(std::string const& _contractName) const { solAssert(m_stackState == CompilationSuccessful, "Compilation was not successful."); Contract const& currentContract = contract(_contractName); if (!currentContract.evmAssembly) return nullptr; solUnimplementedAssert(!m_eofVersion.has_value(), "EVM assembly output not implemented for EOF yet."); solAssert(currentContract.evmAssembly->codeSections().size() == 1, "Expected a single code section in legacy codegen."); return &currentContract.evmAssembly->codeSections().front().items; } evmasm::AssemblyItems const* CompilerStack::runtimeAssemblyItems(std::string const& _contractName) const { solAssert(m_stackState == CompilationSuccessful, "Compilation was not successful."); Contract const& currentContract = contract(_contractName); if (!currentContract.evmRuntimeAssembly) return nullptr; solUnimplementedAssert(!m_eofVersion.has_value(), "EVM assembly output not implemented for EOF yet."); solAssert(currentContract.evmRuntimeAssembly->codeSections().size() == 1, "Expected a single code section in legacy codegen."); return &currentContract.evmRuntimeAssembly->codeSections().front().items; } Json CompilerStack::generatedSources(std::string const& _contractName, bool _runtime) const { solAssert(m_stackState == CompilationSuccessful, "Compilation was not successful."); Contract const& c = contract(_contractName); Json sources = Json::array(); // If there is no compiler, then no bytecode was generated and thus no // sources were generated (or we compiled "via IR"). if (c.runtimeGeneratedYulUtilityCode.has_value()) { solAssert(c.generatedYulUtilityCode.has_value() == c.runtimeGeneratedYulUtilityCode.has_value()); solAssert(!m_viaIR); std::string source = _runtime ? *c.runtimeGeneratedYulUtilityCode : *c.generatedYulUtilityCode; if (!source.empty()) { std::string sourceName = CompilerContext::yulUtilityFileName(); unsigned sourceIndex = sourceIndices()[sourceName]; ErrorList errors; ErrorReporter errorReporter(errors); CharStream charStream(source, sourceName); yul::EVMDialect const& dialect = yul::EVMDialect::strictAssemblyForEVM(m_evmVersion, m_eofVersion); std::shared_ptr<yul::AST> parserResult = yul::Parser{errorReporter, dialect}.parse(charStream); solAssert(parserResult); sources[0]["ast"] = yul::AsmJsonConverter{dialect, sourceIndex}(parserResult->root()); sources[0]["name"] = sourceName; sources[0]["id"] = sourceIndex; sources[0]["language"] = "Yul"; sources[0]["contents"] = std::move(source); } } return sources; } std::string const* CompilerStack::sourceMapping(std::string const& _contractName) const { solAssert(m_stackState == CompilationSuccessful, "Compilation was not successful."); // TODO if (m_eofVersion.has_value()) return nullptr; Contract const& c = contract(_contractName); if (!c.sourceMapping) { if (auto items = assemblyItems(_contractName)) c.sourceMapping.emplace(evmasm::AssemblyItem::computeSourceMapping(*items, sourceIndices())); } return c.sourceMapping ? &*c.sourceMapping : nullptr; } std::string const* CompilerStack::runtimeSourceMapping(std::string const& _contractName) const { solAssert(m_stackState == CompilationSuccessful, "Compilation was not successful."); // TODO if (m_eofVersion.has_value()) return nullptr; Contract const& c = contract(_contractName); if (!c.runtimeSourceMapping) { if (auto items = runtimeAssemblyItems(_contractName)) c.runtimeSourceMapping.emplace( evmasm::AssemblyItem::computeSourceMapping(*items, sourceIndices()) ); } return c.runtimeSourceMapping ? &*c.runtimeSourceMapping : nullptr; } std::string const CompilerStack::filesystemFriendlyName(std::string const& _contractName) const { solAssert(m_stackState >= AnalysisSuccessful, "No compiled contracts found."); // Look up the contract (by its fully-qualified name) Contract const& matchContract = m_contracts.at(_contractName); // Check to see if it could collide on name for (auto const& contract: m_contracts) { if (contract.second.contract->name() == matchContract.contract->name() && contract.second.contract != matchContract.contract) { // If it does, then return its fully-qualified name, made fs-friendly std::string friendlyName = boost::algorithm::replace_all_copy(_contractName, "/", "_"); boost::algorithm::replace_all(friendlyName, ":", "_"); boost::algorithm::replace_all(friendlyName, ".", "_"); return friendlyName; } } // If no collision, return the contract's name return matchContract.contract->name(); } std::optional<std::string> const& CompilerStack::yulIR(std::string const& _contractName) const { solAssert(m_stackState == CompilationSuccessful, "Compilation was not successful."); return contract(_contractName).yulIR; } std::optional<Json> CompilerStack::yulIRAst(std::string const& _contractName) const { solAssert(m_stackState == CompilationSuccessful, "Compilation was not successful."); solUnimplementedAssert(!isExperimentalSolidity()); // NOTE: Intentionally not using LazyInit. The artifact can get very large and we don't want to // keep it around when compiling a large project containing many contracts. Contract const& currentContract = contract(_contractName); yulAssert(currentContract.contract); yulAssert(currentContract.yulIR.has_value() == currentContract.contract->canBeDeployed()); if (!currentContract.yulIR) return std::nullopt; return loadGeneratedIR(*currentContract.yulIR).astJson(); } std::optional<Json> CompilerStack::yulCFGJson(std::string const& _contractName) const { solAssert(m_stackState == CompilationSuccessful, "Compilation was not successful."); solUnimplementedAssert(!isExperimentalSolidity()); // NOTE: Intentionally not using LazyInit. The artifact can get very large and we don't want to // keep it around when compiling a large project containing many contracts. Contract const& currentContract = contract(_contractName); yulAssert(currentContract.contract); yulAssert(currentContract.yulIR.has_value() == currentContract.contract->canBeDeployed()); if (!currentContract.yulIR) return std::nullopt; return loadGeneratedIR(*currentContract.yulIR).cfgJson(); } std::optional<std::string> const& CompilerStack::yulIROptimized(std::string const& _contractName) const { solAssert(m_stackState == CompilationSuccessful, "Compilation was not successful."); return contract(_contractName).yulIROptimized; } std::optional<Json> CompilerStack::yulIROptimizedAst(std::string const& _contractName) const { solAssert(m_stackState == CompilationSuccessful, "Compilation was not successful."); solUnimplementedAssert(!isExperimentalSolidity()); // NOTE: Intentionally not using LazyInit. The artifact can get very large and we don't want to // keep it around when compiling a large project containing many contracts. Contract const& currentContract = contract(_contractName); yulAssert(currentContract.contract); yulAssert(currentContract.yulIROptimized.has_value() == currentContract.contract->canBeDeployed()); if (!currentContract.yulIROptimized) return std::nullopt; return loadGeneratedIR(*currentContract.yulIROptimized).astJson(); } evmasm::LinkerObject const& CompilerStack::object(std::string const& _contractName) const { solAssert(m_stackState == CompilationSuccessful, "Compilation was not successful."); return contract(_contractName).object; } evmasm::LinkerObject const& CompilerStack::runtimeObject(std::string const& _contractName) const { solAssert(m_stackState == CompilationSuccessful, "Compilation was not successful."); return contract(_contractName).runtimeObject; } /// TODO: cache this string std::string CompilerStack::assemblyString(std::string const& _contractName, StringMap const& _sourceCodes) const { solAssert(m_stackState == CompilationSuccessful, "Compilation was not successful."); Contract const& currentContract = contract(_contractName); if (currentContract.evmAssembly) return currentContract.evmAssembly->assemblyString(m_debugInfoSelection, _sourceCodes); else return std::string(); } /// TODO: cache the JSON Json CompilerStack::assemblyJSON(std::string const& _contractName) const { solAssert(m_stackState == CompilationSuccessful, "Compilation was not successful."); solUnimplementedAssert(!isExperimentalSolidity()); Contract const& currentContract = contract(_contractName); if (currentContract.evmAssembly) return currentContract.evmAssembly->assemblyJSON(sourceIndices()); else return Json(); } std::vector<std::string> CompilerStack::sourceNames() const { return ranges::to<std::vector>(m_sources | ranges::views::keys); } std::map<std::string, unsigned> CompilerStack::sourceIndices() const { std::map<std::string, unsigned> indices; unsigned index = 0; for (auto const& s: m_sources) indices[s.first] = index++; solAssert(!indices.count(CompilerContext::yulUtilityFileName()), ""); indices[CompilerContext::yulUtilityFileName()] = index++; return indices; } Json const& CompilerStack::contractABI(std::string const& _contractName) const { solAssert(m_stackState >= AnalysisSuccessful, "Analysis was not successful."); return contractABI(contract(_contractName)); } Json const& CompilerStack::contractABI(Contract const& _contract) const { solAssert(m_stackState >= AnalysisSuccessful, "Analysis was not successful."); solAssert(_contract.contract); solUnimplementedAssert(!isExperimentalSolidity()); return _contract.abi.init([&]{ return ABI::generate(*_contract.contract); }); } Json const& CompilerStack::storageLayout(std::string const& _contractName) const { solAssert(m_stackState >= AnalysisSuccessful, "Analysis was not successful."); return storageLayout(contract(_contractName)); } Json const& CompilerStack::storageLayout(Contract const& _contract) const { solAssert(m_stackState >= AnalysisSuccessful, "Analysis was not successful."); solAssert(_contract.contract); solUnimplementedAssert(!isExperimentalSolidity()); return _contract.storageLayout.init([&]{ return StorageLayout().generate(*_contract.contract, DataLocation::Storage); }); } Json const& CompilerStack::transientStorageLayout(std::string const& _contractName) const { solAssert(m_stackState >= AnalysisSuccessful, "Analysis was not successful."); return transientStorageLayout(contract(_contractName)); } Json const& CompilerStack::transientStorageLayout(Contract const& _contract) const { solAssert(m_stackState >= AnalysisSuccessful, "Analysis was not successful."); solAssert(_contract.contract); solUnimplementedAssert(!isExperimentalSolidity()); return _contract.transientStorageLayout.init([&]{ return StorageLayout().generate(*_contract.contract, DataLocation::Transient); }); } Json const& CompilerStack::natspecUser(std::string const& _contractName) const { solAssert(m_stackState >= AnalysisSuccessful, "Analysis was not successful."); return natspecUser(contract(_contractName)); } Json const& CompilerStack::natspecUser(Contract const& _contract) const { solAssert(m_stackState >= AnalysisSuccessful, "Analysis was not successful."); solAssert(_contract.contract); solUnimplementedAssert(!isExperimentalSolidity()); return _contract.userDocumentation.init([&]{ return Natspec::userDocumentation(*_contract.contract); }); } Json const& CompilerStack::natspecDev(std::string const& _contractName) const { solAssert(m_stackState >= AnalysisSuccessful, "Analysis was not successful."); return natspecDev(contract(_contractName)); } Json const& CompilerStack::natspecDev(Contract const& _contract) const { solAssert(m_stackState >= AnalysisSuccessful, "Analysis was not successful."); solAssert(_contract.contract); solUnimplementedAssert(!isExperimentalSolidity()); return _contract.devDocumentation.init([&]{ return Natspec::devDocumentation(*_contract.contract); }); } Json CompilerStack::interfaceSymbols(std::string const& _contractName) const { solAssert(m_stackState >= AnalysisSuccessful, "Analysis was not successful."); solUnimplementedAssert(!isExperimentalSolidity()); Json interfaceSymbols; // Always have a methods object interfaceSymbols["methods"] = Json::object(); for (auto const& it: contractDefinition(_contractName).interfaceFunctions()) interfaceSymbols["methods"][it.second->externalSignature()] = it.first.hex(); for (ErrorDefinition const* error: contractDefinition(_contractName).interfaceErrors()) { std::string signature = error->functionType(true)->externalSignature(); interfaceSymbols["errors"][signature] = util::toHex(toCompactBigEndian(util::selectorFromSignatureU32(signature), 4)); } for (EventDefinition const* event: ranges::concat_view( contractDefinition(_contractName).definedInterfaceEvents(), contractDefinition(_contractName).usedInterfaceEvents() )) if (!event->isAnonymous()) { std::string signature = event->functionType(true)->externalSignature(); interfaceSymbols["events"][signature] = toHex(u256(h256::Arith(util::keccak256(signature)))); } return interfaceSymbols; } bytes CompilerStack::cborMetadata(std::string const& _contractName, bool _forIR) const { solAssert(m_stackState >= AnalysisSuccessful, "Analysis was not successful."); return createCBORMetadata(contract(_contractName), _forIR); } std::string const& CompilerStack::metadata(Contract const& _contract) const { solAssert(m_stackState >= AnalysisSuccessful, "Analysis was not successful."); solAssert(_contract.contract); solUnimplementedAssert(!isExperimentalSolidity()); return _contract.metadata.init([&]{ return createMetadata(_contract, m_viaIR); }); } CharStream const& CompilerStack::charStream(std::string const& _sourceName) const { solAssert(m_stackState >= SourcesSet, "No sources set."); solAssert(source(_sourceName).charStream); return *source(_sourceName).charStream; } SourceUnit const& CompilerStack::ast(std::string const& _sourceName) const { solAssert(m_stackState >= Parsed, "Parsing not yet performed."); solAssert(source(_sourceName).ast, "Parsing was not successful."); solUnimplementedAssert(!isExperimentalSolidity()); return *source(_sourceName).ast; } ContractDefinition const& CompilerStack::contractDefinition(std::string const& _contractName) const { solAssert(m_stackState >= AnalysisSuccessful, "Analysis was not successful."); return *contract(_contractName).contract; } size_t CompilerStack::functionEntryPoint( std::string const& _contractName, FunctionDefinition const& _function ) const { solAssert(m_stackState == CompilationSuccessful, "Compilation was not successful."); for (auto&& [name, data]: contract(_contractName).runtimeObject.functionDebugData) if (data.sourceID == _function.id()) if (data.instructionIndex) return *data.instructionIndex; return 0; } h256 const& CompilerStack::Source::keccak256() const { if (keccak256HashCached == h256{}) keccak256HashCached = util::keccak256(charStream->source()); return keccak256HashCached; } h256 const& CompilerStack::Source::swarmHash() const { if (swarmHashCached == h256{}) swarmHashCached = util::bzzr1Hash(charStream->source()); return swarmHashCached; } std::string const& CompilerStack::Source::ipfsUrl() const { if (ipfsUrlCached.empty()) ipfsUrlCached = "dweb:/ipfs/" + util::ipfsHashBase58(charStream->source()); return ipfsUrlCached; } StringMap CompilerStack::loadMissingSources(SourceUnit const& _ast) { solAssert(m_stackState < ParsedAndImported, ""); StringMap newSources; try { for (auto const& node: _ast.nodes()) if (ImportDirective const* import = dynamic_cast<ImportDirective*>(node.get())) { std::string const& importPath = *import->annotation().absolutePath; if (m_sources.count(importPath) || newSources.count(importPath)) continue; ReadCallback::Result result{false, std::string("File not supplied initially.")}; if (m_readFile) result = m_readFile(ReadCallback::kindString(ReadCallback::Kind::ReadFile), importPath); if (result.success) newSources[importPath] = result.responseOrErrorMessage; else { m_errorReporter.parserError( 6275_error, import->location(), std::string("Source \"" + importPath + "\" not found: " + result.responseOrErrorMessage) ); continue; } } } catch (FatalError const& error) { solAssert(m_errorReporter.hasErrors(), "Unreported fatal error: "s + error.what()); } return newSources; } std::string CompilerStack::applyRemapping(std::string const& _path, std::string const& _context) { solAssert(m_stackState < ParsedAndImported, ""); return m_importRemapper.apply(_path, _context); } bool CompilerStack::resolveImports() { solAssert(m_stackState == ParsedAndImported, ""); // topological sorting (depth first search) of the import graph, cutting potential cycles std::vector<Source const*> sourceOrder; std::set<Source const*> sourcesSeen; std::function<void(Source const*)> toposort = [&](Source const* _source) { if (sourcesSeen.count(_source)) return; sourcesSeen.insert(_source); solAssert(_source->ast); for (ASTPointer<ASTNode> const& node: _source->ast->nodes()) if (ImportDirective const* import = dynamic_cast<ImportDirective*>(node.get())) { std::string const& path = *import->annotation().absolutePath; solAssert(m_sources.count(path), ""); import->annotation().sourceUnit = m_sources[path].ast.get(); toposort(&m_sources[path]); } sourceOrder.push_back(_source); }; std::vector<PragmaDirective const*> experimentalPragmaDirectives; for (auto const& sourcePair: m_sources) { if (isRequestedSource(sourcePair.first)) toposort(&sourcePair.second); if (sourcePair.second.ast && sourcePair.second.ast->experimentalSolidity()) for (ASTPointer<ASTNode> const& node: sourcePair.second.ast->nodes()) if (PragmaDirective const* pragma = dynamic_cast<PragmaDirective*>(node.get())) if (pragma->literals().size() >=2 && pragma->literals()[0] == "experimental" && pragma->literals()[1] == "solidity") { experimentalPragmaDirectives.push_back(pragma); break; } } if (!experimentalPragmaDirectives.empty() && experimentalPragmaDirectives.size() != m_sources.size()) { for (auto &&pragma: experimentalPragmaDirectives) m_errorReporter.parserError( 2141_error, pragma->location(), "File declares \"pragma experimental solidity\". If you want to enable the experimental mode, all source units must include the pragma." ); return false; } swap(m_sourceOrder, sourceOrder); return true; } void CompilerStack::storeContractDefinitions() { for (auto const& pair: m_sources) if (pair.second.ast) for ( ContractDefinition const* contract: ASTNode::filteredNodes<ContractDefinition>(pair.second.ast->nodes()) ) { std::string fullyQualifiedName = *pair.second.ast->annotation().path + ":" + contract->name(); // Note that we now reference contracts by their fully qualified names, and // thus contracts can only conflict if declared in the same source file. This // should already cause a double-declaration error elsewhere. if (!m_contracts.count(fullyQualifiedName)) m_contracts[fullyQualifiedName].contract = contract; } } void CompilerStack::annotateInternalFunctionIDs() { for (Source const* source: m_sourceOrder) { if (!source->ast) continue; for (ContractDefinition const* contract: ASTNode::filteredNodes<ContractDefinition>(source->ast->nodes())) { uint64_t internalFunctionID = 1; ContractDefinitionAnnotation& annotation = contract->annotation(); if (auto const* deployTimeInternalDispatch = util::valueOrNullptr((*annotation.deployedCallGraph)->edges, CallGraph::SpecialNode::InternalDispatch)) for (auto const& node: *deployTimeInternalDispatch) if (auto const* callable = std::get_if<CallableDeclaration const*>(&node)) if (auto const* function = dynamic_cast<FunctionDefinition const*>(*callable)) { solAssert(contract->annotation().internalFunctionIDs.count(function) == 0); contract->annotation().internalFunctionIDs[function] = internalFunctionID++; } if (auto const* creationTimeInternalDispatch = util::valueOrNullptr((*annotation.creationCallGraph)->edges, CallGraph::SpecialNode::InternalDispatch)) for (auto const& node: *creationTimeInternalDispatch) if (auto const* callable = std::get_if<CallableDeclaration const*>(&node)) if (auto const* function = dynamic_cast<FunctionDefinition const*>(*callable)) // Make sure the function already got an ID since it also occurs in the deploy-time internal dispatch. solAssert(contract->annotation().internalFunctionIDs.count(function) != 0); } } } namespace { bool onlySafeExperimentalFeaturesActivated(std::set<ExperimentalFeature> const& features) { for (auto const feature: features) if (!ExperimentalFeatureWithoutWarning.count(feature)) return false; return true; } } void CompilerStack::assembleYul( ContractDefinition const& _contract, std::shared_ptr<evmasm::Assembly> _assembly, std::shared_ptr<evmasm::Assembly> _runtimeAssembly ) { solAssert(m_stackState >= AnalysisSuccessful, ""); Contract& compiledContract = m_contracts.at(_contract.fullyQualifiedName()); compiledContract.evmAssembly = _assembly; solAssert(compiledContract.evmAssembly, ""); try { // Assemble deployment (incl. runtime) object. compiledContract.object = compiledContract.evmAssembly->assemble(); } catch (evmasm::AssemblyException const& error) { solAssert(false, "Assembly exception for bytecode: "s + error.what()); } solAssert(compiledContract.object.immutableReferences.empty(), "Leftover immutables."); compiledContract.evmRuntimeAssembly = _runtimeAssembly; solAssert(compiledContract.evmRuntimeAssembly, ""); try { // Assemble runtime object. compiledContract.runtimeObject = compiledContract.evmRuntimeAssembly->assemble(); } catch (evmasm::AssemblyException const& error) { solAssert(false, "Assembly exception for deployed bytecode"s + error.what()); } // Throw a warning if EIP-170 limits are exceeded: // If contract creation returns data with length greater than 0x6000 (2^14 + 2^13) bytes, // contract creation fails with an out of gas error. if ( m_evmVersion >= langutil::EVMVersion::spuriousDragon() && compiledContract.runtimeObject.bytecode.size() > 0x6000 ) m_errorReporter.warning( 5574_error, _contract.location(), "Contract code size is "s + std::to_string(compiledContract.runtimeObject.bytecode.size()) + " bytes and exceeds 24576 bytes (a limit introduced in Spurious Dragon). " "This contract may not be deployable on Mainnet. " "Consider enabling the optimizer (with a low \"runs\" value!), " "turning off revert strings, or using libraries." ); // Throw a warning if EIP-3860 limits are exceeded: // If initcode is larger than 0xC000 bytes (twice the runtime code limit), // then contract creation fails with an out of gas error. if ( m_evmVersion >= langutil::EVMVersion::shanghai() && compiledContract.object.bytecode.size() > 0xC000 ) m_errorReporter.warning( 3860_error, _contract.location(), "Contract initcode size is "s + std::to_string(compiledContract.object.bytecode.size()) + " bytes and exceeds 49152 bytes (a limit introduced in Shanghai). " "This contract may not be deployable on Mainnet. " "Consider enabling the optimizer (with a low \"runs\" value!), " "turning off revert strings, or using libraries." ); } void CompilerStack::compileContract( ContractDefinition const& _contract, std::map<ContractDefinition const*, std::shared_ptr<Compiler const>>& _otherCompilers ) { solAssert(!m_viaIR, ""); solUnimplementedAssert(!m_eofVersion.has_value(), "Experimental EOF support is only available for via-IR compilation."); solAssert(m_stackState >= AnalysisSuccessful, ""); if (_otherCompilers.count(&_contract)) return; for (auto const& [dependency, referencee]: _contract.annotation().contractDependencies) compileContract(*dependency, _otherCompilers); if (!_contract.canBeDeployed()) return; Contract& compiledContract = m_contracts.at(_contract.fullyQualifiedName()); std::shared_ptr<Compiler> compiler = std::make_shared<Compiler>(m_evmVersion, m_revertStrings, m_optimiserSettings); solAssert(!m_viaIR, ""); bytes cborEncodedMetadata = createCBORMetadata(compiledContract, /* _forIR */ false); // Run optimiser and compile the contract. compiler->compileContract(_contract, _otherCompilers, cborEncodedMetadata); compiledContract.generatedYulUtilityCode = compiler->generatedYulUtilityCode(); compiledContract.runtimeGeneratedYulUtilityCode = compiler->runtimeGeneratedYulUtilityCode(); _otherCompilers[compiledContract.contract] = compiler; assembleYul(_contract, compiler->assemblyPtr(), compiler->runtimeAssemblyPtr()); } void CompilerStack::generateIR(ContractDefinition const& _contract, bool _unoptimizedOnly) { solAssert(m_stackState >= AnalysisSuccessful, ""); Contract& compiledContract = m_contracts.at(_contract.fullyQualifiedName()); if (compiledContract.yulIR) { solAssert(!compiledContract.yulIR->empty()); return; } if (!*_contract.sourceUnit().annotation().useABICoderV2) m_errorReporter.warning( 2066_error, _contract.location(), "Contract requests the ABI coder v1, which is incompatible with the IR. " "Using ABI coder v2 instead." ); std::string dependenciesSource; for (auto const& [dependency, referencee]: _contract.annotation().contractDependencies) generateIR(*dependency, _unoptimizedOnly); if (!_contract.canBeDeployed()) return; std::map<ContractDefinition const*, std::string_view const> otherYulSources; for (auto const& pair: m_contracts) otherYulSources.emplace(pair.second.contract, pair.second.yulIR ? *pair.second.yulIR : std::string_view{}); if (m_experimentalAnalysis) { experimental::IRGenerator generator( m_evmVersion, m_eofVersion, m_revertStrings, sourceIndices(), m_debugInfoSelection, this, *m_experimentalAnalysis ); compiledContract.yulIR = generator.run( _contract, {}, // TODO: createCBORMetadata(compiledContract, /* _forIR */ true), otherYulSources ); } else { IRGenerator generator( m_evmVersion, m_eofVersion, m_revertStrings, sourceIndices(), m_debugInfoSelection, this, m_optimiserSettings ); compiledContract.yulIR = generator.run( _contract, createCBORMetadata(compiledContract, /* _forIR */ true), otherYulSources ); } yulAssert(compiledContract.yulIR); YulStack stack = loadGeneratedIR(*compiledContract.yulIR); if (!_unoptimizedOnly) { stack.optimize(); compiledContract.yulIROptimized = stack.print(); } } void CompilerStack::generateEVMFromIR(ContractDefinition const& _contract) { solAssert(m_stackState >= AnalysisSuccessful, ""); if (!_contract.canBeDeployed()) return; Contract& compiledContract = m_contracts.at(_contract.fullyQualifiedName()); solAssert(compiledContract.yulIROptimized); solAssert(!compiledContract.yulIROptimized->empty()); if (!compiledContract.object.bytecode.empty()) return; // Re-parse the Yul IR in EVM dialect YulStack stack = loadGeneratedIR(*compiledContract.yulIROptimized); std::string deployedName = IRNames::deployedObject(_contract); solAssert(!deployedName.empty(), ""); tie(compiledContract.evmAssembly, compiledContract.evmRuntimeAssembly) = stack.assembleEVMWithDeployed(deployedName); assembleYul(_contract, compiledContract.evmAssembly, compiledContract.evmRuntimeAssembly); } CompilerStack::Contract const& CompilerStack::contract(std::string const& _contractName) const { solAssert(m_stackState >= AnalysisSuccessful, ""); auto it = m_contracts.find(_contractName); if (it != m_contracts.end()) return it->second; // To provide a measure of backward-compatibility, if a contract is not located by its // fully-qualified name, a lookup will be attempted purely on the contract's name to see // if anything will satisfy. if (_contractName.find(':') == std::string::npos) { for (auto const& contractEntry: m_contracts) { std::stringstream ss; ss.str(contractEntry.first); // All entries are <source>:<contract> std::string source; std::string foundName; getline(ss, source, ':'); getline(ss, foundName, ':'); if (foundName == _contractName) return contractEntry.second; } } // If we get here, both lookup methods failed. solAssert(false, "Contract \"" + _contractName + "\" not found."); } CompilerStack::Source const& CompilerStack::source(std::string const& _sourceName) const { auto it = m_sources.find(_sourceName); solAssert(it != m_sources.end(), "Given source file not found: " + _sourceName); return it->second; } std::string CompilerStack::createMetadata(Contract const& _contract, bool _forIR) const { Json meta; meta["version"] = 1; std::string sourceType; switch (m_compilationSourceType) { case CompilationSourceType::Solidity: sourceType = "Solidity"; break; case CompilationSourceType::SolidityAST: sourceType = "SolidityAST"; break; } meta["language"] = sourceType; meta["compiler"]["version"] = VersionStringStrict; /// All the source files (including self), which should be included in the metadata. std::set<std::string> referencedSources; referencedSources.insert(*_contract.contract->sourceUnit().annotation().path); for (auto const sourceUnit: _contract.contract->sourceUnit().referencedSourceUnits(true)) referencedSources.insert(*sourceUnit->annotation().path); meta["sources"] = Json::object(); for (auto const& s: m_sources) { if (!referencedSources.count(s.first)) continue; solAssert(s.second.charStream, "Character stream not available"); meta["sources"][s.first]["keccak256"] = "0x" + util::toHex(s.second.keccak256().asBytes()); if (std::optional<std::string> licenseString = s.second.ast->licenseString()) meta["sources"][s.first]["license"] = *licenseString; if (m_metadataLiteralSources) meta["sources"][s.first]["content"] = s.second.charStream->source(); else { meta["sources"][s.first]["urls"] = Json::array(); meta["sources"][s.first]["urls"].emplace_back("bzz-raw://" + util::toHex(s.second.swarmHash().asBytes())); meta["sources"][s.first]["urls"].emplace_back(s.second.ipfsUrl()); } } static_assert(sizeof(m_optimiserSettings.expectedExecutionsPerDeployment) <= sizeof(Json::number_integer_t), "Invalid word size."); solAssert(static_cast<Json::number_integer_t>(m_optimiserSettings.expectedExecutionsPerDeployment) < std::numeric_limits<Json::number_integer_t>::max(), ""); meta["settings"]["optimizer"]["runs"] = Json::number_integer_t(m_optimiserSettings.expectedExecutionsPerDeployment); /// Backwards compatibility: If set to one of the default settings, do not provide details. OptimiserSettings settingsWithoutRuns = m_optimiserSettings; // reset to default settingsWithoutRuns.expectedExecutionsPerDeployment = OptimiserSettings::minimal().expectedExecutionsPerDeployment; if (settingsWithoutRuns == OptimiserSettings::minimal()) meta["settings"]["optimizer"]["enabled"] = false; else if (settingsWithoutRuns == OptimiserSettings::standard()) meta["settings"]["optimizer"]["enabled"] = true; else { Json details = Json::object(); details["orderLiterals"] = m_optimiserSettings.runOrderLiterals; details["inliner"] = m_optimiserSettings.runInliner; details["jumpdestRemover"] = m_optimiserSettings.runJumpdestRemover; details["peephole"] = m_optimiserSettings.runPeephole; details["deduplicate"] = m_optimiserSettings.runDeduplicate; details["cse"] = m_optimiserSettings.runCSE; details["constantOptimizer"] = m_optimiserSettings.runConstantOptimiser; details["simpleCounterForLoopUncheckedIncrement"] = m_optimiserSettings.simpleCounterForLoopUncheckedIncrement; details["yul"] = m_optimiserSettings.runYulOptimiser; if (m_optimiserSettings.runYulOptimiser) { details["yulDetails"] = Json::object(); details["yulDetails"]["stackAllocation"] = m_optimiserSettings.optimizeStackAllocation; details["yulDetails"]["optimizerSteps"] = m_optimiserSettings.yulOptimiserSteps + ":" + m_optimiserSettings.yulOptimiserCleanupSteps; } else if (OptimiserSuite::isEmptyOptimizerSequence(m_optimiserSettings.yulOptimiserSteps + ":" + m_optimiserSettings.yulOptimiserCleanupSteps)) { solAssert(m_optimiserSettings.optimizeStackAllocation == false); details["yulDetails"] = Json::object(); details["yulDetails"]["optimizerSteps"] = ":"; } else { solAssert(m_optimiserSettings.optimizeStackAllocation == false); solAssert(m_optimiserSettings.yulOptimiserSteps == OptimiserSettings::DefaultYulOptimiserSteps); solAssert(m_optimiserSettings.yulOptimiserCleanupSteps == OptimiserSettings::DefaultYulOptimiserCleanupSteps); } meta["settings"]["optimizer"]["details"] = std::move(details); } if (m_revertStrings != RevertStrings::Default) meta["settings"]["debug"]["revertStrings"] = revertStringsToString(m_revertStrings); if (m_metadataFormat == MetadataFormat::NoMetadata) meta["settings"]["metadata"]["appendCBOR"] = false; if (m_metadataLiteralSources) meta["settings"]["metadata"]["useLiteralContent"] = true; static std::vector<std::string> hashes{"ipfs", "bzzr1", "none"}; meta["settings"]["metadata"]["bytecodeHash"] = hashes.at(unsigned(m_metadataHash)); if (_forIR) meta["settings"]["viaIR"] = _forIR; meta["settings"]["evmVersion"] = m_evmVersion.name(); if (m_eofVersion.has_value()) meta["settings"]["eofVersion"] = *m_eofVersion; meta["settings"]["compilationTarget"][_contract.contract->sourceUnitName()] = *_contract.contract->annotation().canonicalName; meta["settings"]["remappings"] = Json::array(); std::set<std::string> remappings; for (auto const& r: m_importRemapper.remappings()) remappings.insert(r.context + ":" + r.prefix + "=" + r.target); for (auto const& r: remappings) meta["settings"]["remappings"].emplace_back(r); meta["settings"]["libraries"] = Json::object(); for (auto const& library: m_libraries) meta["settings"]["libraries"][library.first] = "0x" + util::toHex(library.second.asBytes()); meta["output"]["abi"] = contractABI(_contract); meta["output"]["userdoc"] = natspecUser(_contract); meta["output"]["devdoc"] = natspecDev(_contract); return util::jsonCompactPrint(meta); } class MetadataCBOREncoder { public: void pushBytes(std::string const& key, bytes const& value) { m_entryCount++; pushTextString(key); pushByteString(value); } void pushString(std::string const& key, std::string const& value) { m_entryCount++; pushTextString(key); pushTextString(value); } void pushBool(std::string const& key, bool value) { m_entryCount++; pushTextString(key); pushBool(value); } bytes serialise() const { size_t size = m_data.size() + 1; solAssert(size <= 0xffff, "Metadata too large."); solAssert(m_entryCount <= 0x1f, "Too many map entries."); // CBOR fixed-length map bytes ret{static_cast<unsigned char>(0xa0 + m_entryCount)}; // The already encoded key-value pairs ret += m_data; // 16-bit big endian length ret += toCompactBigEndian(size, 2); return ret; } private: void pushTextString(std::string const& key) { size_t length = key.size(); if (length < 24) { m_data += bytes{static_cast<unsigned char>(0x60 + length)}; m_data += key; } else if (length <= 256) { m_data += bytes{0x78, static_cast<unsigned char>(length)}; m_data += key; } else solAssert(false, "Text std::string too large."); } void pushByteString(bytes const& key) { size_t length = key.size(); if (length < 24) { m_data += bytes{static_cast<unsigned char>(0x40 + length)}; m_data += key; } else if (length <= 256) { m_data += bytes{0x58, static_cast<unsigned char>(length)}; m_data += key; } else solAssert(false, "Byte std::string too large."); } void pushBool(bool value) { if (value) m_data += bytes{0xf5}; else m_data += bytes{0xf4}; } unsigned m_entryCount = 0; bytes m_data; }; bytes CompilerStack::createCBORMetadata(Contract const& _contract, bool _forIR) const { if (m_metadataFormat == MetadataFormat::NoMetadata) return bytes{}; bool const experimentalMode = !onlySafeExperimentalFeaturesActivated( _contract.contract->sourceUnit().annotation().experimentalFeatures ); std::string meta = (_forIR == m_viaIR ? metadata(_contract) : createMetadata(_contract, _forIR)); MetadataCBOREncoder encoder; if (m_metadataHash == MetadataHash::IPFS) encoder.pushBytes("ipfs", util::ipfsHash(meta)); else if (m_metadataHash == MetadataHash::Bzzr1) encoder.pushBytes("bzzr1", util::bzzr1Hash(meta).asBytes()); else solAssert(m_metadataHash == MetadataHash::None, "Invalid metadata hash"); if (experimentalMode || m_eofVersion.has_value()) encoder.pushBool("experimental", true); if (m_metadataFormat == MetadataFormat::WithReleaseVersionTag) encoder.pushBytes("solc", VersionCompactBytes); else { solAssert( m_metadataFormat == MetadataFormat::WithPrereleaseVersionTag, "Invalid metadata format." ); encoder.pushString("solc", VersionStringStrict); } return encoder.serialise(); } namespace { Json gasToJson(GasEstimator::GasConsumption const& _gas) { if (_gas.isInfinite) return Json("infinite"); else return Json(util::toString(_gas.value)); } } Json CompilerStack::gasEstimates(std::string const& _contractName) const { solAssert(m_stackState == CompilationSuccessful, "Compilation was not successful."); solUnimplementedAssert(!isExperimentalSolidity()); if (!assemblyItems(_contractName) && !runtimeAssemblyItems(_contractName)) return Json(); using Gas = GasEstimator::GasConsumption; GasEstimator gasEstimator(m_evmVersion); Json output = Json::object(); if (evmasm::AssemblyItems const* items = assemblyItems(_contractName)) { Gas executionGas = gasEstimator.functionalEstimation(*items); Gas codeDepositGas{evmasm::GasMeter::dataGas(runtimeObject(_contractName).bytecode, false, m_evmVersion)}; Json creation = Json::object(); creation["codeDepositCost"] = gasToJson(codeDepositGas); creation["executionCost"] = gasToJson(executionGas); /// TODO: implement + overload to avoid the need of += executionGas += codeDepositGas; creation["totalCost"] = gasToJson(executionGas); output["creation"] = creation; } if (evmasm::AssemblyItems const* items = runtimeAssemblyItems(_contractName)) { /// External functions ContractDefinition const& contract = contractDefinition(_contractName); Json externalFunctions = Json::object(); for (auto it: contract.interfaceFunctions()) { std::string sig = it.second->externalSignature(); externalFunctions[sig] = gasToJson(gasEstimator.functionalEstimation(*items, sig)); } if (contract.fallbackFunction()) /// This needs to be set to an invalid signature in order to trigger the fallback, /// without the shortcut (of CALLDATSIZE == 0), and therefore to receive the upper bound. /// An empty string ("") would work to trigger the shortcut only. externalFunctions[""] = gasToJson(gasEstimator.functionalEstimation(*items, "INVALID")); if (!externalFunctions.empty()) output["external"] = externalFunctions; /// Internal functions Json internalFunctions = Json::object(); for (auto const& it: contract.definedFunctions()) { /// Exclude externally visible functions, constructor, fallback and receive ether function if (it->isPartOfExternalInterface() || !it->isOrdinary()) continue; size_t entry = functionEntryPoint(_contractName, *it); GasEstimator::GasConsumption gas = GasEstimator::GasConsumption::infinite(); if (entry > 0) gas = gasEstimator.functionalEstimation(*items, entry, *it); /// TODO: This could move into a method shared with externalSignature() FunctionType type(*it); std::string sig = it->name() + "("; auto paramTypes = type.parameterTypes(); for (auto it = paramTypes.begin(); it != paramTypes.end(); ++it) sig += (*it)->toString() + (it + 1 == paramTypes.end() ? "" : ","); sig += ")"; internalFunctions[sig] = gasToJson(gas); } if (!internalFunctions.empty()) output["internal"] = internalFunctions; } return output; } bool CompilerStack::isExperimentalSolidity() const { return !m_sourceOrder.empty() && ranges::all_of(m_sourceOrder, [](auto const* _source) { return _source->ast->experimentalSolidity(); } ) ; } experimental::Analysis const& CompilerStack::experimentalAnalysis() const { solAssert(!!m_experimentalAnalysis); return *m_experimentalAnalysis; } void CompilerStack::reportUnimplementedFeatureError(UnimplementedFeatureError const& _error) { solAssert(_error.comment(), "Unimplemented feature errors must include a message for the user"); m_errorReporter.unimplementedFeatureError(1834_error, _error.sourceLocation(), *_error.comment()); }
68,807
C++
.cpp
1,722
37.154472
158
0.76134
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,233
GasEstimator.cpp
ethereum_solidity/libsolidity/interface/GasEstimator.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 /** * @author Christian <c@ethdev.com> * @date 2015 * Gas consumption estimator working alongside the AST. */ #include <libsolidity/interface/GasEstimator.h> #include <libsolidity/ast/AST.h> #include <libsolidity/ast/ASTVisitor.h> #include <libsolidity/codegen/CompilerUtils.h> #include <libevmasm/ControlFlowGraph.h> #include <libevmasm/KnownState.h> #include <libevmasm/PathGasMeter.h> #include <libsolutil/FunctionSelector.h> #include <libsolutil/Keccak256.h> #include <functional> #include <map> #include <memory> using namespace solidity; using namespace solidity::evmasm; using namespace solidity::frontend; using namespace solidity::langutil; GasEstimator::GasConsumption GasEstimator::functionalEstimation( AssemblyItems const& _items, std::string const& _signature ) const { auto state = std::make_shared<KnownState>(); if (!_signature.empty()) { ExpressionClasses& classes = state->expressionClasses(); using Id = ExpressionClasses::Id; using Ids = std::vector<Id>; Id hashValue = classes.find(u256(util::selectorFromSignatureU32(_signature))); Id calldata = classes.find(Instruction::CALLDATALOAD, Ids{classes.find(u256(0))}); if (!m_evmVersion.hasBitwiseShifting()) // div(calldataload(0), 1 << 224) equals to hashValue classes.forceEqual( hashValue, Instruction::DIV, Ids{calldata, classes.find(u256(1) << 224)} ); else // shr(0xe0, calldataload(0)) equals to hashValue classes.forceEqual( hashValue, Instruction::SHR, Ids{classes.find(u256(0xe0)), calldata} ); // lt(calldatasize(), 4) equals to 0 (ignore the shortcut for fallback functions) classes.forceEqual( classes.find(u256(0)), Instruction::LT, Ids{classes.find(Instruction::CALLDATASIZE), classes.find(u256(4))} ); } return PathGasMeter::estimateMax(_items, m_evmVersion, 0, state); } GasEstimator::GasConsumption GasEstimator::functionalEstimation( AssemblyItems const& _items, size_t const& _offset, FunctionDefinition const& _function ) const { auto state = std::make_shared<KnownState>(); unsigned parametersSize = CompilerUtils::sizeOnStack(_function.parameters()); if (parametersSize > 16) return GasConsumption::infinite(); // Store an invalid return value on the stack, so that the path estimator breaks upon reaching // the return jump. AssemblyItem invalidTag(PushTag, u256(-0x10)); state->feedItem(invalidTag, true); if (parametersSize > 0) state->feedItem(swapInstruction(parametersSize)); return PathGasMeter::estimateMax(_items, m_evmVersion, _offset, state); } std::set<ASTNode const*> GasEstimator::finestNodesAtLocation( std::vector<ASTNode const*> const& _roots ) { std::map<SourceLocation, ASTNode const*> locations; std::set<ASTNode const*> nodes; SimpleASTVisitor visitor(std::function<bool(ASTNode const&)>(), [&](ASTNode const& _n) { if (!locations.count(_n.location())) { locations[_n.location()] = &_n; nodes.insert(&_n); } }); for (ASTNode const* root: _roots) root->accept(visitor); return nodes; }
3,718
C++
.cpp
107
32.364486
95
0.760712
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
3,234
Natspec.cpp
ethereum_solidity/libsolidity/interface/Natspec.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 /** * @author Lefteris <lefteris@ethdev.com> * @date 2014 * Takes the parsed AST and produces the Natspec documentation: * https://github.com/ethereum/wiki/wiki/Ethereum-Natural-Specification-Format * * Can generally deal with JSON files */ #include <libsolidity/interface/Natspec.h> #include <libsolidity/ast/AST.h> #include <boost/algorithm/string.hpp> using namespace solidity; using namespace solidity::frontend; Json Natspec::userDocumentation(ContractDefinition const& _contractDef) { Json doc; doc["version"] = Json(c_natspecVersion); doc["kind"] = Json("user"); doc["methods"] = Json::object(); auto constructorDefinition(_contractDef.constructor()); if (constructorDefinition) { std::string const value = extractDoc(constructorDefinition->annotation().docTags, "notice"); if (!value.empty()) { // add the constructor, only if we have any documentation to add Json user; user["notice"] = Json(value); doc["methods"]["constructor"] = user; } } std::string notice = extractDoc(_contractDef.annotation().docTags, "notice"); if (!notice.empty()) doc["notice"] = Json(notice); for (auto const& it: _contractDef.interfaceFunctions()) if (it.second->hasDeclaration()) { std::string value; if (auto const* f = dynamic_cast<FunctionDefinition const*>(&it.second->declaration())) value = extractDoc(f->annotation().docTags, "notice"); else if (auto var = dynamic_cast<VariableDeclaration const*>(&it.second->declaration())) { solAssert(var->isStateVariable() && var->isPublic(), ""); value = extractDoc(var->annotation().docTags, "notice"); } if (!value.empty()) // since @notice is the only user tag if missing function should not appear doc["methods"][it.second->externalSignature()]["notice"] = value; } for (auto const& event: uniqueInterfaceEvents(_contractDef)) { std::string value = extractDoc(event->annotation().docTags, "notice"); if (!value.empty()) doc["events"][event->functionType(true)->externalSignature()]["notice"] = value; } for (auto const& error: _contractDef.interfaceErrors()) { std::string value = extractDoc(error->annotation().docTags, "notice"); if (!value.empty()) { Json errorDoc; errorDoc["notice"] = value; doc["errors"][error->functionType(true)->externalSignature()].emplace_back(std::move(errorDoc)); } } return doc; } Json Natspec::devDocumentation(ContractDefinition const& _contractDef) { Json doc = extractCustomDoc(_contractDef.annotation().docTags); doc["version"] = Json(c_natspecVersion); doc["kind"] = Json("dev"); auto author = extractDoc(_contractDef.annotation().docTags, "author"); if (!author.empty()) doc["author"] = author; auto title = extractDoc(_contractDef.annotation().docTags, "title"); if (!title.empty()) doc["title"] = title; auto dev = extractDoc(_contractDef.annotation().docTags, "dev"); if (!dev.empty()) doc["details"] = Json(dev); doc["methods"] = Json::object(); auto constructorDefinition(_contractDef.constructor()); if (constructorDefinition) { Json constructor(devDocumentation(constructorDefinition->annotation().docTags)); if (!constructor.empty()) // add the constructor, only if we have any documentation to add doc["methods"]["constructor"] = constructor; } for (auto const& it: _contractDef.interfaceFunctions()) { if (!it.second->hasDeclaration()) continue; if (auto fun = dynamic_cast<FunctionDefinition const*>(&it.second->declaration())) { Json method(devDocumentation(fun->annotation().docTags)); // add the function, only if we have any documentation to add Json jsonReturn = extractReturnParameterDocs( fun->annotation().docTags, fun->functionType(false)->returnParameterNames() ); if (!jsonReturn.empty()) method["returns"] = std::move(jsonReturn); if (!method.empty()) doc["methods"][it.second->externalSignature()] = std::move(method); } } for (VariableDeclaration const* varDecl: _contractDef.stateVariables()) { if (auto devDoc = devDocumentation(varDecl->annotation().docTags); !devDoc.empty()) doc["stateVariables"][varDecl->name()] = devDoc; auto const assignIfNotEmpty = [&](std::string const& _name, Json const& _content) { if (!_content.empty()) doc["stateVariables"][varDecl->name()][_name] = _content; }; if (varDecl->annotation().docTags.count("return") == 1) assignIfNotEmpty("return", extractDoc(varDecl->annotation().docTags, "return")); if (FunctionTypePointer functionType = varDecl->functionType(false)) assignIfNotEmpty("returns", extractReturnParameterDocs( varDecl->annotation().docTags, functionType->returnParameterNames() )); } for (auto const& event: uniqueInterfaceEvents(_contractDef)) if (auto devDoc = devDocumentation(event->annotation().docTags); !devDoc.empty()) doc["events"][event->functionType(true)->externalSignature()] = devDoc; for (auto const& error: _contractDef.interfaceErrors()) if (auto devDoc = devDocumentation(error->annotation().docTags); !devDoc.empty()) doc["errors"][error->functionType(true)->externalSignature()].emplace_back(devDoc); return doc; } Json Natspec::extractReturnParameterDocs(std::multimap<std::string, DocTag> const& _tags, std::vector<std::string> const& _returnParameterNames) { Json jsonReturn; auto returnDocs = _tags.equal_range("return"); if (!_returnParameterNames.empty()) { size_t n = 0; for (auto i = returnDocs.first; i != returnDocs.second; i++) { std::string paramName = _returnParameterNames.at(n); std::string content = i->second.content; if (paramName.empty()) paramName = "_" + std::to_string(n); else { //check to make sure the first word of the doc str is the same as the return name auto nameEndPos = content.find_first_of(" \t"); solAssert(content.substr(0, nameEndPos) == paramName, "No return param name given: " + paramName); content = content.substr(nameEndPos+1); } jsonReturn[paramName] = Json(content); n++; } } return jsonReturn; } std::string Natspec::extractDoc(std::multimap<std::string, DocTag> const& _tags, std::string const& _name) { std::string value; auto range = _tags.equal_range(_name); for (auto i = range.first; i != range.second; i++) value += i->second.content; return value; } Json Natspec::extractCustomDoc(std::multimap<std::string, DocTag> const& _tags) { std::map<std::string, std::string> concatenated; for (auto const& [tag, value]: _tags) if (boost::starts_with(tag, "custom")) concatenated[tag] += value.content; // We do not want to create an object if there are no custom tags found. if (concatenated.empty()) return Json(); Json result; for (auto& [tag, value]: concatenated) result[tag] = std::move(value); return result; } Json Natspec::devDocumentation(std::multimap<std::string, DocTag> const& _tags) { Json json = extractCustomDoc(_tags); auto dev = extractDoc(_tags, "dev"); if (!dev.empty()) json["details"] = Json(dev); auto author = extractDoc(_tags, "author"); if (!author.empty()) json["author"] = author; Json params; auto paramRange = _tags.equal_range("param"); for (auto i = paramRange.first; i != paramRange.second; ++i) params[i->second.paramName] = Json(i->second.content); if (!params.empty()) json["params"] = params; return json; } std::vector<EventDefinition const*> Natspec::uniqueInterfaceEvents(ContractDefinition const& _contract) { auto eventSignature = [](EventDefinition const* _event) -> std::string { FunctionType const* functionType = _event->functionType(true); solAssert(functionType, ""); return functionType->externalSignature(); }; auto compareBySignature = [&](EventDefinition const* _lhs, EventDefinition const* _rhs) -> bool { return eventSignature(_lhs) < eventSignature(_rhs); }; std::set<EventDefinition const*, decltype(compareBySignature)> uniqueEvents{compareBySignature}; // Insert events defined in the contract first so that in case of a conflict // they're the ones that get selected. uniqueEvents += _contract.definedInterfaceEvents(); std::set<EventDefinition const*, decltype(compareBySignature)> filteredUsedEvents{compareBySignature}; std::set<std::string> usedSignatures; for (EventDefinition const* event: _contract.usedInterfaceEvents()) { auto&& [eventIt, eventInserted] = filteredUsedEvents.insert(event); auto&& [signatureIt, signatureInserted] = usedSignatures.insert(eventSignature(event)); if (!signatureInserted) filteredUsedEvents.erase(eventIt); } uniqueEvents += filteredUsedEvents; return util::convertContainer<std::vector<EventDefinition const*>>(std::move(uniqueEvents)); }
9,369
C++
.cpp
239
36.364017
144
0.728314
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
3,236
StandardCompiler.cpp
ethereum_solidity/libsolidity/interface/StandardCompiler.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 /** * @author Alex Beregszaszi * @date 2016 * Standard JSON compiler interface. */ #include <libsolidity/interface/StandardCompiler.h> #include <libsolidity/interface/ImportRemapper.h> #include <libsolidity/ast/ASTJsonExporter.h> #include <libyul/YulStack.h> #include <libyul/Exceptions.h> #include <libyul/optimiser/Suite.h> #include <libevmasm/Disassemble.h> #include <libevmasm/EVMAssemblyStack.h> #include <libsmtutil/Exceptions.h> #include <liblangutil/SourceReferenceFormatter.h> #include <libsolutil/JSON.h> #include <libsolutil/Keccak256.h> #include <libsolutil/CommonData.h> #include <boost/algorithm/string/predicate.hpp> #include <algorithm> #include <optional> using namespace solidity; using namespace solidity::yul; using namespace solidity::frontend; using namespace solidity::langutil; using namespace solidity::util; using namespace std::string_literals; namespace { Json formatError( Error::Type _type, std::string const& _component, std::string const& _message, std::string const& _formattedMessage = "", Json const& _sourceLocation = Json(), Json const& _secondarySourceLocation = Json() ) { Json error; error["type"] = Error::formatErrorType(_type); error["component"] = _component; error["severity"] = Error::formatErrorSeverityLowercase(Error::errorSeverity(_type)); error["message"] = _message; error["formattedMessage"] = (_formattedMessage.length() > 0) ? _formattedMessage : _message; if (_sourceLocation.is_object()) error["sourceLocation"] = _sourceLocation; if (_secondarySourceLocation.is_array()) error["secondarySourceLocations"] = _secondarySourceLocation; return error; } Json formatFatalError(Error::Type _type, std::string const& _message) { Json output; output["errors"] = Json::array(); output["errors"].emplace_back(formatError(_type, "general", _message)); return output; } Json formatSourceLocation(SourceLocation const* location) { if (!location || !location->sourceName) return Json(); Json sourceLocation; sourceLocation["file"] = *location->sourceName; sourceLocation["start"] = location->start; sourceLocation["end"] = location->end; return sourceLocation; } Json formatSecondarySourceLocation(SecondarySourceLocation const* _secondaryLocation) { if (!_secondaryLocation) return Json(); Json secondarySourceLocation = Json::array(); for (auto const& location: _secondaryLocation->infos) { Json msg = formatSourceLocation(&location.second); msg["message"] = location.first; secondarySourceLocation.emplace_back(msg); } return secondarySourceLocation; } Json formatErrorWithException( CharStreamProvider const& _charStreamProvider, util::Exception const& _exception, Error::Type _type, std::string const& _component, std::string const& _message, std::optional<ErrorId> _errorId = std::nullopt ) { std::string message; // TODO: consider enabling color std::string formattedMessage = SourceReferenceFormatter::formatExceptionInformation( _exception, _type, _charStreamProvider, false // colored ); if (std::string const* description = _exception.comment()) message = ((_message.length() > 0) ? (_message + ":") : "") + *description; else message = _message; Json error = formatError( _type, _component, message, formattedMessage, formatSourceLocation(boost::get_error_info<errinfo_sourceLocation>(_exception)), formatSecondarySourceLocation(boost::get_error_info<errinfo_secondarySourceLocation>(_exception)) ); if (_errorId) error["errorCode"] = std::to_string(_errorId.value().error); return error; } /// Returns true iff @a _hash (hex with 0x prefix) is the Keccak256 hash of the binary data in @a _content. bool hashMatchesContent(std::string const& _hash, std::string const& _content) { try { return util::h256(_hash) == util::keccak256(_content); } catch (util::BadHexCharacter const&) { return false; } } bool isArtifactRequested(Json const& _outputSelection, std::string const& _artifact, bool _wildcardMatchesExperimental) { static std::set<std::string> experimental{"ir", "irAst", "irOptimized", "irOptimizedAst", "yulCFGJson"}; for (auto const& selectedArtifactJson: _outputSelection) { std::string const& selectedArtifact = selectedArtifactJson.get<std::string>(); if ( _artifact == selectedArtifact || boost::algorithm::starts_with(_artifact, selectedArtifact + ".") ) return true; else if (selectedArtifact == "*") { // TODO: yulCFGJson is only experimental now, so it should not be matched by "*". if (_artifact == "yulCFGJson") return false; // "ir", "irOptimized" can only be matched by "*" if activated. if (experimental.count(_artifact) == 0 || _wildcardMatchesExperimental) return true; } } return false; } /// /// @a _outputSelection is a JSON object containing a two-level hashmap, where the first level is the filename, /// the second level is the contract name and the value is an array of artifact names to be requested for that contract. /// @a _file is the current file /// @a _contract is the current contract /// @a _artifact is the current artifact name /// /// @returns true if the @a _outputSelection has a match for the requested target in the specific file / contract. /// /// In @a _outputSelection the use of '*' as a wildcard is permitted. /// /// @TODO optimise this. Perhaps flatten the structure upfront. /// bool isArtifactRequested(Json const& _outputSelection, std::string const& _file, std::string const& _contract, std::string const& _artifact, bool _wildcardMatchesExperimental) { if (!_outputSelection.is_object()) return false; for (auto const& file: { _file, std::string("*") }) if (_outputSelection.contains(file) && _outputSelection[file].is_object()) { /// For SourceUnit-level targets (such as AST) only allow empty name, otherwise /// for Contract-level targets try both contract name and wildcard std::vector<std::string> contracts{ _contract }; if (!_contract.empty()) contracts.emplace_back("*"); for (auto const& contract: contracts) if ( _outputSelection[file].contains(contract) && _outputSelection[file][contract].is_array() && isArtifactRequested(_outputSelection[file][contract], _artifact, _wildcardMatchesExperimental) ) return true; } return false; } bool isArtifactRequested(Json const& _outputSelection, std::string const& _file, std::string const& _contract, std::vector<std::string> const& _artifacts, bool _wildcardMatchesExperimental) { for (auto const& artifact: _artifacts) if (isArtifactRequested(_outputSelection, _file, _contract, artifact, _wildcardMatchesExperimental)) return true; return false; } /// @returns all artifact names of the EVM object, either for creation or deploy time. std::vector<std::string> evmObjectComponents(std::string const& _objectKind) { solAssert(_objectKind == "bytecode" || _objectKind == "deployedBytecode", ""); std::vector<std::string> components{"", ".object", ".opcodes", ".sourceMap", ".functionDebugData", ".generatedSources", ".linkReferences"}; if (_objectKind == "deployedBytecode") components.push_back(".immutableReferences"); return util::applyMap(components, [&](auto const& _s) { return "evm." + _objectKind + _s; }); } /// @returns true if any binary was requested, i.e. we actually have to perform compilation. bool isBinaryRequested(Json const& _outputSelection) { if (!_outputSelection.is_object()) return false; // This does not include "evm.methodIdentifiers" on purpose! static std::vector<std::string> const outputsThatRequireBinaries = std::vector<std::string>{ "*", "ir", "irAst", "irOptimized", "irOptimizedAst", "yulCFGJson", "evm.gasEstimates", "evm.legacyAssembly", "evm.assembly" } + evmObjectComponents("bytecode") + evmObjectComponents("deployedBytecode"); for (auto const& fileRequests: _outputSelection) for (auto const& requests: fileRequests) for (auto const& output: outputsThatRequireBinaries) if (isArtifactRequested(requests, output, false)) return true; return false; } /// @returns true if EVM bytecode was requested, i.e. we have to run the old code generator. bool isEvmBytecodeRequested(Json const& _outputSelection) { if (!_outputSelection.is_object()) return false; static std::vector<std::string> const outputsThatRequireEvmBinaries = std::vector<std::string>{ "*", "evm.gasEstimates", "evm.legacyAssembly", "evm.assembly" } + evmObjectComponents("bytecode") + evmObjectComponents("deployedBytecode"); for (auto const& fileRequests: _outputSelection) for (auto const& requests: fileRequests) for (auto const& output: outputsThatRequireEvmBinaries) if (isArtifactRequested(requests, output, false)) return true; return false; } /// @returns The set of selected contracts, along with their compiler pipeline configuration, based /// on outputs requested in the JSON. Translates wildcards to the ones understood by CompilerStack. /// Note that as an exception, '*' does not yet match "ir", "irAst", "irOptimized" or "irOptimizedAst". CompilerStack::ContractSelection pipelineConfig( Json const& _jsonOutputSelection ) { if (!_jsonOutputSelection.is_object()) return {}; CompilerStack::ContractSelection contractSelection; for (auto const& [sourceUnitName, jsonOutputSelectionForSource]: _jsonOutputSelection.items()) { solAssert(jsonOutputSelectionForSource.is_object()); for (auto const& [contractName, jsonOutputSelectionForContract]: jsonOutputSelectionForSource.items()) { solAssert(jsonOutputSelectionForContract.is_array()); CompilerStack::PipelineConfig pipelineForContract; for (Json const& request: jsonOutputSelectionForContract) { solAssert(request.is_string()); pipelineForContract.irOptimization = pipelineForContract.irOptimization || request == "irOptimized" || request == "irOptimizedAst" || request == "yulCFGJson"; pipelineForContract.irCodegen = pipelineForContract.irCodegen || pipelineForContract.irOptimization || request == "ir" || request == "irAst"; pipelineForContract.bytecode = isEvmBytecodeRequested(_jsonOutputSelection); } std::string key = (sourceUnitName == "*") ? "" : sourceUnitName; std::string value = (contractName == "*") ? "" : contractName; contractSelection[key][value] = pipelineForContract; } } return contractSelection; } Json formatLinkReferences(std::map<size_t, std::string> const& linkReferences) { Json ret = Json::object(); for (auto const& ref: linkReferences) { std::string const& fullname = ref.second; // If the link reference does not contain a colon, assume that the file name is missing and // the whole string represents the library name. size_t colon = fullname.rfind(':'); std::string file = (colon != std::string::npos ? fullname.substr(0, colon) : ""); std::string name = (colon != std::string::npos ? fullname.substr(colon + 1) : fullname); Json fileObject = ret.value(file, Json::object()); Json libraryArray = fileObject.value(name, Json::array()); Json entry; entry["start"] = Json(ref.first); entry["length"] = 20; libraryArray.emplace_back(entry); fileObject[name] = libraryArray; ret[file] = fileObject; } return ret; } Json formatImmutableReferences(std::map<u256, evmasm::LinkerObject::ImmutableRefs> const& _immutableReferences) { Json ret = Json::object(); for (auto const& immutableReference: _immutableReferences) { auto const& [identifier, byteOffsets] = immutableReference.second; Json array = Json::array(); for (size_t byteOffset: byteOffsets) { Json byteRange; byteRange["start"] = Json::number_unsigned_t(byteOffset); byteRange["length"] = Json::number_unsigned_t(32); // immutable references are currently always 32 bytes wide array.emplace_back(byteRange); } ret[identifier] = array; } return ret; } Json collectEVMObject( langutil::EVMVersion _evmVersion, evmasm::LinkerObject const& _object, std::string const* _sourceMap, Json _generatedSources, bool _runtimeObject, std::function<bool(std::string)> const& _artifactRequested ) { Json output; if (_artifactRequested("object")) output["object"] = _object.toHex(); if (_artifactRequested("opcodes")) output["opcodes"] = evmasm::disassemble(_object.bytecode, _evmVersion); if (_artifactRequested("sourceMap")) output["sourceMap"] = _sourceMap ? *_sourceMap : ""; if (_artifactRequested("functionDebugData")) output["functionDebugData"] = StandardCompiler::formatFunctionDebugData(_object.functionDebugData); if (_artifactRequested("linkReferences")) output["linkReferences"] = formatLinkReferences(_object.linkReferences); if (_runtimeObject && _artifactRequested("immutableReferences")) output["immutableReferences"] = formatImmutableReferences(_object.immutableReferences); if (_artifactRequested("generatedSources")) output["generatedSources"] = std::move(_generatedSources); return output; } std::optional<Json> checkKeys(Json const& _input, std::set<std::string> const& _keys, std::string const& _name) { if (!_input.empty() && !_input.is_object()) return formatFatalError(Error::Type::JSONError, "\"" + _name + "\" must be an object"); for (auto const& [member, _]: _input.items()) if (!_keys.count(member)) return formatFatalError(Error::Type::JSONError, "Unknown key \"" + member + "\""); return std::nullopt; } std::optional<Json> checkRootKeys(Json const& _input) { static std::set<std::string> keys{"auxiliaryInput", "language", "settings", "sources"}; return checkKeys(_input, keys, "root"); } std::optional<Json> checkSourceKeys(Json const& _input, std::string const& _name) { static std::set<std::string> keys{"content", "keccak256", "urls"}; return checkKeys(_input, keys, "sources." + _name); } std::optional<Json> checkAuxiliaryInputKeys(Json const& _input) { static std::set<std::string> keys{"smtlib2responses"}; return checkKeys(_input, keys, "auxiliaryInput"); } std::optional<Json> checkSettingsKeys(Json const& _input) { static std::set<std::string> keys{"debug", "evmVersion", "eofVersion", "libraries", "metadata", "modelChecker", "optimizer", "outputSelection", "remappings", "stopAfter", "viaIR"}; return checkKeys(_input, keys, "settings"); } std::optional<Json> checkModelCheckerSettingsKeys(Json const& _input) { static std::set<std::string> keys{"bmcLoopIterations", "contracts", "divModNoSlacks", "engine", "extCalls", "invariants", "printQuery", "showProvedSafe", "showUnproved", "showUnsupported", "solvers", "targets", "timeout"}; return checkKeys(_input, keys, "modelChecker"); } std::optional<Json> checkOptimizerKeys(Json const& _input) { static std::set<std::string> keys{"details", "enabled", "runs"}; return checkKeys(_input, keys, "settings.optimizer"); } std::optional<Json> checkOptimizerDetailsKeys(Json const& _input) { static std::set<std::string> keys{"peephole", "inliner", "jumpdestRemover", "orderLiterals", "deduplicate", "cse", "constantOptimizer", "yul", "yulDetails", "simpleCounterForLoopUncheckedIncrement"}; return checkKeys(_input, keys, "settings.optimizer.details"); } std::optional<Json> checkOptimizerDetail(Json const& _details, std::string const& _name, bool& _setting) { if (_details.contains(_name)) { if (!_details[_name].is_boolean()) return formatFatalError(Error::Type::JSONError, "\"settings.optimizer.details." + _name + "\" must be Boolean"); _setting = _details[_name].get<bool>(); } return {}; } std::optional<Json> checkOptimizerDetailSteps(Json const& _details, std::string const& _name, std::string& _optimiserSetting, std::string& _cleanupSetting, bool _runYulOptimizer) { if (_details.contains(_name)) { if (_details[_name].is_string()) { std::string const fullSequence = _details[_name].get<std::string>(); if (!_runYulOptimizer && !OptimiserSuite::isEmptyOptimizerSequence(fullSequence)) { std::string errorMessage = "If Yul optimizer is disabled, only an empty optimizerSteps sequence is accepted." " Note that the empty optimizer sequence is properly denoted by \":\"."; return formatFatalError(Error::Type::JSONError, errorMessage); } try { yul::OptimiserSuite::validateSequence(_details[_name].get<std::string>()); } catch (yul::OptimizerException const& _exception) { return formatFatalError( Error::Type::JSONError, "Invalid optimizer step sequence in \"settings.optimizer.details." + _name + "\": " + _exception.what() ); } auto const delimiterPos = fullSequence.find(":"); _optimiserSetting = fullSequence.substr(0, delimiterPos); if (delimiterPos != std::string::npos) _cleanupSetting = fullSequence.substr(delimiterPos + 1); else solAssert(_cleanupSetting == OptimiserSettings::DefaultYulOptimiserCleanupSteps); } else return formatFatalError(Error::Type::JSONError, "\"settings.optimizer.details." + _name + "\" must be a string"); } return {}; } std::optional<Json> checkMetadataKeys(Json const& _input) { if (_input.is_object()) { if (_input.contains("appendCBOR") && !_input["appendCBOR"].is_boolean()) return formatFatalError(Error::Type::JSONError, "\"settings.metadata.appendCBOR\" must be Boolean"); if (_input.contains("useLiteralContent") && !_input["useLiteralContent"].is_boolean()) return formatFatalError(Error::Type::JSONError, "\"settings.metadata.useLiteralContent\" must be Boolean"); static std::set<std::string> hashes{"ipfs", "bzzr1", "none"}; if (_input.contains("bytecodeHash") && !hashes.count(_input["bytecodeHash"].get<std::string>())) return formatFatalError(Error::Type::JSONError, "\"settings.metadata.bytecodeHash\" must be \"ipfs\", \"bzzr1\" or \"none\""); } static std::set<std::string> keys{"appendCBOR", "useLiteralContent", "bytecodeHash"}; return checkKeys(_input, keys, "settings.metadata"); } std::optional<Json> checkOutputSelection(Json const& _outputSelection) { if (!_outputSelection.empty() && !_outputSelection.is_object()) return formatFatalError(Error::Type::JSONError, "\"settings.outputSelection\" must be an object"); for (auto const& [sourceName, sourceVal]: _outputSelection.items()) { if (!sourceVal.is_object()) return formatFatalError( Error::Type::JSONError, "\"settings.outputSelection." + sourceName + "\" must be an object" ); for (auto const& [contractName, contractVal]: sourceVal.items()) { if (!contractVal.is_array()) return formatFatalError( Error::Type::JSONError, "\"settings.outputSelection." + sourceName + "." + contractName + "\" must be a string array" ); for (auto const& output: contractVal) if (!output.is_string()) return formatFatalError( Error::Type::JSONError, "\"settings.outputSelection." + sourceName + "." + contractName + "\" must be a string array" ); } } return std::nullopt; } /// Validates the optimizer settings and returns them in a parsed object. /// On error returns the json-formatted error message. std::variant<OptimiserSettings, Json> parseOptimizerSettings(Json const& _jsonInput) { if (auto result = checkOptimizerKeys(_jsonInput)) return *result; OptimiserSettings settings = OptimiserSettings::minimal(); if (_jsonInput.contains("enabled")) { if (!_jsonInput["enabled"].is_boolean()) return formatFatalError(Error::Type::JSONError, "The \"enabled\" setting must be a Boolean."); if (_jsonInput["enabled"].get<bool>()) settings = OptimiserSettings::standard(); } if (_jsonInput.contains("runs")) { if (!_jsonInput["runs"].is_number_unsigned()) return formatFatalError(Error::Type::JSONError, "The \"runs\" setting must be an unsigned number."); settings.expectedExecutionsPerDeployment = _jsonInput["runs"].get<size_t>(); } if (_jsonInput.contains("details")) { Json const& details = _jsonInput["details"]; if (auto result = checkOptimizerDetailsKeys(details)) return *result; if (auto error = checkOptimizerDetail(details, "peephole", settings.runPeephole)) return *error; if (auto error = checkOptimizerDetail(details, "inliner", settings.runInliner)) return *error; if (auto error = checkOptimizerDetail(details, "jumpdestRemover", settings.runJumpdestRemover)) return *error; if (auto error = checkOptimizerDetail(details, "orderLiterals", settings.runOrderLiterals)) return *error; if (auto error = checkOptimizerDetail(details, "deduplicate", settings.runDeduplicate)) return *error; if (auto error = checkOptimizerDetail(details, "cse", settings.runCSE)) return *error; if (auto error = checkOptimizerDetail(details, "constantOptimizer", settings.runConstantOptimiser)) return *error; if (auto error = checkOptimizerDetail(details, "yul", settings.runYulOptimiser)) return *error; if (auto error = checkOptimizerDetail(details, "simpleCounterForLoopUncheckedIncrement", settings.simpleCounterForLoopUncheckedIncrement)) return *error; settings.optimizeStackAllocation = settings.runYulOptimiser; if (details.contains("yulDetails")) { if (!settings.runYulOptimiser) { if (checkKeys(details["yulDetails"], {"optimizerSteps"}, "settings.optimizer.details.yulDetails")) return formatFatalError(Error::Type::JSONError, "Only optimizerSteps can be set in yulDetails when Yul optimizer is disabled."); if (auto error = checkOptimizerDetailSteps(details["yulDetails"], "optimizerSteps", settings.yulOptimiserSteps, settings.yulOptimiserCleanupSteps, settings.runYulOptimiser)) return *error; return {std::move(settings)}; } if (auto result = checkKeys(details["yulDetails"], {"stackAllocation", "optimizerSteps"}, "settings.optimizer.details.yulDetails")) return *result; if (auto error = checkOptimizerDetail(details["yulDetails"], "stackAllocation", settings.optimizeStackAllocation)) return *error; if (auto error = checkOptimizerDetailSteps(details["yulDetails"], "optimizerSteps", settings.yulOptimiserSteps, settings.yulOptimiserCleanupSteps, settings.runYulOptimiser)) return *error; } } return {std::move(settings)}; } } std::variant<StandardCompiler::InputsAndSettings, Json> StandardCompiler::parseInput(Json const& _input) { InputsAndSettings ret; if (!_input.is_object()) return formatFatalError(Error::Type::JSONError, "Input is not a JSON object."); if (auto result = checkRootKeys(_input)) return *result; ret.language = _input.value<std::string>("language", ""); Json const& sources = _input.value<Json>("sources", Json()); if (!sources.is_object() && !sources.is_null()) return formatFatalError(Error::Type::JSONError, "\"sources\" is not a JSON object."); if (sources.empty()) return formatFatalError(Error::Type::JSONError, "No input sources specified."); ret.errors = Json::array(); ret.sources = Json::object(); if (ret.language == "Solidity" || ret.language == "Yul") { for (auto const& [sourceName, sourceValue]: sources.items()) { std::string hash; if (auto result = checkSourceKeys(sourceValue, sourceName)) return *result; if (sourceValue.contains("keccak256") && sourceValue["keccak256"].is_string()) hash = sourceValue["keccak256"].get<std::string>(); if (sourceValue.contains("content") && sourceValue["content"].is_string()) { std::string content = sourceValue["content"].get<std::string>(); if (!hash.empty() && !hashMatchesContent(hash, content)) ret.errors.emplace_back(formatError( Error::Type::IOError, "general", "Mismatch between content and supplied hash for \"" + sourceName + "\"" )); else ret.sources[sourceName] = content; } else if (sourceValue["urls"].is_array()) { if (!m_readFile) return formatFatalError( Error::Type::JSONError, "No import callback supplied, but URL is requested." ); std::vector<std::string> failures; bool found = false; for (auto const& url: sourceValue["urls"]) { if (!url.is_string()) return formatFatalError(Error::Type::JSONError, "URL must be a string."); ReadCallback::Result result = m_readFile(ReadCallback::kindString(ReadCallback::Kind::ReadFile), url.get<std::string>()); if (result.success) { if (!hash.empty() && !hashMatchesContent(hash, result.responseOrErrorMessage)) ret.errors.emplace_back(formatError( Error::Type::IOError, "general", "Mismatch between content and supplied hash for \"" + sourceName + "\" at \"" + url.get<std::string>() + "\"" )); else { ret.sources[sourceName] = result.responseOrErrorMessage; found = true; break; } } else failures.push_back( "Cannot import url (\"" + url.get<std::string>() + "\"): " + result.responseOrErrorMessage ); } for (auto const& failure: failures) { /// If the import succeeded, let mark all the others as warnings, otherwise all of them are errors. ret.errors.emplace_back(formatError( found ? Error::Type::Warning : Error::Type::IOError, "general", failure )); } } else return formatFatalError(Error::Type::JSONError, "Invalid input source specified."); } } else if (ret.language == "SolidityAST") { for (auto const& [sourceName, sourceValue]: sources.items()) ret.sources[sourceName] = util::jsonCompactPrint(sourceValue); } else if (ret.language == "EVMAssembly") { for (auto const& [sourceName, sourceValue]: sources.items()) { solAssert(sources.contains(sourceName)); if ( !sourceValue.contains("assemblyJson") || !sourceValue["assemblyJson"].is_object() || sourceValue.size() != 1 ) return formatFatalError( Error::Type::JSONError, "Invalid input source specified. Expected exactly one object, named 'assemblyJson', inside $.sources." + sourceName ); ret.jsonSources[sourceName] = sourceValue["assemblyJson"]; } if (ret.jsonSources.size() != 1) return formatFatalError( Error::Type::JSONError, "EVMAssembly import only supports exactly one input file." ); } Json const& auxInputs = _input.value("auxiliaryInput", Json::object()); if (auto result = checkAuxiliaryInputKeys(auxInputs)) return *result; if (!auxInputs.empty()) { Json const& smtlib2Responses = auxInputs.value("smtlib2responses", Json::object()); if (!smtlib2Responses.empty()) { if (!smtlib2Responses.is_object()) return formatFatalError(Error::Type::JSONError, "\"auxiliaryInput.smtlib2responses\" must be an object."); for (auto const& [hashString, response]: smtlib2Responses.items()) { util::h256 hash; try { hash = util::h256(hashString); } catch (util::BadHexCharacter const&) { return formatFatalError(Error::Type::JSONError, "Invalid hex encoding of SMTLib2 auxiliary input."); } if (!response.is_string()) return formatFatalError( Error::Type::JSONError, "\"smtlib2Responses." + hashString + "\" must be a string." ); ret.smtLib2Responses[hash] = response.get<std::string>(); } } } Json const& settings = _input.value("settings", Json::object()); if (auto result = checkSettingsKeys(settings)) return *result; if (settings.contains("stopAfter")) { if (!settings["stopAfter"].is_string()) return formatFatalError(Error::Type::JSONError, "\"settings.stopAfter\" must be a string."); if (settings["stopAfter"].get<std::string>() != "parsing") return formatFatalError(Error::Type::JSONError, "Invalid value for \"settings.stopAfter\". Only valid value is \"parsing\"."); ret.stopAfter = CompilerStack::State::Parsed; } if (settings.contains("viaIR")) { if (!settings["viaIR"].is_boolean()) return formatFatalError(Error::Type::JSONError, "\"settings.viaIR\" must be a Boolean."); ret.viaIR = settings["viaIR"].get<bool>(); } if (settings.contains("evmVersion")) { if (!settings["evmVersion"].is_string()) return formatFatalError(Error::Type::JSONError, "evmVersion must be a string."); std::optional<langutil::EVMVersion> version = langutil::EVMVersion::fromString(settings["evmVersion"].get<std::string>()); if (!version) return formatFatalError(Error::Type::JSONError, "Invalid EVM version requested."); if (version < EVMVersion::constantinople()) ret.errors.emplace_back(formatError( Error::Type::Warning, "general", "Support for EVM versions older than constantinople is deprecated and will be removed in the future." )); ret.evmVersion = *version; } if (settings.contains("eofVersion")) { if (!settings["eofVersion"].is_number_unsigned()) return formatFatalError(Error::Type::JSONError, "eofVersion must be an unsigned integer."); auto eofVersion = settings["eofVersion"].get<uint8_t>(); if (eofVersion != 1) return formatFatalError(Error::Type::JSONError, "Invalid EOF version requested."); ret.eofVersion = 1; } if (settings.contains("debug")) { if (auto result = checkKeys(settings["debug"], {"revertStrings", "debugInfo"}, "settings.debug")) return *result; if (settings["debug"].contains("revertStrings")) { if (!settings["debug"]["revertStrings"].is_string()) return formatFatalError(Error::Type::JSONError, "settings.debug.revertStrings must be a string."); std::optional<RevertStrings> revertStrings = revertStringsFromString(settings["debug"]["revertStrings"].get<std::string>()); if (!revertStrings) return formatFatalError(Error::Type::JSONError, "Invalid value for settings.debug.revertStrings."); if (*revertStrings == RevertStrings::VerboseDebug) return formatFatalError( Error::Type::UnimplementedFeatureError, "Only \"default\", \"strip\" and \"debug\" are implemented for settings.debug.revertStrings for now." ); ret.revertStrings = *revertStrings; } if (settings["debug"].contains("debugInfo")) { if (!settings["debug"]["debugInfo"].is_array()) return formatFatalError(Error::Type::JSONError, "settings.debug.debugInfo must be an array."); std::vector<std::string> components; for (Json const& arrayValue: settings["debug"]["debugInfo"]) components.push_back(arrayValue.get<std::string>()); std::optional<DebugInfoSelection> debugInfoSelection = DebugInfoSelection::fromComponents( components, true /* _acceptWildcards */ ); if (!debugInfoSelection.has_value()) return formatFatalError(Error::Type::JSONError, "Invalid value in settings.debug.debugInfo."); if (debugInfoSelection->snippet && !debugInfoSelection->location) return formatFatalError( Error::Type::JSONError, "To use 'snippet' with settings.debug.debugInfo you must select also 'location'." ); ret.debugInfoSelection = debugInfoSelection.value(); } } if (settings.contains("remappings") && !settings["remappings"].is_array()) return formatFatalError(Error::Type::JSONError, "\"settings.remappings\" must be an array of strings."); for (auto const& remapping: settings.value("remappings", Json::object())) { if (!remapping.is_string()) return formatFatalError(Error::Type::JSONError, "\"settings.remappings\" must be an array of strings"); if (auto r = ImportRemapper::parseRemapping(remapping.get<std::string>())) ret.remappings.emplace_back(std::move(*r)); else return formatFatalError(Error::Type::JSONError, "Invalid remapping: \"" + remapping.get<std::string>() + "\""); } if (settings.contains("optimizer")) { auto optimiserSettings = parseOptimizerSettings(settings["optimizer"]); if (std::holds_alternative<Json>(optimiserSettings)) return std::get<Json>(std::move(optimiserSettings)); // was an error else ret.optimiserSettings = std::get<OptimiserSettings>(std::move(optimiserSettings)); } Json const& jsonLibraries = settings.value("libraries", Json::object()); if (!jsonLibraries.is_object()) return formatFatalError(Error::Type::JSONError, "\"libraries\" is not a JSON object."); for (auto const& [sourceName, jsonSourceName]: jsonLibraries.items()) { if (!jsonSourceName.is_object()) return formatFatalError(Error::Type::JSONError, "Library entry is not a JSON object."); for (auto const& [library, libraryValue]: jsonSourceName.items()) { if (!libraryValue.is_string()) return formatFatalError(Error::Type::JSONError, "Library address must be a string."); std::string address = libraryValue.get<std::string>(); if (!boost::starts_with(address, "0x")) return formatFatalError( Error::Type::JSONError, "Library address is not prefixed with \"0x\"." ); if (address.length() != 42) return formatFatalError( Error::Type::JSONError, "Library address is of invalid length." ); try { ret.libraries[sourceName + ":" + library] = util::h160(address); } catch (util::BadHexCharacter const&) { return formatFatalError( Error::Type::JSONError, "Invalid library address (\"" + address + "\") supplied." ); } } } Json const& metadataSettings = settings.value("metadata", Json::object()); if (auto result = checkMetadataKeys(metadataSettings)) return *result; solAssert(CompilerStack::defaultMetadataFormat() != CompilerStack::MetadataFormat::NoMetadata, ""); ret.metadataFormat = metadataSettings.value("appendCBOR", Json(true)) ? CompilerStack::defaultMetadataFormat() : CompilerStack::MetadataFormat::NoMetadata; ret.metadataLiteralSources = metadataSettings.contains("useLiteralContent") && metadataSettings["useLiteralContent"].is_boolean() && metadataSettings["useLiteralContent"].get<bool>(); if (metadataSettings.contains("bytecodeHash")) { auto metadataHash = metadataSettings["bytecodeHash"].get<std::string>(); ret.metadataHash = metadataHash == "ipfs" ? CompilerStack::MetadataHash::IPFS : metadataHash == "bzzr1" ? CompilerStack::MetadataHash::Bzzr1 : CompilerStack::MetadataHash::None; if (ret.metadataFormat == CompilerStack::MetadataFormat::NoMetadata && ret.metadataHash != CompilerStack::MetadataHash::None) return formatFatalError( Error::Type::JSONError, "When the parameter \"appendCBOR\" is set to false, the parameter \"bytecodeHash\" cannot be set to \"" + metadataHash + "\". The parameter \"bytecodeHash\" should either be skipped, or set to \"none\"." ); } Json const& outputSelection = settings.value("outputSelection", Json::object()); if (auto jsonError = checkOutputSelection(outputSelection)) return *jsonError; ret.outputSelection = outputSelection; if (ret.stopAfter != CompilerStack::State::CompilationSuccessful && isBinaryRequested(ret.outputSelection)) return formatFatalError( Error::Type::JSONError, "Requested output selection conflicts with \"settings.stopAfter\"." ); Json const& modelCheckerSettings = settings.value("modelChecker", Json::object()); if (auto result = checkModelCheckerSettingsKeys(modelCheckerSettings)) return *result; if (modelCheckerSettings.contains("contracts")) { auto const& sources = modelCheckerSettings["contracts"]; if (!sources.is_object() && !sources.is_null()) return formatFatalError(Error::Type::JSONError, "settings.modelChecker.contracts is not a JSON object."); std::map<std::string, std::set<std::string>> sourceContracts; for (auto const& [source, contracts]: sources.items()) { if (source.empty()) return formatFatalError(Error::Type::JSONError, "Source name cannot be empty."); if (!contracts.is_array()) return formatFatalError(Error::Type::JSONError, "Source contracts must be an array."); for (auto const& contract: contracts) { if (!contract.is_string()) return formatFatalError(Error::Type::JSONError, "Every contract in settings.modelChecker.contracts must be a string."); if (contract.get<std::string>().empty()) return formatFatalError(Error::Type::JSONError, "Contract name cannot be empty."); sourceContracts[source].insert(contract.get<std::string>()); } if (sourceContracts[source].empty()) return formatFatalError(Error::Type::JSONError, "Source contracts must be a non-empty array."); } ret.modelCheckerSettings.contracts = {std::move(sourceContracts)}; } if (modelCheckerSettings.contains("divModNoSlacks")) { auto const& divModNoSlacks = modelCheckerSettings["divModNoSlacks"]; if (!divModNoSlacks.is_boolean()) return formatFatalError(Error::Type::JSONError, "settings.modelChecker.divModNoSlacks must be a Boolean."); ret.modelCheckerSettings.divModNoSlacks = divModNoSlacks.get<bool>(); } if (modelCheckerSettings.contains("engine")) { if (!modelCheckerSettings["engine"].is_string()) return formatFatalError(Error::Type::JSONError, "settings.modelChecker.engine must be a string."); std::optional<ModelCheckerEngine> engine = ModelCheckerEngine::fromString(modelCheckerSettings["engine"].get<std::string>()); if (!engine) return formatFatalError(Error::Type::JSONError, "Invalid model checker engine requested."); ret.modelCheckerSettings.engine = *engine; } if (modelCheckerSettings.contains("bmcLoopIterations")) { if (!ret.modelCheckerSettings.engine.bmc) return formatFatalError(Error::Type::JSONError, "settings.modelChecker.bmcLoopIterations requires the BMC engine to be enabled."); if (modelCheckerSettings["bmcLoopIterations"].is_number_unsigned()) ret.modelCheckerSettings.bmcLoopIterations = modelCheckerSettings["bmcLoopIterations"].get<unsigned>(); else return formatFatalError(Error::Type::JSONError, "settings.modelChecker.bmcLoopIterations must be an unsigned integer."); } if (modelCheckerSettings.contains("extCalls")) { if (!modelCheckerSettings["extCalls"].is_string()) return formatFatalError(Error::Type::JSONError, "settings.modelChecker.extCalls must be a string."); std::optional<ModelCheckerExtCalls> extCalls = ModelCheckerExtCalls::fromString(modelCheckerSettings["extCalls"].get<std::string>()); if (!extCalls) return formatFatalError(Error::Type::JSONError, "Invalid model checker extCalls requested."); ret.modelCheckerSettings.externalCalls = *extCalls; } if (modelCheckerSettings.contains("invariants")) { auto const& invariantsArray = modelCheckerSettings["invariants"]; if (!invariantsArray.is_array()) return formatFatalError(Error::Type::JSONError, "settings.modelChecker.invariants must be an array."); ModelCheckerInvariants invariants; for (auto const& i: invariantsArray) { if (!i.is_string()) return formatFatalError(Error::Type::JSONError, "Every invariant type in settings.modelChecker.invariants must be a string."); if (!invariants.setFromString(i.get<std::string>())) return formatFatalError(Error::Type::JSONError, "Invalid model checker invariants requested."); } if (invariants.invariants.empty()) return formatFatalError(Error::Type::JSONError, "settings.modelChecker.invariants must be a non-empty array."); ret.modelCheckerSettings.invariants = invariants; } if (modelCheckerSettings.contains("showProvedSafe")) { auto const& showProvedSafe = modelCheckerSettings["showProvedSafe"]; if (!showProvedSafe.is_boolean()) return formatFatalError(Error::Type::JSONError, "settings.modelChecker.showProvedSafe must be a Boolean value."); ret.modelCheckerSettings.showProvedSafe = showProvedSafe.get<bool>(); } if (modelCheckerSettings.contains("showUnproved")) { auto const& showUnproved = modelCheckerSettings["showUnproved"]; if (!showUnproved.is_boolean()) return formatFatalError(Error::Type::JSONError, "settings.modelChecker.showUnproved must be a Boolean value."); ret.modelCheckerSettings.showUnproved = showUnproved.get<bool>(); } if (modelCheckerSettings.contains("showUnsupported")) { auto const& showUnsupported = modelCheckerSettings["showUnsupported"]; if (!showUnsupported.is_boolean()) return formatFatalError(Error::Type::JSONError, "settings.modelChecker.showUnsupported must be a Boolean value."); ret.modelCheckerSettings.showUnsupported = showUnsupported.get<bool>(); } if (modelCheckerSettings.contains("solvers")) { auto const& solversArray = modelCheckerSettings["solvers"]; if (!solversArray.is_array()) return formatFatalError(Error::Type::JSONError, "settings.modelChecker.solvers must be an array."); smtutil::SMTSolverChoice solvers; for (auto const& s: solversArray) { if (!s.is_string()) return formatFatalError(Error::Type::JSONError, "Every target in settings.modelChecker.solvers must be a string."); if (!solvers.setSolver(s.get<std::string>())) return formatFatalError(Error::Type::JSONError, "Invalid model checker solvers requested."); } ret.modelCheckerSettings.solvers = solvers; } if (modelCheckerSettings.contains("printQuery")) { auto const& printQuery = modelCheckerSettings["printQuery"]; if (!printQuery.is_boolean()) return formatFatalError(Error::Type::JSONError, "settings.modelChecker.printQuery must be a Boolean value."); if (!(ret.modelCheckerSettings.solvers == smtutil::SMTSolverChoice::SMTLIB2())) return formatFatalError(Error::Type::JSONError, "Only SMTLib2 solver can be enabled to print queries"); ret.modelCheckerSettings.printQuery = printQuery.get<bool>(); } if (modelCheckerSettings.contains("targets")) { auto const& targetsArray = modelCheckerSettings["targets"]; if (!targetsArray.is_array()) return formatFatalError(Error::Type::JSONError, "settings.modelChecker.targets must be an array."); ModelCheckerTargets targets; for (auto const& t: targetsArray) { if (!t.is_string()) return formatFatalError(Error::Type::JSONError, "Every target in settings.modelChecker.targets must be a string."); if (!targets.setFromString(t.get<std::string>())) return formatFatalError(Error::Type::JSONError, "Invalid model checker targets requested."); } if (targets.targets.empty()) return formatFatalError(Error::Type::JSONError, "settings.modelChecker.targets must be a non-empty array."); ret.modelCheckerSettings.targets = targets; } if (modelCheckerSettings.contains("timeout")) { if (!modelCheckerSettings["timeout"].is_number_unsigned()) return formatFatalError(Error::Type::JSONError, "settings.modelChecker.timeout must be an unsigned integer."); ret.modelCheckerSettings.timeout = modelCheckerSettings["timeout"].get<Json::number_unsigned_t>(); } return {std::move(ret)}; } std::map<std::string, Json> StandardCompiler::parseAstFromInput(StringMap const& _sources) { std::map<std::string, Json> sourceJsons; for (auto const& [sourceName, sourceCode]: _sources) { Json ast; astAssert(util::jsonParseStrict(sourceCode, ast), "Input file could not be parsed to JSON"); std::string astKey = ast.contains("ast") ? "ast" : "AST"; astAssert(ast.contains(astKey), "astkey is not member"); astAssert(ast[astKey]["nodeType"].get<std::string>() == "SourceUnit", "Top-level node should be a 'SourceUnit'"); astAssert(sourceJsons.count(sourceName) == 0, "All sources must have unique names"); sourceJsons.emplace(sourceName, std::move(ast[astKey])); } return sourceJsons; } Json StandardCompiler::importEVMAssembly(StandardCompiler::InputsAndSettings _inputsAndSettings) { solAssert(_inputsAndSettings.language == "EVMAssembly"); solAssert(_inputsAndSettings.sources.empty()); solAssert(_inputsAndSettings.jsonSources.size() == 1); if (!isBinaryRequested(_inputsAndSettings.outputSelection)) return Json::object(); evmasm::EVMAssemblyStack stack(_inputsAndSettings.evmVersion, _inputsAndSettings.eofVersion); std::string const& sourceName = _inputsAndSettings.jsonSources.begin()->first; // result of structured binding can only be used within lambda from C++20 on. Json const& sourceJson = _inputsAndSettings.jsonSources.begin()->second; try { stack.analyze(sourceName, sourceJson); stack.assemble(); } catch (evmasm::AssemblyImportException const& e) { return formatFatalError(Error::Type::Exception, "Assembly import error: " + std::string(e.what())); } catch (evmasm::InvalidOpcode const& e) { return formatFatalError(Error::Type::Exception, "Assembly import error: " + std::string(e.what())); } catch (...) { return formatError( Error::Type::Exception, "general", "Unknown exception during assembly import: " + boost::current_exception_diagnostic_information() ); } if (!stack.compilationSuccessful()) return Json::object(); // EVM bool const wildcardMatchesExperimental = false; Json evmData; if (isArtifactRequested(_inputsAndSettings.outputSelection, sourceName, "", "evm.assembly", wildcardMatchesExperimental)) evmData["assembly"] = stack.assemblyString(sourceName, {}); if (isArtifactRequested(_inputsAndSettings.outputSelection, sourceName, "", "evm.legacyAssembly", wildcardMatchesExperimental)) evmData["legacyAssembly"] = stack.assemblyJSON(sourceName); if (isArtifactRequested( _inputsAndSettings.outputSelection, sourceName, "", evmObjectComponents("bytecode"), wildcardMatchesExperimental )) evmData["bytecode"] = collectEVMObject( _inputsAndSettings.evmVersion, stack.object(sourceName), stack.sourceMapping(sourceName), {}, false, // _runtimeObject [&](std::string const& _element) { return isArtifactRequested( _inputsAndSettings.outputSelection, sourceName, "", "evm.bytecode." + _element, wildcardMatchesExperimental ); } ); if (isArtifactRequested( _inputsAndSettings.outputSelection, sourceName, "", evmObjectComponents("deployedBytecode"), wildcardMatchesExperimental )) evmData["deployedBytecode"] = collectEVMObject( _inputsAndSettings.evmVersion, stack.runtimeObject(sourceName), stack.runtimeSourceMapping(sourceName), {}, true, // _runtimeObject [&](std::string const& _element) { return isArtifactRequested( _inputsAndSettings.outputSelection, sourceName, "", "evm.deployedBytecode." + _element, wildcardMatchesExperimental ); } ); Json contractData; if (!evmData.empty()) contractData["evm"] = evmData; Json contractsOutput; contractsOutput[sourceName][""] = contractData; Json output; output["contracts"] = contractsOutput; return util::removeNullMembers(output); } Json StandardCompiler::compileSolidity(StandardCompiler::InputsAndSettings _inputsAndSettings) { solAssert(_inputsAndSettings.jsonSources.empty()); CompilerStack compilerStack(m_readFile); StringMap sourceList = std::move(_inputsAndSettings.sources); if (_inputsAndSettings.language == "Solidity") compilerStack.setSources(sourceList); for (auto const& smtLib2Response: _inputsAndSettings.smtLib2Responses) compilerStack.addSMTLib2Response(smtLib2Response.first, smtLib2Response.second); compilerStack.setViaIR(_inputsAndSettings.viaIR); compilerStack.setEVMVersion(_inputsAndSettings.evmVersion); compilerStack.setEOFVersion(_inputsAndSettings.eofVersion); compilerStack.setRemappings(std::move(_inputsAndSettings.remappings)); compilerStack.setOptimiserSettings(std::move(_inputsAndSettings.optimiserSettings)); compilerStack.setRevertStringBehaviour(_inputsAndSettings.revertStrings); if (_inputsAndSettings.debugInfoSelection.has_value()) compilerStack.selectDebugInfo(_inputsAndSettings.debugInfoSelection.value()); compilerStack.setLibraries(_inputsAndSettings.libraries); compilerStack.useMetadataLiteralSources(_inputsAndSettings.metadataLiteralSources); compilerStack.setMetadataFormat(_inputsAndSettings.metadataFormat); compilerStack.setMetadataHash(_inputsAndSettings.metadataHash); compilerStack.selectContracts(pipelineConfig(_inputsAndSettings.outputSelection)); compilerStack.setModelCheckerSettings(_inputsAndSettings.modelCheckerSettings); Json errors = std::move(_inputsAndSettings.errors); bool const binariesRequested = isBinaryRequested(_inputsAndSettings.outputSelection); try { if (_inputsAndSettings.language == "SolidityAST") { try { compilerStack.importASTs(parseAstFromInput(sourceList)); if (!compilerStack.analyze()) errors.emplace_back(formatError(Error::Type::FatalError, "general", "Analysis of the AST failed.")); if (binariesRequested) compilerStack.compile(); } catch (util::Exception const& _exc) { solThrow(util::Exception, "Failed to import AST: "s + _exc.what()); } } else { if (binariesRequested) compilerStack.compile(); else compilerStack.parseAndAnalyze(_inputsAndSettings.stopAfter); for (auto const& error: compilerStack.errors()) errors.emplace_back(formatErrorWithException( compilerStack, *error, error->type(), "general", "", error->errorId() )); } } catch (CompilerError const& _exception) { errors.emplace_back(formatErrorWithException( compilerStack, _exception, Error::Type::CompilerError, "general", "Compiler error (" + _exception.lineInfo() + ")" )); } catch (InternalCompilerError const& _exception) { errors.emplace_back(formatErrorWithException( compilerStack, _exception, Error::Type::InternalCompilerError, "general", "Internal compiler error (" + _exception.lineInfo() + ")" )); } catch (UnimplementedFeatureError const& _exception) { // let StandardCompiler::compile handle this throw _exception; } catch (yul::YulException const& _exception) { errors.emplace_back(formatErrorWithException( compilerStack, _exception, Error::Type::YulException, "general", "Yul exception" )); } catch (smtutil::SMTLogicError const& _exception) { errors.emplace_back(formatErrorWithException( compilerStack, _exception, Error::Type::SMTLogicException, "general", "SMT logic exception" )); } catch (...) { errors.emplace_back(formatError( Error::Type::Exception, "general", "Unknown exception during compilation: " + boost::current_exception_diagnostic_information() )); } bool parsingSuccess = compilerStack.state() >= CompilerStack::State::Parsed; bool analysisSuccess = compilerStack.state() >= CompilerStack::State::AnalysisSuccessful; bool compilationSuccess = compilerStack.state() == CompilerStack::State::CompilationSuccessful; // If analysis fails, the artifacts inside CompilerStack are potentially incomplete and must not be returned. // Note that not completing analysis due to stopAfter does not count as a failure. It's neither failure nor success. bool analysisFailed = !analysisSuccess && _inputsAndSettings.stopAfter >= CompilerStack::State::AnalysisSuccessful; bool compilationFailed = !compilationSuccess && binariesRequested; if (compilationFailed || analysisFailed || !parsingSuccess) solAssert(!errors.empty(), "No error reported, but compilation failed."); Json output; if (errors.size() > 0) output["errors"] = std::move(errors); if (!compilerStack.unhandledSMTLib2Queries().empty()) for (std::string const& query: compilerStack.unhandledSMTLib2Queries()) output["auxiliaryInputRequested"]["smtlib2queries"]["0x" + util::keccak256(query).hex()] = query; bool const wildcardMatchesExperimental = false; output["sources"] = Json::object(); unsigned sourceIndex = 0; // NOTE: A case that will pass `parsingSuccess && !analysisFailed` but not `analysisSuccess` is // stopAfter: parsing with no parsing errors. if (parsingSuccess && !analysisFailed) for (std::string const& sourceName: compilerStack.sourceNames()) { Json sourceResult; sourceResult["id"] = sourceIndex++; if (isArtifactRequested(_inputsAndSettings.outputSelection, sourceName, "", "ast", wildcardMatchesExperimental)) sourceResult["ast"] = ASTJsonExporter(compilerStack.state(), compilerStack.sourceIndices()).toJson(compilerStack.ast(sourceName)); output["sources"][sourceName] = sourceResult; } Json contractsOutput; for (std::string const& contractName: analysisSuccess ? compilerStack.contractNames() : std::vector<std::string>()) { size_t colon = contractName.rfind(':'); solAssert(colon != std::string::npos, ""); std::string file = contractName.substr(0, colon); std::string name = contractName.substr(colon + 1); // ABI, storage layout, documentation and metadata Json contractData; if (isArtifactRequested(_inputsAndSettings.outputSelection, file, name, "abi", wildcardMatchesExperimental)) contractData["abi"] = compilerStack.contractABI(contractName); if (isArtifactRequested(_inputsAndSettings.outputSelection, file, name, "storageLayout", false)) contractData["storageLayout"] = compilerStack.storageLayout(contractName); if (isArtifactRequested(_inputsAndSettings.outputSelection, file, name, "transientStorageLayout", false)) contractData["transientStorageLayout"] = compilerStack.transientStorageLayout(contractName); if (isArtifactRequested(_inputsAndSettings.outputSelection, file, name, "metadata", wildcardMatchesExperimental)) contractData["metadata"] = compilerStack.metadata(contractName); if (isArtifactRequested(_inputsAndSettings.outputSelection, file, name, "userdoc", wildcardMatchesExperimental)) contractData["userdoc"] = compilerStack.natspecUser(contractName); if (isArtifactRequested(_inputsAndSettings.outputSelection, file, name, "devdoc", wildcardMatchesExperimental)) contractData["devdoc"] = compilerStack.natspecDev(contractName); // IR if (compilationSuccess && isArtifactRequested(_inputsAndSettings.outputSelection, file, name, "ir", wildcardMatchesExperimental)) contractData["ir"] = compilerStack.yulIR(contractName).value_or(""); if (compilationSuccess && isArtifactRequested(_inputsAndSettings.outputSelection, file, name, "irAst", wildcardMatchesExperimental)) contractData["irAst"] = compilerStack.yulIRAst(contractName).value_or(Json{}); if (compilationSuccess && isArtifactRequested(_inputsAndSettings.outputSelection, file, name, "irOptimized", wildcardMatchesExperimental)) contractData["irOptimized"] = compilerStack.yulIROptimized(contractName).value_or(""); if (compilationSuccess && isArtifactRequested(_inputsAndSettings.outputSelection, file, name, "irOptimizedAst", wildcardMatchesExperimental)) contractData["irOptimizedAst"] = compilerStack.yulIROptimizedAst(contractName).value_or(Json{}); if (compilationSuccess && isArtifactRequested(_inputsAndSettings.outputSelection, file, name, "yulCFGJson", wildcardMatchesExperimental)) contractData["yulCFGJson"] = compilerStack.yulCFGJson(contractName).value_or(Json{}); // EVM Json evmData; if (compilationSuccess && isArtifactRequested(_inputsAndSettings.outputSelection, file, name, "evm.assembly", wildcardMatchesExperimental)) evmData["assembly"] = compilerStack.assemblyString(contractName, sourceList); if (compilationSuccess && isArtifactRequested(_inputsAndSettings.outputSelection, file, name, "evm.legacyAssembly", wildcardMatchesExperimental)) evmData["legacyAssembly"] = compilerStack.assemblyJSON(contractName); if (isArtifactRequested(_inputsAndSettings.outputSelection, file, name, "evm.methodIdentifiers", wildcardMatchesExperimental)) evmData["methodIdentifiers"] = compilerStack.interfaceSymbols(contractName)["methods"]; if (compilationSuccess && isArtifactRequested(_inputsAndSettings.outputSelection, file, name, "evm.gasEstimates", wildcardMatchesExperimental)) evmData["gasEstimates"] = compilerStack.gasEstimates(contractName); if (compilationSuccess && isArtifactRequested( _inputsAndSettings.outputSelection, file, name, evmObjectComponents("bytecode"), wildcardMatchesExperimental )) evmData["bytecode"] = collectEVMObject( _inputsAndSettings.evmVersion, compilerStack.object(contractName), compilerStack.sourceMapping(contractName), compilerStack.generatedSources(contractName), false, [&](std::string const& _element) { return isArtifactRequested( _inputsAndSettings.outputSelection, file, name, "evm.bytecode." + _element, wildcardMatchesExperimental ); } ); if (compilationSuccess && isArtifactRequested( _inputsAndSettings.outputSelection, file, name, evmObjectComponents("deployedBytecode"), wildcardMatchesExperimental )) evmData["deployedBytecode"] = collectEVMObject( _inputsAndSettings.evmVersion, compilerStack.runtimeObject(contractName), compilerStack.runtimeSourceMapping(contractName), compilerStack.generatedSources(contractName, true), true, [&](std::string const& _element) { return isArtifactRequested( _inputsAndSettings.outputSelection, file, name, "evm.deployedBytecode." + _element, wildcardMatchesExperimental ); } ); if (!evmData.empty()) contractData["evm"] = evmData; if (!contractData.empty()) { if (!contractsOutput.contains(file)) contractsOutput[file] = Json::object(); contractsOutput[file][name] = contractData; } } if (!contractsOutput.empty()) output["contracts"] = contractsOutput; return output; } Json StandardCompiler::compileYul(InputsAndSettings _inputsAndSettings) { solAssert(_inputsAndSettings.jsonSources.empty()); Json output; output["errors"] = std::move(_inputsAndSettings.errors); if (_inputsAndSettings.sources.size() != 1) { output["errors"].emplace_back(formatError( Error::Type::JSONError, "general", "Yul mode only supports exactly one input file." )); return output; } if (!_inputsAndSettings.smtLib2Responses.empty()) { output["errors"].emplace_back(formatError( Error::Type::JSONError, "general", "Yul mode does not support smtlib2responses." )); return output; } if (!_inputsAndSettings.remappings.empty()) { output["errors"].emplace_back(formatError( Error::Type::JSONError, "general", "Field \"settings.remappings\" cannot be used for Yul." )); return output; } if (_inputsAndSettings.revertStrings != RevertStrings::Default) { output["errors"].emplace_back(formatError( Error::Type::JSONError, "general", "Field \"settings.debug.revertStrings\" cannot be used for Yul." )); return output; } YulStack stack( _inputsAndSettings.evmVersion, _inputsAndSettings.eofVersion, YulStack::Language::StrictAssembly, _inputsAndSettings.optimiserSettings, _inputsAndSettings.debugInfoSelection.has_value() ? _inputsAndSettings.debugInfoSelection.value() : DebugInfoSelection::Default() ); std::string const& sourceName = _inputsAndSettings.sources.begin()->first; std::string const& sourceContents = _inputsAndSettings.sources.begin()->second; // Inconsistent state - stop here to receive error reports from users if (!stack.parseAndAnalyze(sourceName, sourceContents) && !stack.hasErrors()) solAssert(false, "No error reported, but parsing/analysis failed."); for (auto const& error: stack.errors()) { auto err = std::dynamic_pointer_cast<Error const>(error); output["errors"].emplace_back(formatErrorWithException( stack, *error, err->type(), "general", "" )); } if (stack.hasErrors()) return output; std::string contractName = stack.parserResult()->name; bool const wildcardMatchesExperimental = true; if (isArtifactRequested(_inputsAndSettings.outputSelection, sourceName, contractName, "ir", wildcardMatchesExperimental)) output["contracts"][sourceName][contractName]["ir"] = stack.print(); if (isArtifactRequested(_inputsAndSettings.outputSelection, sourceName, contractName, "ast", wildcardMatchesExperimental)) { Json sourceResult; sourceResult["id"] = 0; sourceResult["ast"] = stack.astJson(); output["sources"][sourceName] = sourceResult; } stack.optimize(); MachineAssemblyObject object; MachineAssemblyObject deployedObject; std::tie(object, deployedObject) = stack.assembleWithDeployed(); if (object.bytecode) object.bytecode->link(_inputsAndSettings.libraries); if (deployedObject.bytecode) deployedObject.bytecode->link(_inputsAndSettings.libraries); for (auto&& [kind, isDeployed]: {make_pair("bytecode"s, false), make_pair("deployedBytecode"s, true)}) if (isArtifactRequested( _inputsAndSettings.outputSelection, sourceName, contractName, evmObjectComponents(kind), wildcardMatchesExperimental )) { MachineAssemblyObject const& o = isDeployed ? deployedObject : object; if (o.bytecode) output["contracts"][sourceName][contractName]["evm"][kind] = collectEVMObject( _inputsAndSettings.evmVersion, *o.bytecode, o.sourceMappings.get(), Json::array(), isDeployed, [&, kind = kind](std::string const& _element) { return isArtifactRequested( _inputsAndSettings.outputSelection, sourceName, contractName, "evm." + kind + "." + _element, wildcardMatchesExperimental ); } ); } if (isArtifactRequested(_inputsAndSettings.outputSelection, sourceName, contractName, "irOptimized", wildcardMatchesExperimental)) output["contracts"][sourceName][contractName]["irOptimized"] = stack.print(); if (isArtifactRequested(_inputsAndSettings.outputSelection, sourceName, contractName, "evm.assembly", wildcardMatchesExperimental)) output["contracts"][sourceName][contractName]["evm"]["assembly"] = object.assembly->assemblyString(stack.debugInfoSelection()); if (isArtifactRequested(_inputsAndSettings.outputSelection, sourceName, contractName, "yulCFGJson", wildcardMatchesExperimental)) output["contracts"][sourceName][contractName]["yulCFGJson"] = stack.cfgJson(); return output; } Json StandardCompiler::compile(Json const& _input) noexcept { YulStringRepository::reset(); try { auto parsed = parseInput(_input); if (std::holds_alternative<Json>(parsed)) return std::get<Json>(std::move(parsed)); InputsAndSettings settings = std::get<InputsAndSettings>(std::move(parsed)); if (settings.language == "Solidity") return compileSolidity(std::move(settings)); else if (settings.language == "Yul") return compileYul(std::move(settings)); else if (settings.language == "SolidityAST") return compileSolidity(std::move(settings)); else if (settings.language == "EVMAssembly") return importEVMAssembly(std::move(settings)); else return formatFatalError(Error::Type::JSONError, "Only \"Solidity\", \"Yul\", \"SolidityAST\" or \"EVMAssembly\" is supported as a language."); } catch (UnimplementedFeatureError const& _exception) { solAssert(_exception.comment(), "Unimplemented feature errors must include a message for the user"); return formatFatalError(Error::Type::UnimplementedFeatureError, stringOrDefault(_exception.comment())); } catch (...) { return formatFatalError(Error::Type::InternalCompilerError, "Internal exception in StandardCompiler::compile: " + boost::current_exception_diagnostic_information()); } } std::string StandardCompiler::compile(std::string const& _input) noexcept { Json input; std::string errors; try { if (!util::jsonParseStrict(_input, input, &errors)) return util::jsonPrint(formatFatalError(Error::Type::JSONError, errors), m_jsonPrintingFormat); } catch (...) { if (errors.empty()) return "{\"errors\":[{\"type\":\"JSONError\",\"component\":\"general\",\"severity\":\"error\",\"message\":\"Error parsing input JSON.\"}]}"; else return "{\"errors\":[{\"type\":\"JSONError\",\"component\":\"general\",\"severity\":\"error\",\"message\":\"Error parsing input JSON: " + errors + "\"}]}"; } // std::cout << "Input: " << solidity::util::jsonPrettyPrint(input) << std::endl; Json output = compile(input); // std::cout << "Output: " << solidity::util::jsonPrettyPrint(output) << std::endl; try { return util::jsonPrint(output, m_jsonPrintingFormat); } catch (...) { return "{\"errors\":[{\"type\":\"JSONError\",\"component\":\"general\",\"severity\":\"error\",\"message\":\"Error writing output JSON.\"}]}"; } } Json StandardCompiler::formatFunctionDebugData( std::map<std::string, evmasm::LinkerObject::FunctionDebugData> const& _debugInfo ) { static_assert(std::is_same_v<Json::number_unsigned_t, uint64_t>); Json ret = Json::object(); for (auto const& [name, info]: _debugInfo) { Json fun = Json::object(); if (info.sourceID) fun["id"] = Json::number_unsigned_t(*info.sourceID); else fun["id"] = Json(); if (info.bytecodeOffset) fun["entryPoint"] = Json::number_unsigned_t(*info.bytecodeOffset); else fun["entryPoint"] = Json(); fun["parameterSlots"] = Json::number_unsigned_t(info.params); fun["returnSlots"] = Json::number_unsigned_t(info.returns); ret[name] = std::move(fun); } return ret; }
65,194
C++
.cpp
1,571
38.219605
223
0.742445
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,237
SMTSolverCommand.cpp
ethereum_solidity/libsolidity/interface/SMTSolverCommand.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libsolidity/interface/SMTSolverCommand.h> #include <liblangutil/Exceptions.h> #include <boost/algorithm/string/join.hpp> #include <boost/process.hpp> namespace solidity::frontend { void SMTSolverCommand::setEldarica(std::optional<unsigned int> timeoutInMilliseconds, bool computeInvariants) { m_arguments.clear(); m_solverCmd = "eld"; m_arguments.emplace_back("-hsmt"); // Tell Eldarica to expect input in SMT2 format m_arguments.emplace_back("-in"); // Tell Eldarica to read from standard input if (timeoutInMilliseconds) { unsigned int timeoutInSeconds = timeoutInMilliseconds.value() / 1000u; timeoutInSeconds = timeoutInSeconds == 0 ? 1 : timeoutInSeconds; m_arguments.push_back("-t:" + std::to_string(timeoutInSeconds)); } if (computeInvariants) m_arguments.emplace_back("-ssol"); // Tell Eldarica to produce model (invariant) } void SMTSolverCommand::setCvc5(std::optional<unsigned int> timeoutInMilliseconds) { m_arguments.clear(); m_solverCmd = "cvc5"; if (timeoutInMilliseconds) { m_arguments.emplace_back("--tlimit-per"); m_arguments.push_back(std::to_string(timeoutInMilliseconds.value())); } else { m_arguments.emplace_back("--rlimit"); // Set resource limit cvc5 can spend on a query m_arguments.push_back(std::to_string(12000)); } } void SMTSolverCommand::setZ3(std::optional<unsigned int> timeoutInMilliseconds, bool _preprocessing, bool _computeInvariants) { constexpr int Z3ResourceLimit = 2000000; m_arguments.clear(); m_solverCmd = "z3"; m_arguments.emplace_back("-in"); // Read from standard input m_arguments.emplace_back("-smt2"); // Expect input in SMT-LIB2 format if (_computeInvariants) m_arguments.emplace_back("-model"); // Output model automatically after check-sat if (timeoutInMilliseconds) m_arguments.emplace_back("-t:" + std::to_string(timeoutInMilliseconds.value())); else m_arguments.emplace_back("rlimit=" + std::to_string(Z3ResourceLimit)); // These options have been empirically established to be helpful m_arguments.emplace_back("rewriter.pull_cheap_ite=true"); m_arguments.emplace_back("fp.spacer.q3.use_qgen=true"); m_arguments.emplace_back("fp.spacer.mbqi=false"); m_arguments.emplace_back("fp.spacer.ground_pobs=false"); // Spacer optimization should be // - enabled for better solving (default) // - disable for counterexample generation std::string preprocessingArg = _preprocessing ? "true" : "false"; m_arguments.emplace_back("fp.xform.slice=" + preprocessingArg); m_arguments.emplace_back("fp.xform.inline_linear=" + preprocessingArg); m_arguments.emplace_back("fp.xform.inline_eager=" + preprocessingArg); } ReadCallback::Result SMTSolverCommand::solve(std::string const& _kind, std::string const& _query) const { try { if (_kind != ReadCallback::kindString(ReadCallback::Kind::SMTQuery)) solAssert(false, "SMTQuery callback used as callback kind " + _kind); if (m_solverCmd.empty()) return ReadCallback::Result{false, "No solver set."}; auto solverBin = boost::process::search_path(m_solverCmd); if (solverBin.empty()) return ReadCallback::Result{false, m_solverCmd + " binary not found."}; auto args = m_arguments; boost::process::opstream in; // input to subprocess written to by the main process boost::process::ipstream out; // output from subprocess read by the main process boost::process::child solverProcess( solverBin, args, boost::process::std_out > out, boost::process::std_in < in, boost::process::std_err > boost::process::null ); in << _query << std::flush; in.pipe().close(); in.close(); std::vector<std::string> data; std::string line; while (!(out.fail() || out.eof()) && std::getline(out, line)) if (!line.empty()) data.push_back(line); solverProcess.wait(); return ReadCallback::Result{true, boost::join(data, "\n")}; } catch (...) { return ReadCallback::Result{false, "Exception in SMTQuery callback: " + boost::current_exception_diagnostic_information()}; } } }
4,679
C++
.cpp
114
38.605263
125
0.749064
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,239
ImportRemapper.cpp
ethereum_solidity/libsolidity/interface/ImportRemapper.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libsolidity/interface/ImportRemapper.h> #include <libsolutil/CommonIO.h> #include <liblangutil/Exceptions.h> namespace solidity::frontend { void ImportRemapper::setRemappings(std::vector<Remapping> _remappings) { for (auto const& remapping: _remappings) solAssert(!remapping.prefix.empty(), ""); m_remappings = std::move(_remappings); } SourceUnitName ImportRemapper::apply(ImportPath const& _path, std::string const& _context) const { // Try to find the longest prefix match in all remappings that are active in the current context. auto isPrefixOf = [](std::string const& _a, std::string const& _b) { if (_a.length() > _b.length()) return false; return equal(_a.begin(), _a.end(), _b.begin()); }; size_t longestPrefix = 0; size_t longestContext = 0; std::string bestMatchTarget; for (auto const& redir: m_remappings) { std::string context = util::sanitizePath(redir.context); std::string prefix = util::sanitizePath(redir.prefix); // Skip if current context is closer if (context.length() < longestContext) continue; // Skip if redir.context is not a prefix of _context if (!isPrefixOf(context, _context)) continue; // Skip if we already have a closer prefix match. if (prefix.length() < longestPrefix && context.length() == longestContext) continue; // Skip if the prefix does not match. if (!isPrefixOf(prefix, _path)) continue; longestContext = context.length(); longestPrefix = prefix.length(); bestMatchTarget = util::sanitizePath(redir.target); } std::string path = bestMatchTarget; path.append(_path.begin() + static_cast<std::string::difference_type>(longestPrefix), _path.end()); return path; } bool ImportRemapper::isRemapping(std::string_view _input) { return _input.find("=") != std::string::npos; } std::optional<ImportRemapper::Remapping> ImportRemapper::parseRemapping(std::string_view _input) { auto equals = std::find(_input.cbegin(), _input.cend(), '='); if (equals == _input.end()) return std::nullopt; auto const colon = std::find(_input.cbegin(), equals, ':'); Remapping remapping{ (colon == equals ? "" : std::string(_input.cbegin(), colon)), (colon == equals ? std::string(_input.cbegin(), equals) : std::string(colon + 1, equals)), std::string(equals + 1, _input.cend()), }; if (remapping.prefix.empty()) return std::nullopt; return remapping; } }
3,064
C++
.cpp
81
35.481481
100
0.733648
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
3,240
CallGraph.cpp
ethereum_solidity/libsolidity/ast/CallGraph.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libsolidity/ast/CallGraph.h> using namespace solidity::frontend; bool CallGraph::CompareByID::operator()(Node const& _lhs, Node const& _rhs) const { if (_lhs.index() != _rhs.index()) return _lhs.index() < _rhs.index(); if (std::holds_alternative<SpecialNode>(_lhs)) return std::get<SpecialNode>(_lhs) < std::get<SpecialNode>(_rhs); return std::get<CallableDeclaration const*>(_lhs)->id() < std::get<CallableDeclaration const*>(_rhs)->id(); } bool CallGraph::CompareByID::operator()(Node const& _lhs, int64_t _rhs) const { solAssert(!std::holds_alternative<SpecialNode>(_lhs), ""); return std::get<CallableDeclaration const*>(_lhs)->id() < _rhs; } bool CallGraph::CompareByID::operator()(int64_t _lhs, Node const& _rhs) const { solAssert(!std::holds_alternative<SpecialNode>(_rhs), ""); return _lhs < std::get<CallableDeclaration const*>(_rhs)->id(); }
1,566
C++
.cpp
34
44.088235
108
0.745562
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
3,242
ASTJsonExporter.cpp
ethereum_solidity/libsolidity/ast/ASTJsonExporter.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 /** * @date 2017 * Converts the AST into json format */ #include <libsolidity/ast/ASTJsonExporter.h> #include <libsolidity/ast/AST.h> #include <libsolidity/ast/TypeProvider.h> #include <libyul/AsmJsonConverter.h> #include <libyul/AST.h> #include <libyul/backends/evm/EVMDialect.h> #include <libsolutil/JSON.h> #include <libsolutil/UTF8.h> #include <libsolutil/CommonData.h> #include <libsolutil/Visitor.h> #include <libsolutil/Keccak256.h> #include <boost/algorithm/string/join.hpp> #include <utility> #include <vector> #include <algorithm> #include <limits> #include <type_traits> #include <range/v3/view/map.hpp> using namespace std::string_literals; using namespace solidity::langutil; using namespace solidity; namespace { template<typename V, template<typename> typename C> void addIfSet(std::vector<std::pair<std::string, Json>>& _attributes, std::string const& _name, C<V> const& _value) { if constexpr (std::is_same_v<C<V>, solidity::util::SetOnce<V>>) { if (!_value.set()) return; } else if constexpr (std::is_same_v<C<V>, std::optional<V>>) { if (!_value.has_value()) return; } _attributes.emplace_back(_name, *_value); } } namespace solidity::frontend { ASTJsonExporter::ASTJsonExporter(CompilerStack::State _stackState, std::map<std::string, unsigned> _sourceIndices): m_stackState(_stackState), m_sourceIndices(std::move(_sourceIndices)) { } void ASTJsonExporter::setJsonNode( ASTNode const& _node, std::string const& _nodeName, std::initializer_list<std::pair<std::string, Json>>&& _attributes ) { ASTJsonExporter::setJsonNode( _node, _nodeName, std::vector<std::pair<std::string, Json>>(std::move(_attributes)) ); } void ASTJsonExporter::setJsonNode( ASTNode const& _node, std::string const& _nodeType, std::vector<std::pair<std::string, Json>>&& _attributes ) { m_currentValue = Json::object(); m_currentValue["id"] = nodeId(_node); m_currentValue["src"] = sourceLocationToString(_node.location()); if (auto const* documented = dynamic_cast<Documented const*>(&_node)) if (documented->documentation()) m_currentValue["documentation"] = *documented->documentation(); m_currentValue["nodeType"] = _nodeType; for (auto& e: _attributes) m_currentValue[e.first] = std::move(e.second); } std::optional<size_t> ASTJsonExporter::sourceIndexFromLocation(SourceLocation const& _location) const { if (_location.sourceName && m_sourceIndices.count(*_location.sourceName)) return m_sourceIndices.at(*_location.sourceName); else return std::nullopt; } std::string ASTJsonExporter::sourceLocationToString(SourceLocation const& _location) const { std::optional<size_t> sourceIndexOpt = sourceIndexFromLocation(_location); int length = -1; if (_location.start >= 0 && _location.end >= 0) length = _location.end - _location.start; return std::to_string(_location.start) + ":" + std::to_string(length) + ":" + (sourceIndexOpt.has_value() ? std::to_string(sourceIndexOpt.value()) : "-1"); } Json ASTJsonExporter::sourceLocationsToJson(std::vector<SourceLocation> const& _sourceLocations) const { Json locations = Json::array(); for (SourceLocation const& location: _sourceLocations) locations.emplace_back(sourceLocationToString(location)); return locations; } std::string ASTJsonExporter::namePathToString(std::vector<ASTString> const& _namePath) { return boost::algorithm::join(_namePath, "."s); } Json ASTJsonExporter::typePointerToJson(Type const* _tp, bool _withoutDataLocation) { Json typeDescriptions; typeDescriptions["typeString"] = _tp ? Json(_tp->toString(_withoutDataLocation)) : Json(); typeDescriptions["typeIdentifier"] = _tp ? Json(_tp->identifier()) : Json(); return typeDescriptions; } Json ASTJsonExporter::typePointerToJson(std::optional<FuncCallArguments> const& _tps) { if (_tps) { Json arguments = Json::array(); for (auto const& tp: _tps->types) appendMove(arguments, typePointerToJson(tp)); return arguments; } else return Json(); } void ASTJsonExporter::appendExpressionAttributes( std::vector<std::pair<std::string, Json>>& _attributes, ExpressionAnnotation const& _annotation ) { std::vector<std::pair<std::string, Json>> exprAttributes = { std::make_pair("typeDescriptions", typePointerToJson(_annotation.type)), std::make_pair("argumentTypes", typePointerToJson(_annotation.arguments)) }; addIfSet(exprAttributes, "isLValue", _annotation.isLValue); addIfSet(exprAttributes, "isPure", _annotation.isPure); addIfSet(exprAttributes, "isConstant", _annotation.isConstant); if (m_stackState > CompilerStack::State::ParsedAndImported) exprAttributes.emplace_back("lValueRequested", _annotation.willBeWrittenTo); _attributes += exprAttributes; } Json ASTJsonExporter::inlineAssemblyIdentifierToJson(std::pair<yul::Identifier const*, InlineAssemblyAnnotation::ExternalIdentifierInfo> _info) const { Json tuple; tuple["src"] = sourceLocationToString(nativeLocationOf(*_info.first)); tuple["declaration"] = idOrNull(_info.second.declaration); tuple["isSlot"] = Json(_info.second.suffix == "slot"); tuple["isOffset"] = Json(_info.second.suffix == "offset"); if (!_info.second.suffix.empty()) tuple["suffix"] = Json(_info.second.suffix); tuple["valueSize"] = Json(static_cast<Json::number_integer_t>(_info.second.valueSize)); return tuple; } void ASTJsonExporter::print(std::ostream& _stream, ASTNode const& _node, util::JsonFormat const& _format) { _stream << util::jsonPrint(toJson(_node), _format); } Json ASTJsonExporter::toJson(ASTNode const& _node) { _node.accept(*this); return util::removeNullMembers(std::move(m_currentValue)); } bool ASTJsonExporter::visit(SourceUnit const& _node) { std::vector<std::pair<std::string, Json>> attributes = { std::make_pair("license", _node.licenseString() ? Json(*_node.licenseString()) : Json()), std::make_pair("nodes", toJson(_node.nodes())), }; if (_node.experimentalSolidity()) attributes.emplace_back("experimentalSolidity", Json(_node.experimentalSolidity())); if (_node.annotation().exportedSymbols.set()) { Json exportedSymbols = Json::object(); for (auto const& sym: *_node.annotation().exportedSymbols) { exportedSymbols[sym.first] = Json::array(); for (Declaration const* overload: sym.second) exportedSymbols[sym.first].emplace_back(nodeId(*overload)); } attributes.emplace_back("exportedSymbols", exportedSymbols); }; addIfSet(attributes, "absolutePath", _node.annotation().path); setJsonNode(_node, "SourceUnit", std::move(attributes)); return false; } bool ASTJsonExporter::visit(PragmaDirective const& _node) { Json literals = Json::array(); for (auto const& literal: _node.literals()) literals.emplace_back(literal); setJsonNode(_node, "PragmaDirective", { std::make_pair("literals", std::move(literals)) }); return false; } bool ASTJsonExporter::visit(ImportDirective const& _node) { std::vector<std::pair<std::string, Json>> attributes = { std::make_pair("file", _node.path()), std::make_pair("sourceUnit", idOrNull(_node.annotation().sourceUnit)), std::make_pair("scope", idOrNull(_node.scope())) }; addIfSet(attributes, "absolutePath", _node.annotation().absolutePath); attributes.emplace_back("unitAlias", _node.name()); attributes.emplace_back("nameLocation", Json(sourceLocationToString(_node.nameLocation()))); Json symbolAliases = Json::array(); for (auto const& symbolAlias: _node.symbolAliases()) { Json tuple; solAssert(symbolAlias.symbol, ""); tuple["foreign"] = toJson(*symbolAlias.symbol); tuple["local"] = symbolAlias.alias ? Json(*symbolAlias.alias) : Json(); tuple["nameLocation"] = sourceLocationToString(_node.nameLocation()); symbolAliases.emplace_back(tuple); } attributes.emplace_back("symbolAliases", std::move(symbolAliases)); setJsonNode(_node, "ImportDirective", std::move(attributes)); return false; } bool ASTJsonExporter::visit(ContractDefinition const& _node) { std::vector<std::pair<std::string, Json>> attributes = { std::make_pair("name", _node.name()), std::make_pair("nameLocation", sourceLocationToString(_node.nameLocation())), std::make_pair("documentation", _node.documentation() ? toJson(*_node.documentation()) : Json()), std::make_pair("contractKind", contractKind(_node.contractKind())), std::make_pair("abstract", _node.abstract()), std::make_pair("baseContracts", toJson(_node.baseContracts())), std::make_pair("contractDependencies", getContainerIds(_node.annotation().contractDependencies | ranges::views::keys)), // Do not require call graph because the AST is also created for incorrect sources. std::make_pair("usedEvents", getContainerIds(_node.interfaceEvents(false))), std::make_pair("usedErrors", getContainerIds(_node.interfaceErrors(false))), std::make_pair("nodes", toJson(_node.subNodes())), std::make_pair("scope", idOrNull(_node.scope())) }; addIfSet(attributes, "canonicalName", _node.annotation().canonicalName); if (_node.annotation().unimplementedDeclarations.has_value()) attributes.emplace_back("fullyImplemented", _node.annotation().unimplementedDeclarations->empty()); if (!_node.annotation().linearizedBaseContracts.empty()) attributes.emplace_back("linearizedBaseContracts", getContainerIds(_node.annotation().linearizedBaseContracts)); if (!_node.annotation().internalFunctionIDs.empty()) { Json internalFunctionIDs; for (auto const& [functionDefinition, internalFunctionID]: _node.annotation().internalFunctionIDs) internalFunctionIDs[std::to_string(functionDefinition->id())] = internalFunctionID; attributes.emplace_back("internalFunctionIDs", std::move(internalFunctionIDs)); } setJsonNode(_node, "ContractDefinition", std::move(attributes)); return false; } bool ASTJsonExporter::visit(IdentifierPath const& _node) { Json nameLocations = Json::array(); for (SourceLocation location: _node.pathLocations()) nameLocations.emplace_back(sourceLocationToString(location)); setJsonNode(_node, "IdentifierPath", { std::make_pair("name", namePathToString(_node.path())), std::make_pair("nameLocations", nameLocations), std::make_pair("referencedDeclaration", idOrNull(_node.annotation().referencedDeclaration)) }); return false; } bool ASTJsonExporter::visit(InheritanceSpecifier const& _node) { setJsonNode(_node, "InheritanceSpecifier", { std::make_pair("baseName", toJson(_node.name())), std::make_pair("arguments", _node.arguments() ? toJson(*_node.arguments()) : Json()) }); return false; } bool ASTJsonExporter::visit(UsingForDirective const& _node) { std::vector<std::pair<std::string, Json>> attributes = { std::make_pair("typeName", _node.typeName() ? toJson(*_node.typeName()) : Json()) }; if (_node.usesBraces()) { Json functionList = Json::array(); for (auto&& [function, op]: _node.functionsAndOperators()) { Json functionNode; if (!op.has_value()) functionNode["function"] = toJson(*function); else { functionNode["definition"] = toJson(*function); functionNode["operator"] = std::string(TokenTraits::toString(*op)); } functionList.emplace_back(std::move(functionNode)); } attributes.emplace_back("functionList", std::move(functionList)); } else { auto const& functionAndOperators = _node.functionsAndOperators(); solAssert(_node.functionsAndOperators().size() == 1); solAssert(!functionAndOperators.front().second.has_value()); attributes.emplace_back("libraryName", toJson(*(functionAndOperators.front().first))); } attributes.emplace_back("global", _node.global()); setJsonNode(_node, "UsingForDirective", std::move(attributes)); return false; } bool ASTJsonExporter::visit(StructDefinition const& _node) { std::vector<std::pair<std::string, Json>> attributes = { std::make_pair("name", _node.name()), std::make_pair("nameLocation", sourceLocationToString(_node.nameLocation())), std::make_pair("documentation", _node.documentation() ? toJson(*_node.documentation()) : Json()), std::make_pair("visibility", Declaration::visibilityToString(_node.visibility())), std::make_pair("members", toJson(_node.members())), std::make_pair("scope", idOrNull(_node.scope())) }; addIfSet(attributes,"canonicalName", _node.annotation().canonicalName); setJsonNode(_node, "StructDefinition", std::move(attributes)); return false; } bool ASTJsonExporter::visit(EnumDefinition const& _node) { std::vector<std::pair<std::string, Json>> attributes = { std::make_pair("name", _node.name()), std::make_pair("nameLocation", sourceLocationToString(_node.nameLocation())), std::make_pair("documentation", _node.documentation() ? toJson(*_node.documentation()) : Json()), std::make_pair("members", toJson(_node.members())) }; addIfSet(attributes,"canonicalName", _node.annotation().canonicalName); setJsonNode(_node, "EnumDefinition", std::move(attributes)); return false; } bool ASTJsonExporter::visit(EnumValue const& _node) { setJsonNode(_node, "EnumValue", { std::make_pair("name", _node.name()), std::make_pair("nameLocation", sourceLocationToString(_node.nameLocation())), }); return false; } bool ASTJsonExporter::visit(UserDefinedValueTypeDefinition const& _node) { solAssert(_node.underlyingType(), ""); std::vector<std::pair<std::string, Json>> attributes = { std::make_pair("name", _node.name()), std::make_pair("nameLocation", sourceLocationToString(_node.nameLocation())), std::make_pair("underlyingType", toJson(*_node.underlyingType())) }; addIfSet(attributes, "canonicalName", _node.annotation().canonicalName); setJsonNode(_node, "UserDefinedValueTypeDefinition", std::move(attributes)); return false; } bool ASTJsonExporter::visit(ParameterList const& _node) { setJsonNode(_node, "ParameterList", { std::make_pair("parameters", toJson(_node.parameters())) }); return false; } bool ASTJsonExporter::visit(OverrideSpecifier const& _node) { setJsonNode(_node, "OverrideSpecifier", { std::make_pair("overrides", toJson(_node.overrides())) }); return false; } bool ASTJsonExporter::visit(FunctionDefinition const& _node) { std::vector<std::pair<std::string, Json>> attributes = { std::make_pair("name", _node.name()), std::make_pair("nameLocation", sourceLocationToString(_node.nameLocation())), std::make_pair("documentation", _node.documentation() ? toJson(*_node.documentation()) : Json()), std::make_pair("kind", _node.isFree() ? "freeFunction" : TokenTraits::toString(_node.kind())), std::make_pair("stateMutability", stateMutabilityToString(_node.stateMutability())), std::make_pair("virtual", _node.markedVirtual()), std::make_pair("overrides", _node.overrides() ? toJson(*_node.overrides()) : Json()), std::make_pair("parameters", toJson(_node.parameterList())), std::make_pair("returnParameters", toJson(*_node.returnParameterList())), std::make_pair("modifiers", toJson(_node.modifiers())), std::make_pair("body", _node.isImplemented() ? toJson(_node.body()) : Json()), std::make_pair("implemented", _node.isImplemented()), std::make_pair("scope", idOrNull(_node.scope())) }; std::optional<Visibility> visibility; if (_node.isConstructor()) { if (_node.annotation().contract) visibility = _node.annotation().contract->abstract() ? Visibility::Internal : Visibility::Public; } else visibility = _node.visibility(); if (visibility) attributes.emplace_back("visibility", Declaration::visibilityToString(*visibility)); if (_node.isPartOfExternalInterface() && m_stackState > CompilerStack::State::ParsedAndImported) attributes.emplace_back("functionSelector", _node.externalIdentifierHex()); if (!_node.annotation().baseFunctions.empty()) attributes.emplace_back(std::make_pair("baseFunctions", getContainerIds(_node.annotation().baseFunctions, true))); setJsonNode(_node, "FunctionDefinition", std::move(attributes)); return false; } bool ASTJsonExporter::visit(VariableDeclaration const& _node) { std::vector<std::pair<std::string, Json>> attributes = { std::make_pair("name", _node.name()), std::make_pair("nameLocation", sourceLocationToString(_node.nameLocation())), std::make_pair("typeName", toJson(_node.typeName())), std::make_pair("constant", _node.isConstant()), std::make_pair("mutability", VariableDeclaration::mutabilityToString(_node.mutability())), std::make_pair("stateVariable", _node.isStateVariable()), std::make_pair("storageLocation", location(_node.referenceLocation())), std::make_pair("overrides", _node.overrides() ? toJson(*_node.overrides()) : Json()), std::make_pair("visibility", Declaration::visibilityToString(_node.visibility())), std::make_pair("value", _node.value() ? toJson(*_node.value()) : Json()), std::make_pair("scope", idOrNull(_node.scope())), std::make_pair("typeDescriptions", typePointerToJson(_node.annotation().type, true)) }; if (_node.isStateVariable() && _node.isPublic()) attributes.emplace_back("functionSelector", _node.externalIdentifierHex()); if (_node.isStateVariable() && _node.documentation()) attributes.emplace_back("documentation", toJson(*_node.documentation())); if (m_inEvent) attributes.emplace_back("indexed", _node.isIndexed()); if (!_node.annotation().baseFunctions.empty()) attributes.emplace_back(std::make_pair("baseFunctions", getContainerIds(_node.annotation().baseFunctions, true))); setJsonNode(_node, "VariableDeclaration", std::move(attributes)); return false; } bool ASTJsonExporter::visit(ModifierDefinition const& _node) { std::vector<std::pair<std::string, Json>> attributes = { std::make_pair("name", _node.name()), std::make_pair("nameLocation", sourceLocationToString(_node.nameLocation())), std::make_pair("documentation", _node.documentation() ? toJson(*_node.documentation()) : Json()), std::make_pair("visibility", Declaration::visibilityToString(_node.visibility())), std::make_pair("parameters", toJson(_node.parameterList())), std::make_pair("virtual", _node.markedVirtual()), std::make_pair("overrides", _node.overrides() ? toJson(*_node.overrides()) : Json()), std::make_pair("body", _node.isImplemented() ? toJson(_node.body()) : Json()) }; if (!_node.annotation().baseFunctions.empty()) attributes.emplace_back(std::make_pair("baseModifiers", getContainerIds(_node.annotation().baseFunctions, true))); setJsonNode(_node, "ModifierDefinition", std::move(attributes)); return false; } bool ASTJsonExporter::visit(ModifierInvocation const& _node) { std::vector<std::pair<std::string, Json>> attributes{ std::make_pair("modifierName", toJson(_node.name())), std::make_pair("arguments", _node.arguments() ? toJson(*_node.arguments()) : Json()) }; if (Declaration const* declaration = _node.name().annotation().referencedDeclaration) { if (dynamic_cast<ModifierDefinition const*>(declaration)) attributes.emplace_back("kind", "modifierInvocation"); else if (dynamic_cast<ContractDefinition const*>(declaration)) attributes.emplace_back("kind", "baseConstructorSpecifier"); } setJsonNode(_node, "ModifierInvocation", std::move(attributes)); return false; } bool ASTJsonExporter::visit(EventDefinition const& _node) { m_inEvent = true; std::vector<std::pair<std::string, Json>> _attributes = { std::make_pair("name", _node.name()), std::make_pair("nameLocation", sourceLocationToString(_node.nameLocation())), std::make_pair("documentation", _node.documentation() ? toJson(*_node.documentation()) : Json()), std::make_pair("parameters", toJson(_node.parameterList())), std::make_pair("anonymous", _node.isAnonymous()) }; if (m_stackState >= CompilerStack::State::AnalysisSuccessful) _attributes.emplace_back( std::make_pair( "eventSelector", toHex(u256(util::h256::Arith(util::keccak256(_node.functionType(true)->externalSignature())))) )); setJsonNode(_node, "EventDefinition", std::move(_attributes)); return false; } bool ASTJsonExporter::visit(ErrorDefinition const& _node) { std::vector<std::pair<std::string, Json>> _attributes = { std::make_pair("name", _node.name()), std::make_pair("nameLocation", sourceLocationToString(_node.nameLocation())), std::make_pair("documentation", _node.documentation() ? toJson(*_node.documentation()) : Json()), std::make_pair("parameters", toJson(_node.parameterList())) }; if (m_stackState >= CompilerStack::State::AnalysisSuccessful) _attributes.emplace_back(std::make_pair("errorSelector", _node.functionType(true)->externalIdentifierHex())); setJsonNode(_node, "ErrorDefinition", std::move(_attributes)); return false; } bool ASTJsonExporter::visit(ElementaryTypeName const& _node) { std::vector<std::pair<std::string, Json>> attributes = { std::make_pair("name", _node.typeName().toString()), std::make_pair("typeDescriptions", typePointerToJson(_node.annotation().type, true)) }; if (_node.stateMutability()) attributes.emplace_back(std::make_pair("stateMutability", stateMutabilityToString(*_node.stateMutability()))); setJsonNode(_node, "ElementaryTypeName", std::move(attributes)); return false; } bool ASTJsonExporter::visit(UserDefinedTypeName const& _node) { setJsonNode(_node, "UserDefinedTypeName", { std::make_pair("pathNode", toJson(_node.pathNode())), std::make_pair("referencedDeclaration", idOrNull(_node.pathNode().annotation().referencedDeclaration)), std::make_pair("typeDescriptions", typePointerToJson(_node.annotation().type, true)) }); return false; } bool ASTJsonExporter::visit(FunctionTypeName const& _node) { setJsonNode(_node, "FunctionTypeName", { std::make_pair("visibility", Declaration::visibilityToString(_node.visibility())), std::make_pair("stateMutability", stateMutabilityToString(_node.stateMutability())), std::make_pair("parameterTypes", toJson(*_node.parameterTypeList())), std::make_pair("returnParameterTypes", toJson(*_node.returnParameterTypeList())), std::make_pair("typeDescriptions", typePointerToJson(_node.annotation().type, true)) }); return false; } bool ASTJsonExporter::visit(Mapping const& _node) { setJsonNode(_node, "Mapping", { std::make_pair("keyType", toJson(_node.keyType())), std::make_pair("keyName", _node.keyName()), std::make_pair("keyNameLocation", sourceLocationToString(_node.keyNameLocation())), std::make_pair("valueType", toJson(_node.valueType())), std::make_pair("valueName", _node.valueName()), std::make_pair("valueNameLocation", sourceLocationToString(_node.valueNameLocation())), std::make_pair("typeDescriptions", typePointerToJson(_node.annotation().type, true)) }); return false; } bool ASTJsonExporter::visit(ArrayTypeName const& _node) { setJsonNode(_node, "ArrayTypeName", { std::make_pair("baseType", toJson(_node.baseType())), std::make_pair("length", toJsonOrNull(_node.length())), std::make_pair("typeDescriptions", typePointerToJson(_node.annotation().type, true)) }); return false; } bool ASTJsonExporter::visit(InlineAssembly const& _node) { std::vector<std::pair<std::string, Json>> externalReferences; for (auto const& it: _node.annotation().externalReferences) if (it.first) externalReferences.emplace_back(std::make_pair( it.first->name.str(), inlineAssemblyIdentifierToJson(it) )); Json externalReferencesJson = Json::array(); std::sort(externalReferences.begin(), externalReferences.end()); for (Json& it: externalReferences | ranges::views::values) externalReferencesJson.emplace_back(std::move(it)); auto const& evmDialect = dynamic_cast<solidity::yul::EVMDialect const&>(_node.dialect()); std::vector<std::pair<std::string, Json>> attributes = { std::make_pair("AST", Json(yul::AsmJsonConverter(evmDialect, sourceIndexFromLocation(_node.location()))(_node.operations().root()))), std::make_pair("externalReferences", std::move(externalReferencesJson)), std::make_pair("evmVersion", evmDialect.evmVersion().name()) }; // TODO: Add test in test/linsolidity/ASTJSON/assembly. This requires adding support for eofVersion in ASTJSONTest if (evmDialect.eofVersion()) { solAssert(*evmDialect.eofVersion() > 0); attributes.push_back(std::make_pair("eofVersion", *evmDialect.eofVersion())); } if (_node.flags()) { Json flags = Json::array(); for (auto const& flag: *_node.flags()) if (flag) flags.emplace_back(*flag); else flags.emplace_back(Json()); attributes.emplace_back(std::make_pair("flags", std::move(flags))); } setJsonNode(_node, "InlineAssembly", std::move(attributes)); return false; } bool ASTJsonExporter::visit(Block const& _node) { setJsonNode(_node, _node.unchecked() ? "UncheckedBlock" : "Block", { std::make_pair("statements", toJson(_node.statements())) }); return false; } bool ASTJsonExporter::visit(PlaceholderStatement const& _node) { setJsonNode(_node, "PlaceholderStatement", {}); return false; } bool ASTJsonExporter::visit(IfStatement const& _node) { setJsonNode(_node, "IfStatement", { std::make_pair("condition", toJson(_node.condition())), std::make_pair("trueBody", toJson(_node.trueStatement())), std::make_pair("falseBody", toJsonOrNull(_node.falseStatement())) }); return false; } bool ASTJsonExporter::visit(TryCatchClause const& _node) { setJsonNode(_node, "TryCatchClause", { std::make_pair("errorName", _node.errorName()), std::make_pair("parameters", toJsonOrNull(_node.parameters())), std::make_pair("block", toJson(_node.block())) }); return false; } bool ASTJsonExporter::visit(TryStatement const& _node) { setJsonNode(_node, "TryStatement", { std::make_pair("externalCall", toJson(_node.externalCall())), std::make_pair("clauses", toJson(_node.clauses())) }); return false; } bool ASTJsonExporter::visit(WhileStatement const& _node) { setJsonNode( _node, _node.isDoWhile() ? "DoWhileStatement" : "WhileStatement", { std::make_pair("condition", toJson(_node.condition())), std::make_pair("body", toJson(_node.body())) } ); return false; } bool ASTJsonExporter::visit(ForStatement const& _node) { std::vector<std::pair<std::string, Json>> attributes = { std::make_pair("initializationExpression", toJsonOrNull(_node.initializationExpression())), std::make_pair("condition", toJsonOrNull(_node.condition())), std::make_pair("loopExpression", toJsonOrNull(_node.loopExpression())), std::make_pair("body", toJson(_node.body())) }; if (_node.annotation().isSimpleCounterLoop.set()) attributes.emplace_back("isSimpleCounterLoop", *_node.annotation().isSimpleCounterLoop); setJsonNode(_node, "ForStatement", std::move(attributes)); return false; } bool ASTJsonExporter::visit(Continue const& _node) { setJsonNode(_node, "Continue", {}); return false; } bool ASTJsonExporter::visit(Break const& _node) { setJsonNode(_node, "Break", {}); return false; } bool ASTJsonExporter::visit(Return const& _node) { setJsonNode(_node, "Return", { std::make_pair("expression", toJsonOrNull(_node.expression())), std::make_pair("functionReturnParameters", idOrNull(_node.annotation().functionReturnParameters)) }); return false; } bool ASTJsonExporter::visit(Throw const& _node) { setJsonNode(_node, "Throw", {}); return false; } bool ASTJsonExporter::visit(EmitStatement const& _node) { setJsonNode(_node, "EmitStatement", { std::make_pair("eventCall", toJson(_node.eventCall())) }); return false; } bool ASTJsonExporter::visit(RevertStatement const& _node) { setJsonNode(_node, "RevertStatement", { std::make_pair("errorCall", toJson(_node.errorCall())) }); return false; } bool ASTJsonExporter::visit(VariableDeclarationStatement const& _node) { Json varDecs = Json::array(); for (auto const& v: _node.declarations()) appendMove(varDecs, idOrNull(v.get())); setJsonNode(_node, "VariableDeclarationStatement", { std::make_pair("assignments", std::move(varDecs)), std::make_pair("declarations", toJson(_node.declarations())), std::make_pair("initialValue", toJsonOrNull(_node.initialValue())) }); return false; } bool ASTJsonExporter::visit(ExpressionStatement const& _node) { setJsonNode(_node, "ExpressionStatement", { std::make_pair("expression", toJson(_node.expression())) }); return false; } bool ASTJsonExporter::visit(Conditional const& _node) { std::vector<std::pair<std::string, Json>> attributes = { std::make_pair("condition", toJson(_node.condition())), std::make_pair("trueExpression", toJson(_node.trueExpression())), std::make_pair("falseExpression", toJson(_node.falseExpression())) }; appendExpressionAttributes(attributes, _node.annotation()); setJsonNode(_node, "Conditional", std::move(attributes)); return false; } bool ASTJsonExporter::visit(Assignment const& _node) { std::vector<std::pair<std::string, Json>> attributes = { std::make_pair("operator", TokenTraits::toString(_node.assignmentOperator())), std::make_pair("leftHandSide", toJson(_node.leftHandSide())), std::make_pair("rightHandSide", toJson(_node.rightHandSide())) }; appendExpressionAttributes(attributes, _node.annotation()); setJsonNode(_node, "Assignment", std::move(attributes)); return false; } bool ASTJsonExporter::visit(TupleExpression const& _node) { std::vector<std::pair<std::string, Json>> attributes = { std::make_pair("isInlineArray", Json(_node.isInlineArray())), std::make_pair("components", toJson(_node.components())), }; appendExpressionAttributes(attributes, _node.annotation()); setJsonNode(_node, "TupleExpression", std::move(attributes)); return false; } bool ASTJsonExporter::visit(UnaryOperation const& _node) { std::vector<std::pair<std::string, Json>> attributes = { std::make_pair("prefix", _node.isPrefixOperation()), std::make_pair("operator", TokenTraits::toString(_node.getOperator())), std::make_pair("subExpression", toJson(_node.subExpression())) }; // NOTE: This annotation is guaranteed to be set but only if we didn't stop at the parsing stage. if (_node.annotation().userDefinedFunction.set() && *_node.annotation().userDefinedFunction != nullptr) attributes.emplace_back("function", nodeId(**_node.annotation().userDefinedFunction)); appendExpressionAttributes(attributes, _node.annotation()); setJsonNode(_node, "UnaryOperation", std::move(attributes)); return false; } bool ASTJsonExporter::visit(BinaryOperation const& _node) { std::vector<std::pair<std::string, Json>> attributes = { std::make_pair("operator", TokenTraits::toString(_node.getOperator())), std::make_pair("leftExpression", toJson(_node.leftExpression())), std::make_pair("rightExpression", toJson(_node.rightExpression())), std::make_pair("commonType", typePointerToJson(_node.annotation().commonType)), }; // NOTE: This annotation is guaranteed to be set but only if we didn't stop at the parsing stage. if (_node.annotation().userDefinedFunction.set() && *_node.annotation().userDefinedFunction != nullptr) attributes.emplace_back("function", nodeId(**_node.annotation().userDefinedFunction)); appendExpressionAttributes(attributes, _node.annotation()); setJsonNode(_node, "BinaryOperation", std::move(attributes)); return false; } bool ASTJsonExporter::visit(FunctionCall const& _node) { Json names = Json::array(); for (auto const& name: _node.names()) names.push_back(Json(*name)); std::vector<std::pair<std::string, Json>> attributes = { std::make_pair("expression", toJson(_node.expression())), std::make_pair("names", std::move(names)), std::make_pair("nameLocations", sourceLocationsToJson(_node.nameLocations())), std::make_pair("arguments", toJson(_node.arguments())), std::make_pair("tryCall", _node.annotation().tryCall) }; if (_node.annotation().kind.set()) { FunctionCallKind nodeKind = *_node.annotation().kind; attributes.emplace_back("kind", functionCallKind(nodeKind)); } appendExpressionAttributes(attributes, _node.annotation()); setJsonNode(_node, "FunctionCall", std::move(attributes)); return false; } bool ASTJsonExporter::visit(FunctionCallOptions const& _node) { Json names = Json::array(); for (auto const& name: _node.names()) names.emplace_back(Json(*name)); std::vector<std::pair<std::string, Json>> attributes = { std::make_pair("expression", toJson(_node.expression())), std::make_pair("names", std::move(names)), std::make_pair("options", toJson(_node.options())), }; appendExpressionAttributes(attributes, _node.annotation()); setJsonNode(_node, "FunctionCallOptions", std::move(attributes)); return false; } bool ASTJsonExporter::visit(NewExpression const& _node) { std::vector<std::pair<std::string, Json>> attributes = { std::make_pair("typeName", toJson(_node.typeName())) }; appendExpressionAttributes(attributes, _node.annotation()); setJsonNode(_node, "NewExpression", std::move(attributes)); return false; } bool ASTJsonExporter::visit(MemberAccess const& _node) { std::vector<std::pair<std::string, Json>> attributes = { std::make_pair("memberName", _node.memberName()), std::make_pair("memberLocation", Json(sourceLocationToString(_node.memberLocation()))), std::make_pair("expression", toJson(_node.expression())), std::make_pair("referencedDeclaration", idOrNull(_node.annotation().referencedDeclaration)), }; appendExpressionAttributes(attributes, _node.annotation()); setJsonNode(_node, "MemberAccess", std::move(attributes)); return false; } bool ASTJsonExporter::visit(IndexAccess const& _node) { std::vector<std::pair<std::string, Json>> attributes = { std::make_pair("baseExpression", toJson(_node.baseExpression())), std::make_pair("indexExpression", toJsonOrNull(_node.indexExpression())), }; appendExpressionAttributes(attributes, _node.annotation()); setJsonNode(_node, "IndexAccess", std::move(attributes)); return false; } bool ASTJsonExporter::visit(IndexRangeAccess const& _node) { std::vector<std::pair<std::string, Json>> attributes = { std::make_pair("baseExpression", toJson(_node.baseExpression())), std::make_pair("startExpression", toJsonOrNull(_node.startExpression())), std::make_pair("endExpression", toJsonOrNull(_node.endExpression())), }; appendExpressionAttributes(attributes, _node.annotation()); setJsonNode(_node, "IndexRangeAccess", std::move(attributes)); return false; } bool ASTJsonExporter::visit(Identifier const& _node) { Json overloads = Json::array(); for (auto const& dec: _node.annotation().overloadedDeclarations) overloads.emplace_back(nodeId(*dec)); setJsonNode(_node, "Identifier", { std::make_pair("name", _node.name()), std::make_pair("referencedDeclaration", idOrNull(_node.annotation().referencedDeclaration)), std::make_pair("overloadedDeclarations", overloads), std::make_pair("typeDescriptions", typePointerToJson(_node.annotation().type)), std::make_pair("argumentTypes", typePointerToJson(_node.annotation().arguments)) }); return false; } bool ASTJsonExporter::visit(ElementaryTypeNameExpression const& _node) { std::vector<std::pair<std::string, Json>> attributes = { std::make_pair("typeName", toJson(_node.type())) }; appendExpressionAttributes(attributes, _node.annotation()); setJsonNode(_node, "ElementaryTypeNameExpression", std::move(attributes)); return false; } bool ASTJsonExporter::visit(Literal const& _node) { Json value = _node.value(); if (!util::validateUTF8(_node.value())) value = Json(); Token subdenomination = Token(_node.subDenomination()); std::vector<std::pair<std::string, Json>> attributes = { std::make_pair("kind", literalTokenKind(_node.token())), std::make_pair("value", value), std::make_pair("hexValue", util::toHex(util::asBytes(_node.value()))), std::make_pair( "subdenomination", subdenomination == Token::Illegal ? Json() : Json(TokenTraits::toString(subdenomination)) ) }; appendExpressionAttributes(attributes, _node.annotation()); setJsonNode(_node, "Literal", std::move(attributes)); return false; } bool ASTJsonExporter::visit(StructuredDocumentation const& _node) { Json text = *_node.text(); std::vector<std::pair<std::string, Json>> attributes = { std::make_pair("text", text) }; setJsonNode(_node, "StructuredDocumentation", std::move(attributes)); return false; } void ASTJsonExporter::endVisit(EventDefinition const&) { m_inEvent = false; } bool ASTJsonExporter::visitNode(ASTNode const& _node) { solAssert(false, _node.experimentalSolidityOnly() ? "Attempt to export an AST of experimental solidity." : "Attempt to export an AST that contains unexpected nodes." ); return false; } std::string ASTJsonExporter::location(VariableDeclaration::Location _location) { switch (_location) { case VariableDeclaration::Location::Unspecified: return "default"; case VariableDeclaration::Location::Storage: return "storage"; case VariableDeclaration::Location::Memory: return "memory"; case VariableDeclaration::Location::CallData: return "calldata"; case VariableDeclaration::Location::Transient: return "transient"; } // To make the compiler happy return {}; } std::string ASTJsonExporter::contractKind(ContractKind _kind) { switch (_kind) { case ContractKind::Interface: return "interface"; case ContractKind::Contract: return "contract"; case ContractKind::Library: return "library"; } // To make the compiler happy return {}; } std::string ASTJsonExporter::functionCallKind(FunctionCallKind _kind) { switch (_kind) { case FunctionCallKind::FunctionCall: return "functionCall"; case FunctionCallKind::TypeConversion: return "typeConversion"; case FunctionCallKind::StructConstructorCall: return "structConstructorCall"; default: solAssert(false, "Unknown kind of function call."); } } std::string ASTJsonExporter::literalTokenKind(Token _token) { switch (_token) { case Token::Number: return "number"; case Token::StringLiteral: return "string"; case Token::UnicodeStringLiteral: return "unicodeString"; case Token::HexStringLiteral: return "hexString"; case Token::TrueLiteral: case Token::FalseLiteral: return "bool"; default: solAssert(false, "Unknown kind of literal token."); } } std::string ASTJsonExporter::type(Expression const& _expression) { return _expression.annotation().type ? _expression.annotation().type->toString() : "Unknown"; } std::string ASTJsonExporter::type(VariableDeclaration const& _varDecl) { return _varDecl.annotation().type ? _varDecl.annotation().type->toString() : "Unknown"; } }
38,869
C++
.cpp
988
37.086032
156
0.74289
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
3,244
ASTUtils.cpp
ethereum_solidity/libsolidity/ast/ASTUtils.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libsolidity/ast/AST.h> #include <libsolidity/ast/ASTUtils.h> #include <libsolidity/ast/ASTVisitor.h> #include <libsolutil/Algorithms.h> namespace solidity::frontend { ASTNode const* locateInnermostASTNode(int _offsetInFile, SourceUnit const& _sourceUnit) { ASTNode const* innermostMatch = nullptr; auto locator = SimpleASTVisitor( [&](ASTNode const& _node) -> bool { // In the AST parent location always covers the whole child location. // The parent is visited first so to get the innermost node we simply // take the last one that still contains the offset. if (!_node.location().containsOffset(_offsetInFile)) return false; innermostMatch = &_node; return true; }, [](ASTNode const&) {} ); _sourceUnit.accept(locator); return innermostMatch; } bool isConstantVariableRecursive(VariableDeclaration const& _varDecl) { solAssert(_varDecl.isConstant(), "Constant variable expected"); auto visitor = [](VariableDeclaration const& _variable, util::CycleDetector<VariableDeclaration>& _cycleDetector, size_t _depth) { solAssert(_depth < 256, "Recursion depth limit reached"); if (!_variable.value()) // This should result in an error later on. return; if (auto referencedVarDecl = dynamic_cast<VariableDeclaration const*>( ASTNode::referencedDeclaration(*_variable.value())) ) if (referencedVarDecl->isConstant()) _cycleDetector.run(*referencedVarDecl); }; return util::CycleDetector<VariableDeclaration>(visitor).run(_varDecl) != nullptr; } VariableDeclaration const* rootConstVariableDeclaration(VariableDeclaration const& _varDecl) { solAssert(_varDecl.isConstant(), "Constant variable expected"); solAssert(!isConstantVariableRecursive(_varDecl), "Recursive declaration"); VariableDeclaration const* rootDecl = &_varDecl; Identifier const* identifier; while ((identifier = dynamic_cast<Identifier const*>(rootDecl->value().get()))) { auto referencedVarDecl = dynamic_cast<VariableDeclaration const*>(identifier->annotation().referencedDeclaration); if (!referencedVarDecl || !referencedVarDecl->isConstant()) return nullptr; rootDecl = referencedVarDecl; } return rootDecl; } Expression const* resolveOuterUnaryTuples(Expression const* _expr) { while (auto const* tupleExpression = dynamic_cast<TupleExpression const*>(_expr)) if (tupleExpression->components().size() == 1) _expr = tupleExpression->components().front().get(); else break; return _expr; } Type const* type(Expression const& _expression) { solAssert(!!_expression.annotation().type, "Type requested but not present."); return _expression.annotation().type; } Type const* type(VariableDeclaration const& _variable) { solAssert(!!_variable.annotation().type, "Type requested but not present."); return _variable.annotation().type; } }
3,506
C++
.cpp
91
36.131868
129
0.771201
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,245
AST.cpp
ethereum_solidity/libsolidity/ast/AST.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 /** * @author Christian <c@ethdev.com> * @date 2014 * Solidity abstract syntax tree. */ #include <libsolidity/ast/AST.h> #include <libsolidity/ast/CallGraph.h> #include <libsolidity/ast/ASTVisitor.h> #include <libsolidity/ast/AST_accept.h> #include <libsolidity/ast/TypeProvider.h> #include <libsolutil/FunctionSelector.h> #include <libsolutil/Keccak256.h> #include <range/v3/range/conversion.hpp> #include <range/v3/view/tail.hpp> #include <range/v3/view/zip.hpp> #include <boost/algorithm/string.hpp> #include <functional> #include <utility> using namespace solidity; using namespace solidity::frontend; namespace { TryCatchClause const* findClause(std::vector<ASTPointer<TryCatchClause>> const& _clauses, std::optional<std::string> _errorName = {}) { for (auto const& clause: ranges::views::tail(_clauses)) if (_errorName.has_value() ? clause->errorName() == _errorName : clause->errorName().empty()) return clause.get(); return nullptr; } } ASTNode::ASTNode(int64_t _id, SourceLocation _location): m_id(static_cast<size_t>(_id)), m_location(std::move(_location)) { } Declaration const* ASTNode::referencedDeclaration(Expression const& _expression) { if (auto const* memberAccess = dynamic_cast<MemberAccess const*>(&_expression)) return memberAccess->annotation().referencedDeclaration; else if (auto const* identifierPath = dynamic_cast<IdentifierPath const*>(&_expression)) return identifierPath->annotation().referencedDeclaration; else if (auto const* identifier = dynamic_cast<Identifier const*>(&_expression)) return identifier->annotation().referencedDeclaration; else return nullptr; } FunctionDefinition const* ASTNode::resolveFunctionCall(FunctionCall const& _functionCall, ContractDefinition const* _mostDerivedContract) { auto const* functionDef = dynamic_cast<FunctionDefinition const*>( ASTNode::referencedDeclaration(_functionCall.expression()) ); if (!functionDef) return nullptr; if (auto const* memberAccess = dynamic_cast<MemberAccess const*>(&_functionCall.expression())) { if (*memberAccess->annotation().requiredLookup == VirtualLookup::Super) { if (auto const typeType = dynamic_cast<TypeType const*>(memberAccess->expression().annotation().type)) if (auto const contractType = dynamic_cast<ContractType const*>(typeType->actualType())) { solAssert(_mostDerivedContract, ""); solAssert(contractType->isSuper(), ""); ContractDefinition const* superContract = contractType->contractDefinition().superContract(*_mostDerivedContract); return &functionDef->resolveVirtual( *_mostDerivedContract, superContract ); } } else solAssert(*memberAccess->annotation().requiredLookup == VirtualLookup::Static, ""); } else if (auto const* identifier = dynamic_cast<Identifier const*>(&_functionCall.expression())) { solAssert(*identifier->annotation().requiredLookup == VirtualLookup::Virtual, ""); if (functionDef->virtualSemantics()) { solAssert(_mostDerivedContract, ""); return &functionDef->resolveVirtual(*_mostDerivedContract); } } else solAssert(false, ""); return functionDef; } ASTAnnotation& ASTNode::annotation() const { if (!m_annotation) m_annotation = std::make_unique<ASTAnnotation>(); return *m_annotation; } SourceUnitAnnotation& SourceUnit::annotation() const { return initAnnotation<SourceUnitAnnotation>(); } std::set<SourceUnit const*> SourceUnit::referencedSourceUnits(bool _recurse, std::set<SourceUnit const*> _skipList) const { std::set<SourceUnit const*> sourceUnits; for (ImportDirective const* importDirective: filteredNodes<ImportDirective>(nodes())) { auto const& sourceUnit = importDirective->annotation().sourceUnit; if (!_skipList.count(sourceUnit)) { _skipList.insert(sourceUnit); sourceUnits.insert(sourceUnit); if (_recurse) sourceUnits += sourceUnit->referencedSourceUnits(true, _skipList); } } return sourceUnits; } ImportAnnotation& ImportDirective::annotation() const { return initAnnotation<ImportAnnotation>(); } Type const* ImportDirective::type() const { solAssert(!!annotation().sourceUnit, ""); return TypeProvider::module(*annotation().sourceUnit); } bool ContractDefinition::derivesFrom(ContractDefinition const& _base) const { return util::contains(annotation().linearizedBaseContracts, &_base); } std::map<util::FixedHash<4>, FunctionTypePointer> ContractDefinition::interfaceFunctions(bool _includeInheritedFunctions) const { auto exportedFunctionList = interfaceFunctionList(_includeInheritedFunctions); std::map<util::FixedHash<4>, FunctionTypePointer> exportedFunctions; for (auto const& it: exportedFunctionList) exportedFunctions.insert(it); solAssert( exportedFunctionList.size() == exportedFunctions.size(), "Hash collision at Function Definition Hash calculation" ); return exportedFunctions; } FunctionDefinition const* ContractDefinition::constructor() const { for (FunctionDefinition const* f: definedFunctions()) if (f->isConstructor()) return f; return nullptr; } bool ContractDefinition::canBeDeployed() const { return !abstract() && !isInterface(); } FunctionDefinition const* ContractDefinition::fallbackFunction() const { for (ContractDefinition const* contract: annotation().linearizedBaseContracts) for (FunctionDefinition const* f: contract->definedFunctions()) if (f->isFallback()) return f; return nullptr; } FunctionDefinition const* ContractDefinition::receiveFunction() const { for (ContractDefinition const* contract: annotation().linearizedBaseContracts) for (FunctionDefinition const* f: contract->definedFunctions()) if (f->isReceive()) return f; return nullptr; } std::vector<EventDefinition const*> const& ContractDefinition::definedInterfaceEvents() const { return m_interfaceEvents.init([&]{ std::set<std::string> eventsSeen; std::vector<EventDefinition const*> interfaceEvents; for (ContractDefinition const* contract: annotation().linearizedBaseContracts) for (EventDefinition const* e: contract->events()) { /// NOTE: this requires the "internal" version of an Event, /// though here internal strictly refers to visibility, /// and not to function encoding (jump vs. call) FunctionType const* functionType = e->functionType(true); solAssert(functionType, ""); std::string eventSignature = functionType->externalSignature(); if (eventsSeen.count(eventSignature) == 0) { eventsSeen.insert(eventSignature); interfaceEvents.push_back(e); } } return interfaceEvents; }); } std::vector<EventDefinition const*> const ContractDefinition::usedInterfaceEvents() const { solAssert(annotation().creationCallGraph.set(), ""); return util::convertContainer<std::vector<EventDefinition const*>>( (*annotation().creationCallGraph)->emittedEvents + (*annotation().deployedCallGraph)->emittedEvents ); } std::vector<EventDefinition const*> ContractDefinition::interfaceEvents(bool _requireCallGraph) const { std::set<EventDefinition const*, CompareByID> result; for (ContractDefinition const* contract: annotation().linearizedBaseContracts) result += contract->events(); solAssert(annotation().creationCallGraph.set() == annotation().deployedCallGraph.set()); if (_requireCallGraph) solAssert(annotation().creationCallGraph.set()); if (annotation().creationCallGraph.set()) result += usedInterfaceEvents(); // We could filter out all events that do not have an external interface // if _requireCallGraph is false. return util::convertContainer<std::vector<EventDefinition const*>>(std::move(result)); } std::vector<ErrorDefinition const*> ContractDefinition::interfaceErrors(bool _requireCallGraph) const { std::set<ErrorDefinition const*, CompareByID> result; for (ContractDefinition const* contract: annotation().linearizedBaseContracts) result += filteredNodes<ErrorDefinition>(contract->m_subNodes); solAssert(annotation().creationCallGraph.set() == annotation().deployedCallGraph.set(), ""); if (_requireCallGraph) solAssert(annotation().creationCallGraph.set(), ""); if (annotation().creationCallGraph.set()) result += (*annotation().creationCallGraph)->usedErrors + (*annotation().deployedCallGraph)->usedErrors; return util::convertContainer<std::vector<ErrorDefinition const*>>(std::move(result)); } std::vector<std::pair<util::FixedHash<4>, FunctionTypePointer>> const& ContractDefinition::interfaceFunctionList(bool _includeInheritedFunctions) const { return m_interfaceFunctionList[_includeInheritedFunctions].init([&]{ std::set<std::string> signaturesSeen; std::vector<std::pair<util::FixedHash<4>, FunctionTypePointer>> interfaceFunctionList; for (ContractDefinition const* contract: annotation().linearizedBaseContracts) { if (_includeInheritedFunctions == false && contract != this) continue; std::vector<FunctionTypePointer> functions; for (FunctionDefinition const* f: contract->definedFunctions()) if (f->isPartOfExternalInterface()) functions.push_back(TypeProvider::function(*f, FunctionType::Kind::External)); for (VariableDeclaration const* v: contract->stateVariables()) if (v->isPartOfExternalInterface()) functions.push_back(TypeProvider::function(*v)); for (FunctionTypePointer const& fun: functions) { if (!fun->interfaceFunctionType()) // Fails hopefully because we already registered the error continue; std::string functionSignature = fun->externalSignature(); if (signaturesSeen.count(functionSignature) == 0) { signaturesSeen.insert(functionSignature); interfaceFunctionList.emplace_back(util::selectorFromSignatureH32(functionSignature), fun); } } } return interfaceFunctionList; }); } uint32_t ContractDefinition::interfaceId() const { uint32_t result{0}; for (auto const& function: interfaceFunctionList(false)) result ^= fromBigEndian<uint32_t>(function.first.ref()); return result; } Type const* ContractDefinition::type() const { return TypeProvider::typeType(TypeProvider::contract(*this)); } ContractDefinitionAnnotation& ContractDefinition::annotation() const { return initAnnotation<ContractDefinitionAnnotation>(); } ContractDefinition const* ContractDefinition::superContract(ContractDefinition const& _mostDerivedContract) const { auto const& hierarchy = _mostDerivedContract.annotation().linearizedBaseContracts; auto it = find(hierarchy.begin(), hierarchy.end(), this); solAssert(it != hierarchy.end(), "Base not found in inheritance hierarchy."); ++it; if (it == hierarchy.end()) return nullptr; else { solAssert(*it != this, ""); return *it; } } FunctionDefinition const* ContractDefinition::nextConstructor(ContractDefinition const& _mostDerivedContract) const { ContractDefinition const* next = superContract(_mostDerivedContract); if (next == nullptr) return nullptr; for (ContractDefinition const* c: _mostDerivedContract.annotation().linearizedBaseContracts) if (c == next || next == nullptr) { if (c->constructor()) return c->constructor(); next = nullptr; } return nullptr; } std::multimap<std::string, FunctionDefinition const*> const& ContractDefinition::definedFunctionsByName() const { return m_definedFunctionsByName.init([&]{ std::multimap<std::string, FunctionDefinition const*> result; for (FunctionDefinition const* fun: filteredNodes<FunctionDefinition>(m_subNodes)) result.insert({fun->name(), fun}); return result; }); } TypeNameAnnotation& TypeName::annotation() const { return initAnnotation<TypeNameAnnotation>(); } Type const* UserDefinedValueTypeDefinition::type() const { solAssert(m_underlyingType->annotation().type, ""); return TypeProvider::typeType(TypeProvider::userDefinedValueType(*this)); } TypeDeclarationAnnotation& UserDefinedValueTypeDefinition::annotation() const { return initAnnotation<TypeDeclarationAnnotation>(); } std::vector<std::pair<ASTPointer<IdentifierPath>, std::optional<Token>>> UsingForDirective::functionsAndOperators() const { return ranges::zip_view(m_functionsOrLibrary, m_operators) | ranges::to<std::vector>; } Type const* StructDefinition::type() const { solAssert(annotation().recursive.has_value(), "Requested struct type before DeclarationTypeChecker."); return TypeProvider::typeType(TypeProvider::structType(*this, DataLocation::Storage)); } StructDeclarationAnnotation& StructDefinition::annotation() const { return initAnnotation<StructDeclarationAnnotation>(); } Type const* EnumValue::type() const { auto parentDef = dynamic_cast<EnumDefinition const*>(scope()); solAssert(parentDef, "Enclosing Scope of EnumValue was not set"); return TypeProvider::enumType(*parentDef); } Type const* EnumDefinition::type() const { return TypeProvider::typeType(TypeProvider::enumType(*this)); } TypeDeclarationAnnotation& EnumDefinition::annotation() const { return initAnnotation<TypeDeclarationAnnotation>(); } bool FunctionDefinition::libraryFunction() const { if (auto const* contractDef = dynamic_cast<ContractDefinition const*>(scope())) return contractDef->isLibrary(); return false; } Visibility FunctionDefinition::defaultVisibility() const { solAssert(!isConstructor(), ""); return isFree() ? Visibility::Internal : Declaration::defaultVisibility(); } FunctionTypePointer FunctionDefinition::functionType(bool _internal) const { if (_internal) { switch (visibility()) { case Visibility::Default: solAssert(false, "visibility() should not return Default"); case Visibility::Private: case Visibility::Internal: case Visibility::Public: return TypeProvider::function(*this, FunctionType::Kind::Internal); case Visibility::External: return {}; } } else { switch (visibility()) { case Visibility::Default: solAssert(false, "visibility() should not return Default"); case Visibility::Private: case Visibility::Internal: return {}; case Visibility::Public: case Visibility::External: return TypeProvider::function(*this, FunctionType::Kind::External); } } // To make the compiler happy return {}; } Type const* FunctionDefinition::type() const { solAssert(visibility() != Visibility::External, ""); return TypeProvider::function(*this, FunctionType::Kind::Internal); } Type const* FunctionDefinition::typeViaContractName() const { if (libraryFunction()) { if (isPublic()) return FunctionType(*this).asExternallyCallableFunction(true); else return TypeProvider::function(*this, FunctionType::Kind::Internal); } else return TypeProvider::function(*this, FunctionType::Kind::Declaration); } std::string FunctionDefinition::externalSignature() const { return TypeProvider::function(*this)->externalSignature(); } std::string FunctionDefinition::externalIdentifierHex() const { return TypeProvider::function(*this)->externalIdentifierHex(); } FunctionDefinitionAnnotation& FunctionDefinition::annotation() const { return initAnnotation<FunctionDefinitionAnnotation>(); } FunctionDefinition const& FunctionDefinition::resolveVirtual( ContractDefinition const& _mostDerivedContract, ContractDefinition const* _searchStart ) const { solAssert(!isConstructor(), ""); solAssert(!name().empty(), ""); // If we are not doing super-lookup and the function is not virtual, we can stop here. if (_searchStart == nullptr && !virtualSemantics()) return *this; solAssert(!isFree(), ""); solAssert(isOrdinary(), ""); solAssert(!libraryFunction(), ""); // We actually do not want the externally callable function here. // This is just to add an assertion since the comparison used to be less strict. FunctionType const* externalFunctionType = TypeProvider::function(*this)->asExternallyCallableFunction(false); bool foundSearchStart = (_searchStart == nullptr); for (ContractDefinition const* c: _mostDerivedContract.annotation().linearizedBaseContracts) { if (!foundSearchStart && c != _searchStart) continue; else foundSearchStart = true; for (FunctionDefinition const* function: c->definedFunctions(name())) if ( // With super lookup analysis guarantees that there is an implemented function in the chain. // With virtual lookup there are valid cases where returning an unimplemented one is fine. (function->isImplemented() || _searchStart == nullptr) && FunctionType(*function).asExternallyCallableFunction(false)->hasEqualParameterTypes(*externalFunctionType) ) { solAssert(FunctionType(*function).hasEqualParameterTypes(*TypeProvider::function(*this))); return *function; } } solAssert(false, "Virtual function " + name() + " not found."); return *this; // not reached } Type const* ModifierDefinition::type() const { return TypeProvider::modifier(*this); } ModifierDefinitionAnnotation& ModifierDefinition::annotation() const { return initAnnotation<ModifierDefinitionAnnotation>(); } ModifierDefinition const& ModifierDefinition::resolveVirtual( ContractDefinition const& _mostDerivedContract, ContractDefinition const* _searchStart ) const { // Super is not possible with modifiers solAssert(_searchStart == nullptr, "Used super in connection with modifiers."); // The modifier is not virtual, we can stop here. if (!virtualSemantics()) return *this; solAssert(!dynamic_cast<ContractDefinition const&>(*scope()).isLibrary(), ""); for (ContractDefinition const* c: _mostDerivedContract.annotation().linearizedBaseContracts) for (ModifierDefinition const* modifier: c->functionModifiers()) if (modifier->name() == name()) return *modifier; solAssert(false, "Virtual modifier " + name() + " not found."); return *this; // not reached } Type const* EventDefinition::type() const { return TypeProvider::function(*this); } FunctionTypePointer EventDefinition::functionType(bool _internal) const { if (_internal) return TypeProvider::function(*this); else return nullptr; } EventDefinitionAnnotation& EventDefinition::annotation() const { return initAnnotation<EventDefinitionAnnotation>(); } Type const* ErrorDefinition::type() const { return TypeProvider::function(*this); } FunctionTypePointer ErrorDefinition::functionType(bool _internal) const { if (_internal) return TypeProvider::function(*this); else return nullptr; } ErrorDefinitionAnnotation& ErrorDefinition::annotation() const { return initAnnotation<ErrorDefinitionAnnotation>(); } SourceUnit const& Scopable::sourceUnit() const { ASTNode const* s = scope(); solAssert(s, ""); // will not always be a declaration while (dynamic_cast<Scopable const*>(s) && dynamic_cast<Scopable const*>(s)->scope()) s = dynamic_cast<Scopable const*>(s)->scope(); return dynamic_cast<SourceUnit const&>(*s); } CallableDeclaration const* Scopable::functionOrModifierDefinition() const { ASTNode const* s = scope(); solAssert(s, ""); while (dynamic_cast<Scopable const*>(s)) { if (auto funDef = dynamic_cast<FunctionDefinition const*>(s)) return funDef; if (auto modDef = dynamic_cast<ModifierDefinition const*>(s)) return modDef; s = dynamic_cast<Scopable const*>(s)->scope(); } return nullptr; } std::string Scopable::sourceUnitName() const { return *sourceUnit().annotation().path; } bool Declaration::isEnumValue() const { solAssert(scope(), ""); return dynamic_cast<EnumDefinition const*>(scope()); } bool Declaration::isStructMember() const { solAssert(scope(), ""); return dynamic_cast<StructDefinition const*>(scope()); } bool Declaration::isEventOrErrorParameter() const { solAssert(scope(), ""); return dynamic_cast<EventDefinition const*>(scope()) || dynamic_cast<ErrorDefinition const*>(scope()); } bool Declaration::isVisibleAsUnqualifiedName() const { if (!scope()) return true; if (isStructMember() || isEnumValue() || isEventOrErrorParameter()) return false; if (auto const* functionDefinition = dynamic_cast<FunctionDefinition const*>(scope())) if (!functionDefinition->isImplemented()) return false; // parameter of a function without body return true; } DeclarationAnnotation& Declaration::annotation() const { return initAnnotation<DeclarationAnnotation>(); } bool VariableDeclaration::isLValue() const { // Constant declared variables are Read-Only return !isConstant(); } bool VariableDeclaration::isLocalVariable() const { auto s = scope(); return dynamic_cast<FunctionTypeName const*>(s) || dynamic_cast<CallableDeclaration const*>(s) || dynamic_cast<Block const*>(s) || dynamic_cast<TryCatchClause const*>(s) || dynamic_cast<ForStatement const*>(s); } bool VariableDeclaration::isCallableOrCatchParameter() const { if (isReturnParameter() || isTryCatchParameter()) return true; std::vector<ASTPointer<VariableDeclaration>> const* parameters = nullptr; if (auto const* funTypeName = dynamic_cast<FunctionTypeName const*>(scope())) parameters = &funTypeName->parameterTypes(); else if (auto const* callable = dynamic_cast<CallableDeclaration const*>(scope())) parameters = &callable->parameters(); if (parameters) for (auto const& variable: *parameters) if (variable.get() == this) return true; return false; } bool VariableDeclaration::isLocalOrReturn() const { return isReturnParameter() || (isLocalVariable() && !isCallableOrCatchParameter()); } bool VariableDeclaration::isReturnParameter() const { std::vector<ASTPointer<VariableDeclaration>> const* returnParameters = nullptr; if (auto const* funTypeName = dynamic_cast<FunctionTypeName const*>(scope())) returnParameters = &funTypeName->returnParameterTypes(); else if (auto const* callable = dynamic_cast<CallableDeclaration const*>(scope())) if (callable->returnParameterList()) returnParameters = &callable->returnParameterList()->parameters(); if (returnParameters) for (auto const& variable: *returnParameters) if (variable.get() == this) return true; return false; } bool VariableDeclaration::isTryCatchParameter() const { return dynamic_cast<TryCatchClause const*>(scope()); } bool VariableDeclaration::isExternalCallableParameter() const { if (!isCallableOrCatchParameter()) return false; if (auto const* callable = dynamic_cast<CallableDeclaration const*>(scope())) if (callable->visibility() == Visibility::External) return !isReturnParameter(); return false; } bool VariableDeclaration::isPublicCallableParameter() const { if (!isCallableOrCatchParameter()) return false; if (auto const* callable = dynamic_cast<CallableDeclaration const*>(scope())) if (callable->visibility() == Visibility::Public) return !isReturnParameter(); return false; } bool VariableDeclaration::isInternalCallableParameter() const { if (!isCallableOrCatchParameter()) return false; if (auto const* funTypeName = dynamic_cast<FunctionTypeName const*>(scope())) return funTypeName->visibility() == Visibility::Internal; else if (auto const* callable = dynamic_cast<CallableDeclaration const*>(scope())) return callable->visibility() <= Visibility::Internal; return false; } bool VariableDeclaration::isConstructorParameter() const { if (!isCallableOrCatchParameter()) return false; if (auto const* function = dynamic_cast<FunctionDefinition const*>(scope())) return function->isConstructor(); return false; } bool VariableDeclaration::isLibraryFunctionParameter() const { if (!isCallableOrCatchParameter()) return false; if (auto const* funDef = dynamic_cast<FunctionDefinition const*>(scope())) return funDef->libraryFunction(); return false; } bool VariableDeclaration::hasReferenceOrMappingType() const { solAssert(typeName().annotation().type, "Can only be called after reference resolution"); Type const* type = typeName().annotation().type; return type->category() == Type::Category::Mapping || dynamic_cast<ReferenceType const*>(type); } bool VariableDeclaration::isStateVariable() const { return dynamic_cast<ContractDefinition const*>(scope()); } bool VariableDeclaration::isFileLevelVariable() const { return dynamic_cast<SourceUnit const*>(scope()); } std::set<VariableDeclaration::Location> VariableDeclaration::allowedDataLocations() const { using Location = VariableDeclaration::Location; if (isStateVariable()) return std::set<Location>{Location::Unspecified, Location::Transient}; else if (!hasReferenceOrMappingType() || isEventOrErrorParameter()) return std::set<Location>{ Location::Unspecified }; else if (isCallableOrCatchParameter()) { std::set<Location> locations{ Location::Memory }; if ( isConstructorParameter() || isInternalCallableParameter() || isLibraryFunctionParameter() ) locations.insert(Location::Storage); if (!isTryCatchParameter() && !isConstructorParameter()) locations.insert(Location::CallData); return locations; } else if (isLocalVariable()) // Further restrictions will be imposed later on. return std::set<Location>{ Location::Memory, Location::Storage, Location::CallData }; else // Struct members etc. return std::set<Location>{ Location::Unspecified }; } std::string VariableDeclaration::externalIdentifierHex() const { solAssert(isStateVariable() && isPublic(), "Can only be called for public state variables"); return TypeProvider::function(*this)->externalIdentifierHex(); } Type const* VariableDeclaration::type() const { return annotation().type; } FunctionTypePointer VariableDeclaration::functionType(bool _internal) const { if (_internal) return nullptr; switch (visibility()) { case Visibility::Default: solAssert(false, "visibility() should not return Default"); case Visibility::Private: case Visibility::Internal: return nullptr; case Visibility::Public: case Visibility::External: return TypeProvider::function(*this); } // To make the compiler happy return nullptr; } VariableDeclarationAnnotation& VariableDeclaration::annotation() const { return initAnnotation<VariableDeclarationAnnotation>(); } StatementAnnotation& Statement::annotation() const { return initAnnotation<StatementAnnotation>(); } InlineAssemblyAnnotation& InlineAssembly::annotation() const { return initAnnotation<InlineAssemblyAnnotation>(); } BlockAnnotation& Block::annotation() const { return initAnnotation<BlockAnnotation>(); } TryCatchClauseAnnotation& TryCatchClause::annotation() const { return initAnnotation<TryCatchClauseAnnotation>(); } ForStatementAnnotation& ForStatement::annotation() const { return initAnnotation<ForStatementAnnotation>(); } ReturnAnnotation& Return::annotation() const { return initAnnotation<ReturnAnnotation>(); } ExpressionAnnotation& Expression::annotation() const { return initAnnotation<ExpressionAnnotation>(); } MemberAccessAnnotation& MemberAccess::annotation() const { return initAnnotation<MemberAccessAnnotation>(); } OperationAnnotation& UnaryOperation::annotation() const { return initAnnotation<OperationAnnotation>(); } FunctionType const* UnaryOperation::userDefinedFunctionType() const { if (*annotation().userDefinedFunction == nullptr) return nullptr; FunctionDefinition const* userDefinedFunction = *annotation().userDefinedFunction; return dynamic_cast<FunctionType const*>( userDefinedFunction->libraryFunction() ? userDefinedFunction->typeViaContractName() : userDefinedFunction->type() ); } FunctionType const* BinaryOperation::userDefinedFunctionType() const { if (*annotation().userDefinedFunction == nullptr) return nullptr; FunctionDefinition const* userDefinedFunction = *annotation().userDefinedFunction; return dynamic_cast<FunctionType const*>( userDefinedFunction->libraryFunction() ? userDefinedFunction->typeViaContractName() : userDefinedFunction->type() ); } BinaryOperationAnnotation& BinaryOperation::annotation() const { return initAnnotation<BinaryOperationAnnotation>(); } FunctionCallAnnotation& FunctionCall::annotation() const { return initAnnotation<FunctionCallAnnotation>(); } std::vector<ASTPointer<Expression const>> FunctionCall::sortedArguments() const { // normal arguments if (m_names.empty()) return arguments(); // named arguments FunctionTypePointer functionType; if (*annotation().kind == FunctionCallKind::StructConstructorCall) { auto const& type = dynamic_cast<TypeType const&>(*m_expression->annotation().type); auto const& structType = dynamic_cast<StructType const&>(*type.actualType()); functionType = structType.constructorType(); } else functionType = dynamic_cast<FunctionType const*>(m_expression->annotation().type); std::vector<ASTPointer<Expression const>> sorted; for (auto const& parameterName: functionType->parameterNames()) { bool found = false; for (size_t j = 0; j < m_names.size() && !found; j++) if ((found = (parameterName == *m_names.at(j)))) // we found the actual parameter position sorted.push_back(m_arguments.at(j)); solAssert(found, ""); } if (!functionType->takesArbitraryParameters()) { solAssert(m_arguments.size() == functionType->parameterTypes().size(), ""); solAssert(m_arguments.size() == m_names.size(), ""); solAssert(m_arguments.size() == sorted.size(), ""); } return sorted; } IdentifierAnnotation& Identifier::annotation() const { return initAnnotation<IdentifierAnnotation>(); } ASTString Literal::valueWithoutUnderscores() const { return boost::erase_all_copy(value(), "_"); } bool Literal::isHexNumber() const { if (token() != Token::Number) return false; return boost::starts_with(value(), "0x"); } bool Literal::looksLikeAddress() const { if (subDenomination() != SubDenomination::None) return false; if (!isHexNumber()) return false; return abs(int(valueWithoutUnderscores().length()) - 42) <= 1; } bool Literal::passesAddressChecksum() const { solAssert(isHexNumber(), "Expected hex number"); return util::passesAddressChecksum(valueWithoutUnderscores(), true); } std::string Literal::getChecksummedAddress() const { solAssert(isHexNumber(), "Expected hex number"); /// Pad literal to be a proper hex address. std::string address = valueWithoutUnderscores().substr(2); if (address.length() > 40) return std::string(); address.insert(address.begin(), 40 - address.size(), '0'); return util::getChecksummedAddress(address); } TryCatchClause const* TryStatement::successClause() const { solAssert(m_clauses.size() > 0, ""); return m_clauses[0].get(); } TryCatchClause const* TryStatement::panicClause() const { return findClause(m_clauses, "Panic"); } TryCatchClause const* TryStatement::errorClause() const { return findClause(m_clauses, "Error"); } TryCatchClause const* TryStatement::fallbackClause() const { return findClause(m_clauses); } /// Experimental Solidity nodes /// @{ TypeClassDefinitionAnnotation& TypeClassDefinition::annotation() const { return initAnnotation<TypeClassDefinitionAnnotation>(); } TypeDeclarationAnnotation& TypeDefinition::annotation() const { return initAnnotation<TypeDeclarationAnnotation>(); } /// @}
31,542
C++
.cpp
913
32.274918
151
0.77551
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
3,246
ASTJsonImporter.cpp
ethereum_solidity/libsolidity/ast/ASTJsonImporter.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 /** * @author julius <djudju@protonmail.com> * @date 2019 *Component that imports an AST from json format to the internal format */ #include <libsolidity/ast/ASTJsonImporter.h> #include <libsolidity/ast/UserDefinableOperators.h> #include <libyul/AsmJsonImporter.h> #include <libyul/AST.h> #include <libyul/Dialect.h> #include <libyul/backends/evm/EVMDialect.h> #include <liblangutil/Exceptions.h> #include <liblangutil/Scanner.h> #include <liblangutil/SourceLocation.h> #include <liblangutil/Token.h> #include <boost/algorithm/string/split.hpp> #include <boost/algorithm/string.hpp> namespace solidity::frontend { using SourceLocation = langutil::SourceLocation; template<class T> ASTPointer<T> ASTJsonImporter::nullOrCast(Json const& _json) { if (_json.is_null()) return nullptr; else return std::dynamic_pointer_cast<T>(convertJsonToASTNode(_json)); } // ============ public =========================== std::map<std::string, ASTPointer<SourceUnit>> ASTJsonImporter::jsonToSourceUnit(std::map<std::string, Json> const& _sourceList) { for (auto const& src: _sourceList) m_sourceNames.emplace_back(std::make_shared<std::string const>(src.first)); for (auto const& srcPair: _sourceList) { astAssert(!srcPair.second.is_null()); astAssert(member(srcPair.second,"nodeType") == "SourceUnit", "The 'nodeType' of the highest node must be 'SourceUnit'."); m_sourceUnits[srcPair.first] = createSourceUnit(srcPair.second, srcPair.first); } return m_sourceUnits; } // ============ private =========================== // =========== general creation functions ============== template <typename T, typename... Args> ASTPointer<T> ASTJsonImporter::createASTNode(Json const& _node, Args&&... _args) { static_assert(std::is_same_v<Json::number_unsigned_t, uint64_t>); astAssert(member(_node, "id").is_number_integer(), "'id'-field must be 64bit integer."); int64_t id = static_cast<Json::number_integer_t>(_node["id"]); astAssert(m_usedIDs.insert(id).second, "Found duplicate node ID!"); auto n = std::make_shared<T>( id, createSourceLocation(_node), std::forward<Args>(_args)... ); return n; } SourceLocation const ASTJsonImporter::createSourceLocation(Json const& _node) { astAssert(member(_node, "src").is_string(), "'src' must be a string"); return solidity::langutil::parseSourceLocation(_node["src"].get<std::string>(), m_sourceNames); } std::optional<std::vector<SourceLocation>> ASTJsonImporter::createSourceLocations(Json const& _node) const { std::vector<SourceLocation> locations; if (_node.contains("nameLocations") && _node["nameLocations"].is_array()) { for (auto const& val: _node["nameLocations"]) locations.emplace_back(langutil::parseSourceLocation(val.get<std::string>(), m_sourceNames)); return locations; } return std::nullopt; } SourceLocation ASTJsonImporter::createNameSourceLocation(Json const& _node) { astAssert(member(_node, "nameLocation").is_string(), "'nameLocation' must be a string"); return solidity::langutil::parseSourceLocation(_node["nameLocation"].get<std::string>(), m_sourceNames); } SourceLocation ASTJsonImporter::createKeyNameSourceLocation(Json const& _node) { astAssert(member(_node, "keyNameLocation").is_string(), "'keyNameLocation' must be a string"); return solidity::langutil::parseSourceLocation(_node["keyNameLocation"].get<std::string>(), m_sourceNames); } SourceLocation ASTJsonImporter::createValueNameSourceLocation(Json const& _node) { astAssert(member(_node, "valueNameLocation").is_string(), "'valueNameLocation' must be a string"); return solidity::langutil::parseSourceLocation(_node["valueNameLocation"].get<std::string>(), m_sourceNames); } template<class T> ASTPointer<T> ASTJsonImporter::convertJsonToASTNode(Json const& _node) { ASTPointer<T> ret = std::dynamic_pointer_cast<T>(convertJsonToASTNode(_node)); astAssert(ret, "cast of converted json-node must not be nullptr"); return ret; } ASTPointer<ASTNode> ASTJsonImporter::convertJsonToASTNode(Json const& _json) { astAssert(_json["nodeType"].is_string() && _json.contains("id"), "JSON-Node needs to have 'nodeType' and 'id' fields."); std::string nodeType = _json["nodeType"].get<std::string>(); if (nodeType == "PragmaDirective") return createPragmaDirective(_json); if (nodeType == "ImportDirective") return createImportDirective(_json); if (nodeType == "ContractDefinition") return createContractDefinition(_json); if (nodeType == "IdentifierPath") return createIdentifierPath(_json); if (nodeType == "InheritanceSpecifier") return createInheritanceSpecifier(_json); if (nodeType == "UsingForDirective") return createUsingForDirective(_json); if (nodeType == "StructDefinition") return createStructDefinition(_json); if (nodeType == "EnumDefinition") return createEnumDefinition(_json); if (nodeType == "EnumValue") return createEnumValue(_json); if (nodeType == "UserDefinedValueTypeDefinition") return createUserDefinedValueTypeDefinition(_json); if (nodeType == "ParameterList") return createParameterList(_json); if (nodeType == "OverrideSpecifier") return createOverrideSpecifier(_json); if (nodeType == "FunctionDefinition") return createFunctionDefinition(_json); if (nodeType == "VariableDeclaration") return createVariableDeclaration(_json); if (nodeType == "ModifierDefinition") return createModifierDefinition(_json); if (nodeType == "ModifierInvocation") return createModifierInvocation(_json); if (nodeType == "EventDefinition") return createEventDefinition(_json); if (nodeType == "ErrorDefinition") return createErrorDefinition(_json); if (nodeType == "ElementaryTypeName") return createElementaryTypeName(_json); if (nodeType == "UserDefinedTypeName") return createUserDefinedTypeName(_json); if (nodeType == "FunctionTypeName") return createFunctionTypeName(_json); if (nodeType == "Mapping") return createMapping(_json); if (nodeType == "ArrayTypeName") return createArrayTypeName(_json); if (nodeType == "InlineAssembly") return createInlineAssembly(_json); if (nodeType == "Block") return createBlock(_json, false); if (nodeType == "UncheckedBlock") return createBlock(_json, true); if (nodeType == "PlaceholderStatement") return createPlaceholderStatement(_json); if (nodeType == "IfStatement") return createIfStatement(_json); if (nodeType == "TryCatchClause") return createTryCatchClause(_json); if (nodeType == "TryStatement") return createTryStatement(_json); if (nodeType == "WhileStatement") return createWhileStatement(_json, false); if (nodeType == "DoWhileStatement") return createWhileStatement(_json, true); if (nodeType == "ForStatement") return createForStatement(_json); if (nodeType == "Continue") return createContinue(_json); if (nodeType == "Break") return createBreak(_json); if (nodeType == "Return") return createReturn(_json); if (nodeType == "EmitStatement") return createEmitStatement(_json); if (nodeType == "RevertStatement") return createRevertStatement(_json); if (nodeType == "Throw") return createThrow(_json); if (nodeType == "VariableDeclarationStatement") return createVariableDeclarationStatement(_json); if (nodeType == "ExpressionStatement") return createExpressionStatement(_json); if (nodeType == "Conditional") return createConditional(_json); if (nodeType == "Assignment") return createAssignment(_json); if (nodeType == "TupleExpression") return createTupleExpression(_json); if (nodeType == "UnaryOperation") return createUnaryOperation(_json); if (nodeType == "BinaryOperation") return createBinaryOperation(_json); if (nodeType == "FunctionCall") return createFunctionCall(_json); if (nodeType == "FunctionCallOptions") return createFunctionCallOptions(_json); if (nodeType == "NewExpression") return createNewExpression(_json); if (nodeType == "MemberAccess") return createMemberAccess(_json); if (nodeType == "IndexAccess") return createIndexAccess(_json); if (nodeType == "IndexRangeAccess") return createIndexRangeAccess(_json); if (nodeType == "Identifier") return createIdentifier(_json); if (nodeType == "ElementaryTypeNameExpression") return createElementaryTypeNameExpression(_json); if (nodeType == "Literal") return createLiteral(_json); if (nodeType == "StructuredDocumentation") return createDocumentation(_json); else astAssert(false, "Unknown type of ASTNode: " + nodeType); // FIXME: Workaround for spurious GCC 12.1 warning (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=105794) util::unreachable(); } // ============ functions to instantiate the AST-Nodes from Json-Nodes ============== ASTPointer<SourceUnit> ASTJsonImporter::createSourceUnit(Json const& _node, std::string const& _srcName) { std::optional<std::string> license; if (_node.contains("license") && !_node["license"].is_null()) license = _node["license"].get<std::string>(); bool experimentalSolidity = false; if (_node.contains("experimentalSolidity") && !_node["experimentalSolidity"].is_null()) experimentalSolidity = _node["experimentalSolidity"].get<bool>(); std::vector<ASTPointer<ASTNode>> nodes; for (auto& child: member(_node, "nodes")) nodes.emplace_back(convertJsonToASTNode(child)); ASTPointer<SourceUnit> tmp = createASTNode<SourceUnit>(_node, license, nodes, experimentalSolidity); tmp->annotation().path = _srcName; return tmp; } ASTPointer<PragmaDirective> ASTJsonImporter::createPragmaDirective(Json const& _node) { std::vector<Token> tokens; std::vector<ASTString> literals; for (auto const& lit: member(_node, "literals")) { std::string l = lit.get<std::string>(); literals.push_back(l); tokens.push_back(scanSingleToken(l)); } return createASTNode<PragmaDirective>(_node, tokens, literals); } ASTPointer<ImportDirective> ASTJsonImporter::createImportDirective(Json const& _node) { ASTPointer<ASTString> unitAlias = memberAsASTString(_node, "unitAlias"); ASTPointer<ASTString> path = memberAsASTString(_node, "file"); ImportDirective::SymbolAliasList symbolAliases; for (auto& tuple: member(_node, "symbolAliases")) { astAssert(tuple["local"].is_null() || tuple["local"].is_string(), "expected 'local' to be a string or null!"); symbolAliases.push_back({ createIdentifier(tuple["foreign"]), tuple["local"].is_null() ? nullptr : std::make_shared<ASTString>(tuple["local"].get<std::string>()), createSourceLocation(tuple["foreign"])} ); } ASTPointer<ImportDirective> tmp = createASTNode<ImportDirective>( _node, path, unitAlias, createNameSourceLocation(_node), std::move(symbolAliases) ); astAssert(_node["absolutePath"].is_string(), "Expected 'absolutePath' to be a string!"); tmp->annotation().absolutePath = _node["absolutePath"].get<std::string>(); return tmp; } ASTPointer<ContractDefinition> ASTJsonImporter::createContractDefinition(Json const& _node) { astAssert(_node["name"].is_string(), "Expected 'name' to be a string!"); std::vector<ASTPointer<InheritanceSpecifier>> baseContracts; for (auto& base: _node["baseContracts"]) baseContracts.push_back(createInheritanceSpecifier(base)); std::vector<ASTPointer<ASTNode>> subNodes; for (auto& subnode: _node["nodes"]) subNodes.push_back(convertJsonToASTNode(subnode)); return createASTNode<ContractDefinition>( _node, std::make_shared<ASTString>(_node["name"].get<std::string>()), createNameSourceLocation(_node), (_node.contains("documentation") && !_node["documentation"].is_null()) ? createDocumentation(member(_node, "documentation")) : nullptr, baseContracts, subNodes, contractKind(_node), memberAsBool(_node, "abstract") ); } ASTPointer<IdentifierPath> ASTJsonImporter::createIdentifierPath(Json const& _node) { astAssert(_node["name"].is_string(), "Expected 'name' to be a string!"); std::vector<ASTString> namePath; std::vector<SourceLocation> namePathLocations; std::vector<std::string> strs; std::string nameString = member(_node, "name").get<std::string>(); boost::algorithm::split(strs, nameString, boost::is_any_of(".")); astAssert(!strs.empty(), "Expected at least one element in IdentifierPath."); for (std::string s: strs) { astAssert(!s.empty(), "Expected non-empty string for IdentifierPath element."); namePath.emplace_back(s); } if (_node.contains("nameLocations") && _node["nameLocations"].is_array()) for (auto const& val: _node["nameLocations"]) namePathLocations.emplace_back(langutil::parseSourceLocation(val.get<std::string>(), m_sourceNames)); else namePathLocations.resize(namePath.size()); astAssert( namePath.size() == namePathLocations.size(), "SourceLocations don't match name paths." ); return createASTNode<IdentifierPath>( _node, namePath, namePathLocations ); } ASTPointer<InheritanceSpecifier> ASTJsonImporter::createInheritanceSpecifier(Json const& _node) { std::vector<ASTPointer<Expression>> arguments; for (auto& arg: member(_node, "arguments")) arguments.push_back(convertJsonToASTNode<Expression>(arg)); return createASTNode<InheritanceSpecifier>( _node, createIdentifierPath(member(_node, "baseName")), member(_node, "arguments").is_null() ? nullptr : std::make_unique<std::vector<ASTPointer<Expression>>>(arguments) ); } ASTPointer<UsingForDirective> ASTJsonImporter::createUsingForDirective(Json const& _node) { std::vector<ASTPointer<IdentifierPath>> functions; std::vector<std::optional<Token>> operators; if (_node.contains("libraryName")) { astAssert(!_node["libraryName"].is_array()); astAssert(!_node["libraryName"].contains("operator")); functions.emplace_back(createIdentifierPath(_node["libraryName"])); operators.emplace_back(std::nullopt); } else if (_node.contains("functionList")) for (Json const& function: _node["functionList"]) { if (function.contains("function")) { astAssert(!function.contains("operator")); astAssert(!function.contains("definition")); functions.emplace_back(createIdentifierPath(function["function"])); operators.emplace_back(std::nullopt); } else { astAssert(function.contains("operator")); astAssert(function.contains("definition")); Token const operatorName = scanSingleToken(function["operator"]); astAssert(util::contains(frontend::userDefinableOperators, operatorName)); functions.emplace_back(createIdentifierPath(function["definition"])); operators.emplace_back(operatorName); } } return createASTNode<UsingForDirective>( _node, std::move(functions), std::move(operators), !_node.contains("libraryName"), (_node.contains("typeName") && !_node["typeName"].is_null()) ? convertJsonToASTNode<TypeName>(_node["typeName"]) : nullptr, memberAsBool(_node, "global") ); } ASTPointer<ASTNode> ASTJsonImporter::createStructDefinition(Json const& _node) { std::vector<ASTPointer<VariableDeclaration>> members; for (auto& member: _node["members"]) members.push_back(createVariableDeclaration(member)); return createASTNode<StructDefinition>( _node, memberAsASTString(_node, "name"), createNameSourceLocation(_node), members, (_node.contains("documentation") && !_node["documentation"].is_null()) ? createDocumentation(member(_node, "documentation")) : nullptr ); } ASTPointer<EnumDefinition> ASTJsonImporter::createEnumDefinition(Json const& _node) { std::vector<ASTPointer<EnumValue>> members; for (auto& member: _node["members"]) members.push_back(createEnumValue(member)); return createASTNode<EnumDefinition>( _node, memberAsASTString(_node, "name"), createNameSourceLocation(_node), members, (_node.contains("documentation") && !_node["documentation"].is_null()) ? createDocumentation(member(_node, "documentation")) : nullptr ); } ASTPointer<EnumValue> ASTJsonImporter::createEnumValue(Json const& _node) { return createASTNode<EnumValue>( _node, memberAsASTString(_node, "name") ); } ASTPointer<UserDefinedValueTypeDefinition> ASTJsonImporter::createUserDefinedValueTypeDefinition(Json const& _node) { return createASTNode<UserDefinedValueTypeDefinition>( _node, memberAsASTString(_node, "name"), createNameSourceLocation(_node), convertJsonToASTNode<TypeName>(member(_node, "underlyingType")) ); } ASTPointer<ParameterList> ASTJsonImporter::createParameterList(Json const& _node) { std::vector<ASTPointer<VariableDeclaration>> parameters; for (auto& param: _node["parameters"]) parameters.push_back(createVariableDeclaration(param)); return createASTNode<ParameterList>( _node, parameters ); } ASTPointer<OverrideSpecifier> ASTJsonImporter::createOverrideSpecifier(Json const& _node) { std::vector<ASTPointer<IdentifierPath>> overrides; if ( _node.contains("overrides")) for (auto& param: _node["overrides"]) overrides.push_back(createIdentifierPath(param)); return createASTNode<OverrideSpecifier>( _node, overrides ); } ASTPointer<FunctionDefinition> ASTJsonImporter::createFunctionDefinition(Json const& _node) { astAssert(_node["kind"].is_string(), "Expected 'kind' to be a string!"); Token kind; bool freeFunction = false; std::string kindStr = member(_node, "kind").get<std::string>(); if (kindStr == "constructor") kind = Token::Constructor; else if (kindStr == "function") kind = Token::Function; else if (kindStr == "fallback") kind = Token::Fallback; else if (kindStr == "receive") kind = Token::Receive; else if (kindStr == "freeFunction") { kind = Token::Function; freeFunction = true; } else astAssert(false, "Expected 'kind' to be one of [constructor, function, fallback, receive]"); std::vector<ASTPointer<ModifierInvocation>> modifiers; for (auto& mod: member(_node, "modifiers")) modifiers.push_back(createModifierInvocation(mod)); Visibility vis = Visibility::Default; // Ignore public visibility for constructors if (kind == Token::Constructor) vis = (visibility(_node) == Visibility::Public) ? Visibility::Default : visibility(_node); else if (!freeFunction) vis = visibility(_node); return createASTNode<FunctionDefinition>( _node, memberAsASTString(_node, "name"), createNameSourceLocation(_node), vis, stateMutability(_node), freeFunction, kind, memberAsBool(_node, "virtual"), (_node.contains("overrides") && !_node["overrides"].is_null()) ? createOverrideSpecifier(member(_node, "overrides")) : nullptr, (_node.contains("documentation") && !_node["documentation"].is_null()) ? createDocumentation(member(_node, "documentation")) : nullptr, createParameterList(member(_node, "parameters")), modifiers, createParameterList(member(_node, "returnParameters")), memberAsBool(_node, "implemented") ? createBlock(member(_node, "body"), false) : nullptr ); } ASTPointer<VariableDeclaration> ASTJsonImporter::createVariableDeclaration(Json const& _node) { astAssert(_node["name"].is_string(), "Expected 'name' to be a string!"); VariableDeclaration::Mutability mutability{}; astAssert(member(_node, "mutability").is_string(), "'mutability' expected to be string."); std::string const mutabilityStr = member(_node, "mutability").get<std::string>(); if (mutabilityStr == "constant") { mutability = VariableDeclaration::Mutability::Constant; astAssert(memberAsBool(_node, "constant")); } else { astAssert(!memberAsBool(_node, "constant")); if (mutabilityStr == "mutable") mutability = VariableDeclaration::Mutability::Mutable; else if (mutabilityStr == "immutable") mutability = VariableDeclaration::Mutability::Immutable; else astAssert(false); } return createASTNode<VariableDeclaration>( _node, nullOrCast<TypeName>(member(_node, "typeName")), std::make_shared<ASTString>(member(_node, "name").get<std::string>()), createNameSourceLocation(_node), nullOrCast<Expression>(member(_node, "value")), visibility(_node), (_node.contains("documentation") && !_node["documentation"].is_null()) ? createDocumentation(member(_node, "documentation")) : nullptr, (_node.contains("indexed") && !_node["indexed"].is_null()) ? memberAsBool(_node, "indexed") : false, mutability, (_node.contains("overrides") && !_node["overrides"].is_null()) ? createOverrideSpecifier(member(_node, "overrides")) : nullptr, location(_node) ); } ASTPointer<ModifierDefinition> ASTJsonImporter::createModifierDefinition(Json const& _node) { return createASTNode<ModifierDefinition>( _node, memberAsASTString(_node, "name"), createNameSourceLocation(_node), (_node.contains("documentation") && !_node["documentation"].is_null()) ? createDocumentation(member(_node, "documentation")) : nullptr, createParameterList(member(_node, "parameters")), memberAsBool(_node, "virtual"), (_node.contains("overrides") && !_node["overrides"].is_null()) ? createOverrideSpecifier(member(_node, "overrides")) : nullptr, (_node.contains("body") && !_node["body"].is_null()) ? createBlock(member(_node, "body"), false) : nullptr ); } ASTPointer<ModifierInvocation> ASTJsonImporter::createModifierInvocation(Json const& _node) { std::vector<ASTPointer<Expression>> arguments; for (auto& arg: member(_node, "arguments")) arguments.push_back(convertJsonToASTNode<Expression>(arg)); return createASTNode<ModifierInvocation>( _node, createIdentifierPath(member(_node, "modifierName")), member(_node, "arguments").is_null() ? nullptr : std::make_unique<std::vector<ASTPointer<Expression>>>(arguments) ); } ASTPointer<EventDefinition> ASTJsonImporter::createEventDefinition(Json const& _node) { return createASTNode<EventDefinition>( _node, memberAsASTString(_node, "name"), createNameSourceLocation(_node), (_node.contains("documentation") && !_node["documentation"].is_null()) ? createDocumentation(member(_node, "documentation")) : nullptr, createParameterList(member(_node, "parameters")), memberAsBool(_node, "anonymous") ); } ASTPointer<ErrorDefinition> ASTJsonImporter::createErrorDefinition(Json const& _node) { return createASTNode<ErrorDefinition>( _node, memberAsASTString(_node, "name"), createNameSourceLocation(_node), (_node.contains("documentation") && !_node["documentation"].is_null()) ? createDocumentation(member(_node, "documentation")) : nullptr, createParameterList(member(_node, "parameters")) ); } ASTPointer<ElementaryTypeName> ASTJsonImporter::createElementaryTypeName(Json const& _node) { unsigned short firstNum; unsigned short secondNum; astAssert(_node["name"].is_string(), "Expected 'name' to be a string!"); std::string name = member(_node, "name").get<std::string>(); Token token; std::tie(token, firstNum, secondNum) = TokenTraits::fromIdentifierOrKeyword(name); ElementaryTypeNameToken elem(token, firstNum, secondNum); std::optional<StateMutability> mutability = {}; if (_node.contains("stateMutability")) mutability = stateMutability(_node); return createASTNode<ElementaryTypeName>(_node, elem, mutability); } ASTPointer<UserDefinedTypeName> ASTJsonImporter::createUserDefinedTypeName(Json const& _node) { return createASTNode<UserDefinedTypeName>( _node, createIdentifierPath(member(_node, "pathNode")) ); } ASTPointer<FunctionTypeName> ASTJsonImporter::createFunctionTypeName(Json const& _node) { return createASTNode<FunctionTypeName>( _node, createParameterList(member(_node, "parameterTypes")), createParameterList(member(_node, "returnParameterTypes")), visibility(_node), stateMutability(_node) ); } ASTPointer<Mapping> ASTJsonImporter::createMapping(Json const& _node) { return createASTNode<Mapping>( _node, convertJsonToASTNode<TypeName>(member(_node, "keyType")), memberAsASTString(_node, "keyName"), createKeyNameSourceLocation(_node), convertJsonToASTNode<TypeName>(member(_node, "valueType")), memberAsASTString(_node, "valueName"), createValueNameSourceLocation(_node) ); } ASTPointer<ArrayTypeName> ASTJsonImporter::createArrayTypeName(Json const& _node) { return createASTNode<ArrayTypeName>( _node, convertJsonToASTNode<TypeName>(member(_node, "baseType")), nullOrCast<Expression>(member(_node, "length")) ); } ASTPointer<InlineAssembly> ASTJsonImporter::createInlineAssembly(Json const& _node) { astAssert(_node["evmVersion"].is_string(), "Expected evmVersion to be a string!"); auto evmVersion = langutil::EVMVersion::fromString(_node["evmVersion"].get<std::string>()); astAssert(evmVersion.has_value(), "Invalid EVM version!"); astAssert(m_evmVersion == evmVersion, "Imported tree evm version differs from configured evm version!"); // TODO: Add test in test/linsolidity/ASTJSON/assembly. This requires adding support for eofVersion in ASTJSONTest std::optional<uint8_t> eofVersion; if (auto const it = _node.find("eofVersion"); it != _node.end()) { eofVersion = it->get<uint8_t>(); astAssert(eofVersion > 0); } astAssert(m_eofVersion == eofVersion, "Imported tree EOF version differs from configured EOF version!"); yul::Dialect const& dialect = yul::EVMDialect::strictAssemblyForEVM(evmVersion.value(), eofVersion); ASTPointer<std::vector<ASTPointer<ASTString>>> flags; if (_node.contains("flags")) { flags = std::make_shared<std::vector<ASTPointer<ASTString>>>(); Json const& flagsNode = _node["flags"]; astAssert(flagsNode.is_array(), "Assembly flags must be an array."); for (auto const& flag: flagsNode) { astAssert(flag.is_string(), "Assembly flag must be a string."); flags->emplace_back(std::make_shared<ASTString>(flag.get<std::string>())); } } std::shared_ptr<yul::AST> operations = std::make_shared<yul::AST>(yul::AsmJsonImporter(m_sourceNames).createAST(member(_node, "AST"))); return createASTNode<InlineAssembly>( _node, nullOrASTString(_node, "documentation"), dialect, std::move(flags), operations ); } ASTPointer<Block> ASTJsonImporter::createBlock(Json const& _node, bool _unchecked) { std::vector<ASTPointer<Statement>> statements; for (auto& stat: member(_node, "statements")) statements.push_back(convertJsonToASTNode<Statement>(stat)); return createASTNode<Block>( _node, nullOrASTString(_node, "documentation"), _unchecked, statements ); } ASTPointer<PlaceholderStatement> ASTJsonImporter::createPlaceholderStatement(Json const& _node) { return createASTNode<PlaceholderStatement>( _node, nullOrASTString(_node, "documentation") ); } ASTPointer<IfStatement> ASTJsonImporter::createIfStatement(Json const& _node) { return createASTNode<IfStatement>( _node, nullOrASTString(_node, "documentation"), convertJsonToASTNode<Expression>(member(_node, "condition")), convertJsonToASTNode<Statement>(member(_node, "trueBody")), nullOrCast<Statement>(member(_node, "falseBody")) ); } ASTPointer<TryCatchClause> ASTJsonImporter::createTryCatchClause(Json const& _node) { return createASTNode<TryCatchClause>( _node, memberAsASTString(_node, "errorName"), nullOrCast<ParameterList>(member(_node, "parameters")), convertJsonToASTNode<Block>(member(_node, "block")) ); } ASTPointer<TryStatement> ASTJsonImporter::createTryStatement(Json const& _node) { std::vector<ASTPointer<TryCatchClause>> clauses; for (auto& param: _node["clauses"]) clauses.emplace_back(createTryCatchClause(param)); return createASTNode<TryStatement>( _node, nullOrASTString(_node, "documentation"), convertJsonToASTNode<Expression>(member(_node, "externalCall")), clauses ); } ASTPointer<WhileStatement> ASTJsonImporter::createWhileStatement(Json const& _node, bool _isDoWhile=false) { return createASTNode<WhileStatement>( _node, nullOrASTString(_node, "documentation"), convertJsonToASTNode<Expression>(member(_node, "condition")), convertJsonToASTNode<Statement>(member(_node, "body")), _isDoWhile ); } ASTPointer<ForStatement> ASTJsonImporter::createForStatement(Json const& _node) { return createASTNode<ForStatement>( _node, nullOrASTString(_node, "documentation"), nullOrCast<Statement>(member(_node, "initializationExpression")), nullOrCast<Expression>(member(_node, "condition")), nullOrCast<ExpressionStatement>(member(_node, "loopExpression")), convertJsonToASTNode<Statement>(member(_node, "body")) ); } ASTPointer<Continue> ASTJsonImporter::createContinue(Json const& _node) { return createASTNode<Continue>( _node, nullOrASTString(_node, "documentation") ); } ASTPointer<Break> ASTJsonImporter::createBreak(Json const& _node) { return createASTNode<Break>( _node, nullOrASTString(_node, "documentation") ); } ASTPointer<Return> ASTJsonImporter::createReturn(Json const& _node) { return createASTNode<Return>( _node, nullOrASTString(_node, "documentation"), nullOrCast<Expression>(member(_node, "expression")) ); } ASTPointer<Throw> ASTJsonImporter::createThrow(Json const& _node) { return createASTNode<Throw>( _node, nullOrASTString(_node, "documentation") ); } ASTPointer<EmitStatement> ASTJsonImporter::createEmitStatement(Json const& _node) { return createASTNode<EmitStatement>( _node, nullOrASTString(_node, "documentation"), createFunctionCall(member(_node, "eventCall")) ); } ASTPointer<RevertStatement> ASTJsonImporter::createRevertStatement(Json const& _node) { return createASTNode<RevertStatement>( _node, nullOrASTString(_node, "documentation"), createFunctionCall(member(_node, "errorCall")) ); } ASTPointer<VariableDeclarationStatement> ASTJsonImporter::createVariableDeclarationStatement(Json const& _node) { std::vector<ASTPointer<VariableDeclaration>> variables; for (auto& var: member(_node, "declarations")) variables.push_back(var.is_null() ? nullptr : createVariableDeclaration(var)); //unnamed components are empty pointers return createASTNode<VariableDeclarationStatement>( _node, nullOrASTString(_node, "documentation"), variables, nullOrCast<Expression>(member(_node, "initialValue")) ); } ASTPointer<ExpressionStatement> ASTJsonImporter::createExpressionStatement(Json const& _node) { return createASTNode<ExpressionStatement>( _node, nullOrASTString(_node, "documentation"), convertJsonToASTNode<Expression>(member(_node, "expression")) ); } ASTPointer<Conditional> ASTJsonImporter::createConditional(Json const& _node) { return createASTNode<Conditional>( _node, convertJsonToASTNode<Expression>(member(_node, "condition")), convertJsonToASTNode<Expression>(member(_node, "trueExpression")), convertJsonToASTNode<Expression>(member(_node, "falseExpression")) ); } ASTPointer<Assignment> ASTJsonImporter::createAssignment(Json const& _node) { return createASTNode<Assignment>( _node, convertJsonToASTNode<Expression>(member(_node, "leftHandSide")), scanSingleToken(member(_node, "operator")), convertJsonToASTNode<Expression>(member(_node, "rightHandSide")) ); } ASTPointer<TupleExpression> ASTJsonImporter::createTupleExpression(Json const& _node) { std::vector<ASTPointer<Expression>> components; for (auto& comp: member(_node, "components")) components.push_back(nullOrCast<Expression>(comp)); return createASTNode<TupleExpression>( _node, components, memberAsBool(_node, "isInlineArray") ); } ASTPointer<UnaryOperation> ASTJsonImporter::createUnaryOperation(Json const& _node) { return createASTNode<UnaryOperation>( _node, scanSingleToken(member(_node, "operator")), convertJsonToASTNode<Expression>(member(_node, "subExpression")), memberAsBool(_node, "prefix") ); } ASTPointer<BinaryOperation> ASTJsonImporter::createBinaryOperation(Json const& _node) { return createASTNode<BinaryOperation>( _node, convertJsonToASTNode<Expression>(member(_node, "leftExpression")), scanSingleToken(member(_node, "operator")), convertJsonToASTNode<Expression>(member(_node, "rightExpression")) ); } ASTPointer<FunctionCall> ASTJsonImporter::createFunctionCall(Json const& _node) { std::vector<ASTPointer<Expression>> arguments; for (auto& arg: member(_node, "arguments")) arguments.push_back(convertJsonToASTNode<Expression>(arg)); std::vector<ASTPointer<ASTString>> names; for (auto& name: member(_node, "names")) { astAssert(name.is_string(), "Expected 'names' members to be strings!"); names.push_back(std::make_shared<ASTString>(name.get<std::string>())); } std::optional<std::vector<SourceLocation>> sourceLocations = createSourceLocations(_node); return createASTNode<FunctionCall>( _node, convertJsonToASTNode<Expression>(member(_node, "expression")), arguments, names, sourceLocations ? *sourceLocations : std::vector<SourceLocation>(names.size()) ); } ASTPointer<FunctionCallOptions> ASTJsonImporter::createFunctionCallOptions(Json const& _node) { std::vector<ASTPointer<Expression>> options; for (auto& option: member(_node, "options")) options.push_back(convertJsonToASTNode<Expression>(option)); std::vector<ASTPointer<ASTString>> names; for (auto& name: member(_node, "names")) { astAssert(name.is_string(), "Expected 'names' members to be strings!"); names.push_back(std::make_shared<ASTString>(name.get<std::string>())); } return createASTNode<FunctionCallOptions>( _node, convertJsonToASTNode<Expression>(member(_node, "expression")), options, names ); } ASTPointer<NewExpression> ASTJsonImporter::createNewExpression(Json const& _node) { return createASTNode<NewExpression>( _node, convertJsonToASTNode<TypeName>(member(_node, "typeName")) ); } ASTPointer<MemberAccess> ASTJsonImporter::createMemberAccess(Json const& _node) { SourceLocation memberLocation; if (member(_node, "memberLocation").is_string()) memberLocation = solidity::langutil::parseSourceLocation(_node["memberLocation"].get<std::string>(), m_sourceNames); return createASTNode<MemberAccess>( _node, convertJsonToASTNode<Expression>(member(_node, "expression")), memberAsASTString(_node, "memberName"), std::move(memberLocation) ); } ASTPointer<IndexAccess> ASTJsonImporter::createIndexAccess(Json const& _node) { return createASTNode<IndexAccess>( _node, convertJsonToASTNode<Expression>(member(_node, "baseExpression")), nullOrCast<Expression>(member(_node, "indexExpression")) ); } ASTPointer<IndexRangeAccess> ASTJsonImporter::createIndexRangeAccess(Json const& _node) { return createASTNode<IndexRangeAccess>( _node, convertJsonToASTNode<Expression>(member(_node, "baseExpression")), nullOrCast<Expression>(member(_node, "startExpression")), nullOrCast<Expression>(member(_node, "endExpression")) ); } ASTPointer<Identifier> ASTJsonImporter::createIdentifier(Json const& _node) { return createASTNode<Identifier>(_node, memberAsASTString(_node, "name")); } ASTPointer<ElementaryTypeNameExpression> ASTJsonImporter::createElementaryTypeNameExpression(Json const& _node) { return createASTNode<ElementaryTypeNameExpression>( _node, createElementaryTypeName(member(_node, "typeName")) ); } ASTPointer<ASTNode> ASTJsonImporter::createLiteral(Json const& _node) { static std::string const valStr = "value"; static std::string const hexValStr = "hexValue"; astAssert(member(_node, valStr).is_string() || member(_node, hexValStr).is_string(), "Literal-value is unset."); ASTPointer<ASTString> value = _node.contains(hexValStr) ? std::make_shared<ASTString>(util::asString(util::fromHex(_node[hexValStr].get<std::string>()))) : std::make_shared<ASTString>(_node[valStr].get<std::string>()); return createASTNode<Literal>( _node, literalTokenKind(_node), value, member(_node, "subdenomination").is_null() ? Literal::SubDenomination::None : subdenomination(_node) ); } ASTPointer<StructuredDocumentation> ASTJsonImporter::createDocumentation(Json const& _node) { static std::string const textString = "text"; astAssert(member(_node, textString).is_string(), "'text' must be a string"); return createASTNode<StructuredDocumentation>( _node, std::make_shared<ASTString>(_node[textString].get<std::string>()) ); } // ===== helper functions ========== Json ASTJsonImporter::member(Json const& _node, std::string const& _name) { if (!_node.contains(_name)) return Json(); return _node[_name]; } Token ASTJsonImporter::scanSingleToken(Json const& _node) { langutil::CharStream charStream(_node.get<std::string>(), ""); langutil::Scanner scanner{charStream}; astAssert(scanner.peekNextToken() == Token::EOS, "Token string is too long."); return scanner.currentToken(); } ASTPointer<ASTString> ASTJsonImporter::nullOrASTString(Json const& _json, std::string const& _name) { return (_json.contains(_name) && (_json[_name].is_string())) ? memberAsASTString(_json, _name) : nullptr; } ASTPointer<ASTString> ASTJsonImporter::memberAsASTString(Json const& _node, std::string const& _name) { Json value = member(_node, _name); astAssert(value.is_string(), "field " + _name + " must be of type string."); return std::make_shared<ASTString>(_node[_name].get<std::string>()); } bool ASTJsonImporter::memberAsBool(Json const& _node, std::string const& _name) { Json value = member(_node, _name); astAssert(value.is_boolean(), "field " + _name + " must be of type boolean."); return _node[_name].get<bool>(); } // =========== JSON to definition helpers ======================= ContractKind ASTJsonImporter::contractKind(Json const& _node) { ContractKind kind; astAssert(!member(_node, "contractKind").is_null(), "'Contract-kind' can not be null."); if (_node["contractKind"].get<std::string>() == "interface") kind = ContractKind::Interface; else if (_node["contractKind"].get<std::string>() == "contract") kind = ContractKind::Contract; else if (_node["contractKind"].get<std::string>() == "library") kind = ContractKind::Library; else astAssert(false, "Unknown ContractKind"); return kind; } Token ASTJsonImporter::literalTokenKind(Json const& _node) { astAssert(member(_node, "kind").is_string(), "Token-'kind' expected to be a string."); Token tok; if (_node["kind"].get<std::string>() == "number") tok = Token::Number; else if (_node["kind"].get<std::string>() == "string") tok = Token::StringLiteral; else if (_node["kind"].get<std::string>() == "unicodeString") tok = Token::UnicodeStringLiteral; else if (_node["kind"].get<std::string>() == "hexString") tok = Token::HexStringLiteral; else if (_node["kind"].get<std::string>() == "bool") tok = (member(_node, "value").get<std::string>() == "true") ? Token::TrueLiteral : Token::FalseLiteral; else astAssert(false, "Unknown kind of literalString"); return tok; } Visibility ASTJsonImporter::visibility(Json const& _node) { Json visibility = member(_node, "visibility"); astAssert(visibility.is_string(), "'visibility' expected to be a string."); std::string const visibilityStr = visibility.get<std::string>(); if (visibilityStr == "default") return Visibility::Default; else if (visibilityStr == "private") return Visibility::Private; else if ( visibilityStr == "internal") return Visibility::Internal; else if (visibilityStr == "public") return Visibility::Public; else if (visibilityStr == "external") return Visibility::External; else astAssert(false, "Unknown visibility declaration"); // FIXME: Workaround for spurious GCC 12.1 warning (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=105794) util::unreachable(); } VariableDeclaration::Location ASTJsonImporter::location(Json const& _node) { Json storageLoc = member(_node, "storageLocation"); astAssert(storageLoc.is_string(), "'storageLocation' expected to be a string."); std::string const storageLocStr = storageLoc.get<std::string>(); if (storageLocStr == "default") return VariableDeclaration::Location::Unspecified; else if (storageLocStr == "storage") return VariableDeclaration::Location::Storage; else if (storageLocStr == "memory") return VariableDeclaration::Location::Memory; else if (storageLocStr == "calldata") return VariableDeclaration::Location::CallData; else if (storageLocStr == "transient") return VariableDeclaration::Location::Transient; else astAssert(false, "Unknown location declaration"); // FIXME: Workaround for spurious GCC 12.1 warning (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=105794) util::unreachable(); } Literal::SubDenomination ASTJsonImporter::subdenomination(Json const& _node) { Json subDen = member(_node, "subdenomination"); if (subDen.is_null()) return Literal::SubDenomination::None; astAssert(subDen.is_string(), "'subDenomination' expected to be string."); std::string const subDenStr = subDen.get<std::string>(); if (subDenStr == "wei") return Literal::SubDenomination::Wei; else if (subDenStr == "gwei") return Literal::SubDenomination::Gwei; else if (subDenStr == "ether") return Literal::SubDenomination::Ether; else if (subDenStr == "seconds") return Literal::SubDenomination::Second; else if (subDenStr == "minutes") return Literal::SubDenomination::Minute; else if (subDenStr == "hours") return Literal::SubDenomination::Hour; else if (subDenStr == "days") return Literal::SubDenomination::Day; else if (subDenStr == "weeks") return Literal::SubDenomination::Week; else if (subDenStr == "years") return Literal::SubDenomination::Year; else astAssert(false, "Unknown subdenomination"); // FIXME: Workaround for spurious GCC 12.1 warning (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=105794) util::unreachable(); } StateMutability ASTJsonImporter::stateMutability(Json const& _node) { astAssert(member(_node, "stateMutability").is_string(), "StateMutability' expected to be string."); std::string const mutabilityStr = member(_node, "stateMutability").get<std::string>(); if (mutabilityStr == "pure") return StateMutability::Pure; else if (mutabilityStr == "view") return StateMutability::View; else if (mutabilityStr == "nonpayable") return StateMutability::NonPayable; else if (mutabilityStr == "payable") return StateMutability::Payable; else astAssert(false, "Unknown stateMutability"); // FIXME: Workaround for spurious GCC 12.1 warning (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=105794) util::unreachable(); } }
42,573
C++
.cpp
1,105
36.199095
138
0.75466
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,247
Types.cpp
ethereum_solidity/libsolidity/ast/Types.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 /** * @author Christian <c@ethdev.com> * @date 2014 * Solidity data types */ #include <libsolidity/ast/Types.h> #include <libsolidity/ast/AST.h> #include <libsolidity/ast/TypeProvider.h> #include <libsolidity/analysis/ConstantEvaluator.h> #include <libsolutil/Algorithms.h> #include <libsolutil/CommonData.h> #include <libsolutil/CommonIO.h> #include <libsolutil/FunctionSelector.h> #include <libsolutil/Keccak256.h> #include <libsolutil/StringUtils.h> #include <libsolutil/UTF8.h> #include <libsolutil/Visitor.h> #include <boost/algorithm/string.hpp> #include <boost/algorithm/string/classification.hpp> #include <boost/algorithm/string/join.hpp> #include <boost/algorithm/string/predicate.hpp> #include <boost/algorithm/string/replace.hpp> #include <boost/algorithm/string/split.hpp> #include <range/v3/view/enumerate.hpp> #include <range/v3/view/reverse.hpp> #include <range/v3/view/tail.hpp> #include <range/v3/view/transform.hpp> #include <range/v3/view/filter.hpp> #include <limits> #include <unordered_set> #include <utility> using namespace solidity; using namespace solidity::langutil; using namespace solidity::frontend; namespace { /// Checks whether _mantissa * (10 ** _expBase10) fits into 4096 bits. bool fitsPrecisionBase10(bigint const& _mantissa, uint32_t _expBase10) { double const log2Of10AwayFromZero = 3.3219280948873624; return fitsPrecisionBaseX(_mantissa, log2Of10AwayFromZero, _expBase10); } /// Checks whether _value fits into IntegerType _type. BoolResult fitsIntegerType(bigint const& _value, IntegerType const& _type) { if (_value < 0 && !_type.isSigned()) return BoolResult::err("Cannot implicitly convert signed literal to unsigned type."); if (_type.minValue() > _value || _value > _type.maxValue()) return BoolResult::err("Literal is too large to fit in " + _type.toString(false) + "."); return true; } /// Checks whether _value fits into _bits bits when having 1 bit as the sign bit /// if _signed is true. bool fitsIntoBits(bigint const& _value, unsigned _bits, bool _signed) { return fitsIntegerType( _value, *TypeProvider::integer( _bits, _signed ? IntegerType::Modifier::Signed : IntegerType::Modifier::Unsigned ) ); } util::Result<TypePointers> transformParametersToExternal(TypePointers const& _parameters, bool _inLibrary) { TypePointers transformed; for (auto const& type: _parameters) { if (!type) return util::Result<TypePointers>::err("Type information not present."); else if (Type const* ext = type->interfaceType(_inLibrary).get()) transformed.push_back(ext); else return util::Result<TypePointers>::err("Parameter should have external type."); } return transformed; } std::string toStringInParentheses(TypePointers const& _types, bool _withoutDataLocation) { return '(' + util::joinHumanReadable( _types | ranges::views::transform([&](auto const* _type) { return _type->toString(_withoutDataLocation); }), "," ) + ')'; } } MemberList::Member::Member(Declaration const* _declaration, Type const* _type): Member(_declaration, _type, _declaration->name()) {} MemberList::Member::Member(Declaration const* _declaration, Type const* _type, std::string _name): name(std::move(_name)), type(_type), declaration(_declaration) { } void Type::clearCache() const { m_members.clear(); m_stackItems.reset(); m_stackSize.reset(); } void StorageOffsets::computeOffsets(TypePointers const& _types) { bigint slotOffset = 0; unsigned byteOffset = 0; std::map<size_t, std::pair<u256, unsigned>> offsets; for (size_t i = 0; i < _types.size(); ++i) { Type const* type = _types[i]; if (!type->canBeStored()) continue; if (byteOffset + type->storageBytes() > 32) { // would overflow, go to next slot ++slotOffset; byteOffset = 0; } solAssert(slotOffset < bigint(1) << 256 ,"Object too large for storage."); offsets[i] = std::make_pair(u256(slotOffset), byteOffset); solAssert(type->storageSize() >= 1, "Invalid storage size."); if (type->storageSize() == 1 && byteOffset + type->storageBytes() <= 32) byteOffset += type->storageBytes(); else { slotOffset += type->storageSize(); byteOffset = 0; } } if (byteOffset > 0) ++slotOffset; solAssert(slotOffset < bigint(1) << 256, "Object too large for storage."); m_storageSize = u256(slotOffset); swap(m_offsets, offsets); } std::pair<u256, unsigned> const* StorageOffsets::offset(size_t _index) const { if (m_offsets.count(_index)) return &m_offsets.at(_index); else return nullptr; } void MemberList::combine(MemberList const & _other) { m_memberTypes += _other.m_memberTypes; } std::pair<u256, unsigned> const* MemberList::memberStorageOffset(std::string const& _name) const { StorageOffsets const& offsets = storageOffsets(); for (auto&& [index, member]: m_memberTypes | ranges::views::enumerate) if (member.name == _name) return offsets.offset(index); return nullptr; } u256 const& MemberList::storageSize() const { return storageOffsets().storageSize(); } StorageOffsets const& MemberList::storageOffsets() const { return m_storageOffsets.init([&]{ TypePointers memberTypes; memberTypes.reserve(m_memberTypes.size()); for (auto const& member: m_memberTypes) memberTypes.push_back(member.type); StorageOffsets storageOffsets; storageOffsets.computeOffsets(memberTypes); return storageOffsets; }); } /// Helper functions for type identifier namespace { std::string parenthesizeIdentifier(std::string const& _internal) { return "(" + _internal + ")"; } template <class Range> std::string identifierList(Range const&& _list) { return parenthesizeIdentifier(boost::algorithm::join(_list, ",")); } std::string richIdentifier(Type const* _type) { return _type ? _type->richIdentifier() : ""; } std::string identifierList(std::vector<Type const*> const& _list) { return identifierList(_list | ranges::views::transform(richIdentifier)); } std::string identifierList(Type const* _type) { return parenthesizeIdentifier(richIdentifier(_type)); } std::string identifierList(Type const* _type1, Type const* _type2) { TypePointers list; list.push_back(_type1); list.push_back(_type2); return identifierList(list); } std::string parenthesizeUserIdentifier(std::string const& _internal) { return parenthesizeIdentifier(_internal); } } std::string Type::escapeIdentifier(std::string const& _identifier) { std::string ret = _identifier; // FIXME: should be _$$$_ boost::algorithm::replace_all(ret, "$", "$$$"); boost::algorithm::replace_all(ret, ",", "_$_"); boost::algorithm::replace_all(ret, "(", "$_"); boost::algorithm::replace_all(ret, ")", "_$"); return ret; } std::string Type::identifier() const { std::string ret = escapeIdentifier(richIdentifier()); solAssert(ret.find_first_of("0123456789") != 0, "Identifier cannot start with a number."); solAssert( ret.find_first_not_of("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMONPQRSTUVWXYZ_$") == std::string::npos, "Identifier contains invalid characters." ); return ret; } Type const* Type::commonType(Type const* _a, Type const* _b) { if (!_a || !_b) return nullptr; else if (_a->mobileType() && _b->isImplicitlyConvertibleTo(*_a->mobileType())) return _a->mobileType(); else if (_b->mobileType() && _a->isImplicitlyConvertibleTo(*_b->mobileType())) return _b->mobileType(); else return nullptr; } MemberList const& Type::members(ASTNode const* _currentScope) const { if (!m_members[_currentScope]) { solAssert( _currentScope == nullptr || dynamic_cast<SourceUnit const*>(_currentScope) || dynamic_cast<ContractDefinition const*>(_currentScope), ""); MemberList::MemberMap members = nativeMembers(_currentScope); if (_currentScope) members += attachedFunctions(*this, *_currentScope); m_members[_currentScope] = std::make_unique<MemberList>(std::move(members)); } return *m_members[_currentScope]; } Type const* Type::fullEncodingType(bool _inLibraryCall, bool _encoderV2, bool) const { Type const* encodingType = mobileType(); if (encodingType) encodingType = encodingType->interfaceType(_inLibraryCall); if (encodingType) encodingType = encodingType->encodingType(); // Structs are fine in the following circumstances: // - ABIv2 or, // - storage struct for a library if (_inLibraryCall && encodingType && encodingType->dataStoredIn(DataLocation::Storage)) return encodingType; Type const* baseType = encodingType; while (auto const* arrayType = dynamic_cast<ArrayType const*>(baseType)) { baseType = arrayType->baseType(); auto const* baseArrayType = dynamic_cast<ArrayType const*>(baseType); if (!_encoderV2 && baseArrayType && baseArrayType->isDynamicallySized()) return nullptr; } if (!_encoderV2 && dynamic_cast<StructType const*>(baseType)) return nullptr; return encodingType; } namespace { std::vector<UsingForDirective const*> usingForDirectivesForType(Type const& _type, ASTNode const& _scope) { std::vector<UsingForDirective const*> usingForDirectives; SourceUnit const* sourceUnit = dynamic_cast<SourceUnit const*>(&_scope); if (auto const* contract = dynamic_cast<ContractDefinition const*>(&_scope)) { sourceUnit = &contract->sourceUnit(); usingForDirectives += contract->usingForDirectives(); } else solAssert(sourceUnit, ""); usingForDirectives += ASTNode::filteredNodes<UsingForDirective>(sourceUnit->nodes()); if (Declaration const* typeDefinition = _type.typeDefinition()) if (auto const* sourceUnit = dynamic_cast<SourceUnit const*>(typeDefinition->scope())) for (auto usingFor: ASTNode::filteredNodes<UsingForDirective>(sourceUnit->nodes())) // We do not yet compare the type name because of normalization. if (usingFor->global() && usingFor->typeName()) usingForDirectives.emplace_back(usingFor); // Normalise data location of type. DataLocation typeLocation = DataLocation::Storage; if (auto refType = dynamic_cast<ReferenceType const*>(&_type)) typeLocation = refType->location(); return usingForDirectives | ranges::views::filter([&](UsingForDirective const* _directive) -> bool { // Convert both types to pointers for comparison to see if the `using for` directive applies. // Note that at this point we don't yet know if the functions are actually usable with the type. // `_type` may not be convertible to the function parameter type. return !_directive->typeName() || *TypeProvider::withLocationIfReference(typeLocation, &_type, true) == *TypeProvider::withLocationIfReference( typeLocation, _directive->typeName()->annotation().type, true ); }) | ranges::to<std::vector<UsingForDirective const*>>; } } std::set<FunctionDefinition const*, ASTNode::CompareByID> Type::operatorDefinitions( Token _token, ASTNode const& _scope, bool _unary ) const { if (!typeDefinition()) return {}; std::set<FunctionDefinition const*, ASTNode::CompareByID> matchingDefinitions; for (UsingForDirective const* directive: usingForDirectivesForType(*this, _scope)) for (auto const& [identifierPath, operator_]: directive->functionsAndOperators()) { if (operator_ != _token) continue; auto const& functionDefinition = dynamic_cast<FunctionDefinition const&>( *identifierPath->annotation().referencedDeclaration ); auto const* functionType = dynamic_cast<FunctionType const*>( functionDefinition.libraryFunction() ? functionDefinition.typeViaContractName() : functionDefinition.type() ); solAssert(functionType && !functionType->parameterTypes().empty()); size_t parameterCount = functionDefinition.parameterList().parameters().size(); if (*this == *functionType->parameterTypes().front() && (_unary ? parameterCount == 1 : parameterCount == 2)) matchingDefinitions.insert(&functionDefinition); } return matchingDefinitions; } MemberList::MemberMap Type::attachedFunctions(Type const& _type, ASTNode const& _scope) { MemberList::MemberMap members; std::set<std::pair<std::string, Declaration const*>> seenFunctions; auto addFunction = [&](FunctionDefinition const& _function, std::optional<std::string> _name = {}) { if (!_name) _name = _function.name(); Type const* functionType = _function.libraryFunction() ? _function.typeViaContractName() : _function.type(); solAssert(functionType, ""); FunctionType const* withBoundFirstArgument = dynamic_cast<FunctionType const&>(*functionType).withBoundFirstArgument(); solAssert(withBoundFirstArgument, ""); if (_type.isImplicitlyConvertibleTo(*withBoundFirstArgument->selfType())) if (seenFunctions.insert(std::make_pair(*_name, &_function)).second) members.emplace_back(&_function, withBoundFirstArgument, *_name); }; for (UsingForDirective const* ufd: usingForDirectivesForType(_type, _scope)) for (auto const& [identifierPath, operator_]: ufd->functionsAndOperators()) { if (operator_.has_value()) // Functions used to define operators are not automatically attached to the type. // I.e. `using {f, f as +} for T` allows `T x; x.f()` but `using {f as +} for T` does not. continue; solAssert(identifierPath); Declaration const* declaration = identifierPath->annotation().referencedDeclaration; solAssert(declaration); if (ContractDefinition const* library = dynamic_cast<ContractDefinition const*>(declaration)) { solAssert(library->isLibrary()); for (FunctionDefinition const* function: library->definedFunctions()) { if (!function->isOrdinary() || !function->isVisibleAsLibraryMember() || function->parameters().empty()) continue; addFunction(*function); } } else addFunction( dynamic_cast<FunctionDefinition const&>(*declaration), identifierPath->path().back() ); } return members; } AddressType::AddressType(StateMutability _stateMutability): m_stateMutability(_stateMutability) { solAssert(m_stateMutability == StateMutability::Payable || m_stateMutability == StateMutability::NonPayable, ""); } std::string AddressType::richIdentifier() const { if (m_stateMutability == StateMutability::Payable) return "t_address_payable"; else return "t_address"; } BoolResult AddressType::isImplicitlyConvertibleTo(Type const& _other) const { if (_other.category() != category()) return false; AddressType const& other = dynamic_cast<AddressType const&>(_other); return other.m_stateMutability <= m_stateMutability; } BoolResult AddressType::isExplicitlyConvertibleTo(Type const& _convertTo) const { if ((_convertTo.category() == category()) || isImplicitlyConvertibleTo(_convertTo)) return true; else if (auto const* contractType = dynamic_cast<ContractType const*>(&_convertTo)) return (m_stateMutability >= StateMutability::Payable) || !contractType->isPayable(); else if (m_stateMutability == StateMutability::NonPayable) { if (auto integerType = dynamic_cast<IntegerType const*>(&_convertTo)) return (!integerType->isSigned() && integerType->numBits() == 160); else if (auto fixedBytesType = dynamic_cast<FixedBytesType const*>(&_convertTo)) return (fixedBytesType->numBytes() == 20); } return false; } std::string AddressType::toString(bool) const { if (m_stateMutability == StateMutability::Payable) return "address payable"; else return "address"; } std::string AddressType::canonicalName() const { return "address"; } u256 AddressType::literalValue(Literal const* _literal) const { solAssert(_literal, ""); solAssert(_literal->value().substr(0, 2) == "0x", ""); return u256(_literal->valueWithoutUnderscores()); } TypeResult AddressType::unaryOperatorResult(Token _operator) const { return _operator == Token::Delete ? TypeProvider::emptyTuple() : nullptr; } TypeResult AddressType::binaryOperatorResult(Token _operator, Type const* _other) const { if (!TokenTraits::isCompareOp(_operator)) return TypeResult::err("Arithmetic operations on addresses are not supported. Convert to integer first before using them."); return Type::commonType(this, _other); } bool AddressType::operator==(Type const& _other) const { if (_other.category() != category()) return false; AddressType const& other = dynamic_cast<AddressType const&>(_other); return other.m_stateMutability == m_stateMutability; } MemberList::MemberMap AddressType::nativeMembers(ASTNode const*) const { MemberList::MemberMap members = { {"balance", TypeProvider::uint256()}, {"code", TypeProvider::array(DataLocation::Memory)}, {"codehash", TypeProvider::fixedBytes(32)}, {"call", TypeProvider::function(strings{"bytes memory"}, strings{"bool", "bytes memory"}, FunctionType::Kind::BareCall, StateMutability::Payable)}, {"callcode", TypeProvider::function(strings{"bytes memory"}, strings{"bool", "bytes memory"}, FunctionType::Kind::BareCallCode, StateMutability::Payable)}, {"delegatecall", TypeProvider::function(strings{"bytes memory"}, strings{"bool", "bytes memory"}, FunctionType::Kind::BareDelegateCall, StateMutability::NonPayable)}, {"staticcall", TypeProvider::function(strings{"bytes memory"}, strings{"bool", "bytes memory"}, FunctionType::Kind::BareStaticCall, StateMutability::View)} }; if (m_stateMutability == StateMutability::Payable) { members.emplace_back(MemberList::Member{"send", TypeProvider::function(strings{"uint"}, strings{"bool"}, FunctionType::Kind::Send, StateMutability::NonPayable)}); members.emplace_back(MemberList::Member{"transfer", TypeProvider::function(strings{"uint"}, strings(), FunctionType::Kind::Transfer, StateMutability::NonPayable)}); } return members; } namespace { bool isValidShiftAndAmountType(Token _operator, Type const& _shiftAmountType) { // Disable >>> here. if (_operator == Token::SHR) return false; else if (IntegerType const* otherInt = dynamic_cast<decltype(otherInt)>(&_shiftAmountType)) return !otherInt->isSigned(); else if (RationalNumberType const* otherRat = dynamic_cast<decltype(otherRat)>(&_shiftAmountType)) return !otherRat->isFractional() && otherRat->integerType() && !otherRat->integerType()->isSigned(); else return false; } } IntegerType::IntegerType(unsigned _bits, IntegerType::Modifier _modifier): m_bits(_bits), m_modifier(_modifier) { solAssert( m_bits > 0 && m_bits <= 256 && m_bits % 8 == 0, "Invalid bit number for integer type: " + util::toString(m_bits) ); } std::string IntegerType::richIdentifier() const { return "t_" + std::string(isSigned() ? "" : "u") + "int" + std::to_string(numBits()); } BoolResult IntegerType::isImplicitlyConvertibleTo(Type const& _convertTo) const { if (_convertTo.category() == category()) { IntegerType const& convertTo = dynamic_cast<IntegerType const&>(_convertTo); // disallowing unsigned to signed conversion of different bits if (isSigned() != convertTo.isSigned()) return false; else if (convertTo.m_bits < m_bits) return false; else return true; } else if (_convertTo.category() == Category::FixedPoint) { FixedPointType const& convertTo = dynamic_cast<FixedPointType const&>(_convertTo); return maxValue() <= convertTo.maxIntegerValue() && minValue() >= convertTo.minIntegerValue(); } else return false; } BoolResult IntegerType::isExplicitlyConvertibleTo(Type const& _convertTo) const { if (isImplicitlyConvertibleTo(_convertTo)) return true; else if (auto integerType = dynamic_cast<IntegerType const*>(&_convertTo)) return (numBits() == integerType->numBits()) || (isSigned() == integerType->isSigned()); else if (auto addressType = dynamic_cast<AddressType const*>(&_convertTo)) return (addressType->stateMutability() != StateMutability::Payable) && !isSigned() && (numBits() == 160); else if (auto fixedBytesType = dynamic_cast<FixedBytesType const*>(&_convertTo)) return (!isSigned() && (numBits() == fixedBytesType->numBytes() * 8)); else if (dynamic_cast<EnumType const*>(&_convertTo)) return true; else if (auto fixedPointType = dynamic_cast<FixedPointType const*>(&_convertTo)) return (isSigned() == fixedPointType->isSigned()) && (numBits() == fixedPointType->numBits()); return false; } TypeResult IntegerType::unaryOperatorResult(Token _operator) const { // "delete" is ok for all integer types if (_operator == Token::Delete) return TypeResult{TypeProvider::emptyTuple()}; // unary negation only on signed types else if (_operator == Token::Sub) return isSigned() ? TypeResult{this} : TypeResult::err("Unary negation is only allowed for signed integers."); else if (_operator == Token::Inc || _operator == Token::Dec || _operator == Token::BitNot) return TypeResult{this}; else return TypeResult::err(""); } bool IntegerType::operator==(Type const& _other) const { if (_other.category() != category()) return false; IntegerType const& other = dynamic_cast<IntegerType const&>(_other); return other.m_bits == m_bits && other.m_modifier == m_modifier; } std::string IntegerType::toString(bool) const { std::string prefix = isSigned() ? "int" : "uint"; return prefix + util::toString(m_bits); } u256 IntegerType::min() const { if (isSigned()) return s2u(s256(minValue())); else return u256(minValue()); } u256 IntegerType::max() const { if (isSigned()) return s2u(s256(maxValue())); else return u256(maxValue()); } bigint IntegerType::minValue() const { if (isSigned()) return -(bigint(1) << (m_bits - 1)); else return bigint(0); } bigint IntegerType::maxValue() const { if (isSigned()) return (bigint(1) << (m_bits - 1)) - 1; else return (bigint(1) << m_bits) - 1; } TypeResult IntegerType::binaryOperatorResult(Token _operator, Type const* _other) const { if ( _other->category() != Category::RationalNumber && _other->category() != Category::FixedPoint && _other->category() != category() ) return nullptr; if (TokenTraits::isShiftOp(_operator)) { // Shifts are not symmetric with respect to the type if (isValidShiftAndAmountType(_operator, *_other)) return this; else return nullptr; } else if (Token::Exp == _operator) { if (auto otherIntType = dynamic_cast<IntegerType const*>(_other)) { if (otherIntType->isSigned()) return TypeResult::err("Exponentiation power is not allowed to be a signed integer type."); } else if (dynamic_cast<FixedPointType const*>(_other)) return nullptr; else if (auto rationalNumberType = dynamic_cast<RationalNumberType const*>(_other)) { if (rationalNumberType->isFractional()) return TypeResult::err("Exponent is fractional."); if (!rationalNumberType->integerType()) return TypeResult::err("Exponent too large."); if (rationalNumberType->isNegative()) return TypeResult::err("Exponentiation power is not allowed to be a negative integer literal."); } return this; } auto commonType = Type::commonType(this, _other); //might be an integer or fixed point if (!commonType) return nullptr; // All integer types can be compared if (TokenTraits::isCompareOp(_operator)) return commonType; if (TokenTraits::isBooleanOp(_operator)) return nullptr; return commonType; } FixedPointType::FixedPointType(unsigned _totalBits, unsigned _fractionalDigits, FixedPointType::Modifier _modifier): m_totalBits(_totalBits), m_fractionalDigits(_fractionalDigits), m_modifier(_modifier) { solAssert( 8 <= m_totalBits && m_totalBits <= 256 && m_totalBits % 8 == 0 && m_fractionalDigits <= 80, "Invalid bit number(s) for fixed type: " + util::toString(_totalBits) + "x" + util::toString(_fractionalDigits) ); } std::string FixedPointType::richIdentifier() const { return "t_" + std::string(isSigned() ? "" : "u") + "fixed" + std::to_string(m_totalBits) + "x" + std::to_string(m_fractionalDigits); } BoolResult FixedPointType::isImplicitlyConvertibleTo(Type const& _convertTo) const { if (_convertTo.category() == category()) { FixedPointType const& convertTo = dynamic_cast<FixedPointType const&>(_convertTo); if (convertTo.fractionalDigits() < m_fractionalDigits) return BoolResult::err("Too many fractional digits."); if (convertTo.numBits() < m_totalBits) return false; else return convertTo.maxIntegerValue() >= maxIntegerValue() && convertTo.minIntegerValue() <= minIntegerValue(); } return false; } BoolResult FixedPointType::isExplicitlyConvertibleTo(Type const& _convertTo) const { return _convertTo.category() == category() || _convertTo.category() == Category::Integer; } TypeResult FixedPointType::unaryOperatorResult(Token _operator) const { solAssert(_operator != Token::Add); switch (_operator) { case Token::Delete: // "delete" is ok for all fixed types return TypeResult{TypeProvider::emptyTuple()}; case Token::Sub: case Token::Inc: case Token::Dec: // for fixed, we allow -, ++ and -- return this; default: return nullptr; } } bool FixedPointType::operator==(Type const& _other) const { if (_other.category() != category()) return false; FixedPointType const& other = dynamic_cast<FixedPointType const&>(_other); return other.m_totalBits == m_totalBits && other.m_fractionalDigits == m_fractionalDigits && other.m_modifier == m_modifier; } std::string FixedPointType::toString(bool) const { std::string prefix = isSigned() ? "fixed" : "ufixed"; return prefix + util::toString(m_totalBits) + "x" + util::toString(m_fractionalDigits); } bigint FixedPointType::maxIntegerValue() const { bigint maxValue = (bigint(1) << (m_totalBits - (isSigned() ? 1 : 0))) - 1; return maxValue / boost::multiprecision::pow(bigint(10), m_fractionalDigits); } bigint FixedPointType::minIntegerValue() const { if (isSigned()) { bigint minValue = -(bigint(1) << (m_totalBits - (isSigned() ? 1 : 0))); return minValue / boost::multiprecision::pow(bigint(10), m_fractionalDigits); } else return bigint(0); } TypeResult FixedPointType::binaryOperatorResult(Token _operator, Type const* _other) const { auto commonType = Type::commonType(this, _other); if (!commonType) return nullptr; // All fixed types can be compared if (TokenTraits::isCompareOp(_operator)) return commonType; if (TokenTraits::isBitOp(_operator) || TokenTraits::isBooleanOp(_operator) || _operator == Token::Exp) return nullptr; return commonType; } IntegerType const* FixedPointType::asIntegerType() const { return TypeProvider::integer(numBits(), isSigned() ? IntegerType::Modifier::Signed : IntegerType::Modifier::Unsigned); } std::tuple<bool, rational> RationalNumberType::parseRational(std::string const& _value) { rational value; try { auto radixPoint = find(_value.begin(), _value.end(), '.'); if (radixPoint != _value.end()) { if ( !all_of(radixPoint + 1, _value.end(), util::isDigit) || !all_of(_value.begin(), radixPoint, util::isDigit) ) return std::make_tuple(false, rational(0)); // Only decimal notation allowed here, leading zeros would switch to octal. auto fractionalBegin = find_if_not( radixPoint + 1, _value.end(), [](char const& a) { return a == '0'; } ); rational numerator; rational denominator(1); denominator = bigint(std::string(fractionalBegin, _value.end())); denominator /= boost::multiprecision::pow( bigint(10), static_cast<unsigned>(distance(radixPoint + 1, _value.end())) ); numerator = bigint(std::string(_value.begin(), radixPoint)); value = numerator + denominator; } else value = bigint(_value); return std::make_tuple(true, value); } catch (...) { return std::make_tuple(false, rational(0)); } } std::tuple<bool, rational> RationalNumberType::isValidLiteral(Literal const& _literal) { rational value; try { ASTString valueString = _literal.valueWithoutUnderscores(); auto expPoint = find(valueString.begin(), valueString.end(), 'e'); if (expPoint == valueString.end()) expPoint = find(valueString.begin(), valueString.end(), 'E'); if (boost::starts_with(valueString, "0x")) { // process as hex value = bigint(valueString); } else if (expPoint != valueString.end()) { // Parse mantissa and exponent. Checks numeric limit. std::tuple<bool, rational> mantissa = parseRational(std::string(valueString.begin(), expPoint)); if (!std::get<0>(mantissa)) return std::make_tuple(false, rational(0)); value = std::get<1>(mantissa); // 0E... is always zero. if (value == 0) return std::make_tuple(true, rational(0)); bigint exp = bigint(std::string(expPoint + 1, valueString.end())); if (exp > std::numeric_limits<int32_t>::max() || exp < std::numeric_limits<int32_t>::min()) return std::make_tuple(false, rational(0)); uint32_t expAbs = bigint(abs(exp)).convert_to<uint32_t>(); if (exp < 0) { if (!fitsPrecisionBase10(abs(value.denominator()), expAbs)) return std::make_tuple(false, rational(0)); value /= boost::multiprecision::pow( bigint(10), expAbs ); } else if (exp > 0) { if (!fitsPrecisionBase10(abs(value.numerator()), expAbs)) return std::make_tuple(false, rational(0)); value *= boost::multiprecision::pow( bigint(10), expAbs ); } } else { // parse as rational number std::tuple<bool, rational> tmp = parseRational(valueString); if (!std::get<0>(tmp)) return tmp; value = std::get<1>(tmp); } } catch (...) { return std::make_tuple(false, rational(0)); } switch (_literal.subDenomination()) { case Literal::SubDenomination::None: case Literal::SubDenomination::Wei: case Literal::SubDenomination::Second: break; case Literal::SubDenomination::Gwei: value *= bigint("1000000000"); break; case Literal::SubDenomination::Ether: value *= bigint("1000000000000000000"); break; case Literal::SubDenomination::Minute: value *= bigint("60"); break; case Literal::SubDenomination::Hour: value *= bigint("3600"); break; case Literal::SubDenomination::Day: value *= bigint("86400"); break; case Literal::SubDenomination::Week: value *= bigint("604800"); break; case Literal::SubDenomination::Year: value *= bigint("31536000"); break; } return std::make_tuple(true, value); } BoolResult RationalNumberType::isImplicitlyConvertibleTo(Type const& _convertTo) const { switch (_convertTo.category()) { case Category::Integer: { if (isFractional()) return false; IntegerType const& targetType = dynamic_cast<IntegerType const&>(_convertTo); return fitsIntegerType(m_value.numerator(), targetType); } case Category::FixedPoint: { FixedPointType const& targetType = dynamic_cast<FixedPointType const&>(_convertTo); // Store a negative number into an unsigned. if (isNegative() && !targetType.isSigned()) return false; if (!isFractional()) return (targetType.minIntegerValue() <= m_value) && (m_value <= targetType.maxIntegerValue()); rational value = m_value * pow(bigint(10), targetType.fractionalDigits()); // Need explicit conversion since truncation will occur. if (value.denominator() != 1) return false; return fitsIntoBits(value.numerator(), targetType.numBits(), targetType.isSigned()); } case Category::FixedBytes: return (m_value == rational(0)) || (m_compatibleBytesType && *m_compatibleBytesType == _convertTo); default: return false; } } BoolResult RationalNumberType::isExplicitlyConvertibleTo(Type const& _convertTo) const { if (isImplicitlyConvertibleTo(_convertTo)) return true; auto category = _convertTo.category(); if (category == Category::FixedBytes) return false; else if (auto addressType = dynamic_cast<AddressType const*>(&_convertTo)) return (m_value == 0) || ((addressType->stateMutability() != StateMutability::Payable) && !isNegative() && !isFractional() && integerType() && (integerType()->numBits() <= 160)); else if (category == Category::Integer) return false; else if (auto enumType = dynamic_cast<EnumType const*>(&_convertTo)) if (isNegative() || isFractional() || m_value >= enumType->numberOfMembers()) return false; Type const* mobType = mobileType(); return (mobType && mobType->isExplicitlyConvertibleTo(_convertTo)); } TypeResult RationalNumberType::unaryOperatorResult(Token _operator) const { if (std::optional<rational> value = ConstantEvaluator::evaluateUnaryOperator(_operator, m_value)) return TypeResult{TypeProvider::rationalNumber(*value)}; else return nullptr; } TypeResult RationalNumberType::binaryOperatorResult(Token _operator, Type const* _other) const { if (_other->category() == Category::Integer || _other->category() == Category::FixedPoint) { if (isFractional()) return TypeResult::err("Fractional literals not supported."); else if (!integerType()) return TypeResult::err("Literal too large."); // Shift and exp are not symmetric, so it does not make sense to swap // the types as below. As an exception, we always use uint here. if (TokenTraits::isShiftOp(_operator)) { if (!isValidShiftAndAmountType(_operator, *_other)) return nullptr; return isNegative() ? TypeProvider::int256() : TypeProvider::uint256(); } else if (Token::Exp == _operator) { if (auto const* otherIntType = dynamic_cast<IntegerType const*>(_other)) { if (otherIntType->isSigned()) return TypeResult::err("Exponentiation power is not allowed to be a signed integer type."); } else if (dynamic_cast<FixedPointType const*>(_other)) return TypeResult::err("Exponent is fractional."); return isNegative() ? TypeProvider::int256() : TypeProvider::uint256(); } else { auto commonType = Type::commonType(this, _other); if (!commonType) return nullptr; return commonType->binaryOperatorResult(_operator, _other); } } else if (_other->category() != category()) return nullptr; RationalNumberType const& other = dynamic_cast<RationalNumberType const&>(*_other); if (TokenTraits::isCompareOp(_operator)) { // Since we do not have a "BoolConstantType", we have to do the actual comparison // at runtime and convert to mobile typse first. Such a comparison is not a very common // use-case and will be optimized away. Type const* thisMobile = mobileType(); Type const* otherMobile = other.mobileType(); if (!thisMobile || !otherMobile) return nullptr; return thisMobile->binaryOperatorResult(_operator, otherMobile); } else if (std::optional<rational> value = ConstantEvaluator::evaluateBinaryOperator(_operator, m_value, other.m_value)) { // verify that numerator and denominator fit into 4096 bit after every operation if (value->numerator() != 0 && std::max(boost::multiprecision::msb(abs(value->numerator())), boost::multiprecision::msb(abs(value->denominator()))) > 4096) return TypeResult::err("Precision of rational constants is limited to 4096 bits."); return TypeResult{TypeProvider::rationalNumber(*value)}; } else return nullptr; } std::string RationalNumberType::richIdentifier() const { // rational seemingly will put the sign always on the numerator, // but let just make it deterministic here. bigint numerator = abs(m_value.numerator()); bigint denominator = abs(m_value.denominator()); if (m_value < 0) return "t_rational_minus_" + numerator.str() + "_by_" + denominator.str(); else return "t_rational_" + numerator.str() + "_by_" + denominator.str(); } bool RationalNumberType::operator==(Type const& _other) const { if (_other.category() != category()) return false; RationalNumberType const& other = dynamic_cast<RationalNumberType const&>(_other); return m_value == other.m_value; } std::string RationalNumberType::bigintToReadableString(bigint const& _num) { std::string str = _num.str(); if (str.size() > 32) { size_t omitted = str.size() - 8; str = str.substr(0, 4) + "...(" + std::to_string(omitted) + " digits omitted)..." + str.substr(str.size() - 4, 4); } return str; } std::string RationalNumberType::toString(bool) const { if (!isFractional()) return "int_const " + bigintToReadableString(m_value.numerator()); std::string numerator = bigintToReadableString(m_value.numerator()); std::string denominator = bigintToReadableString(m_value.denominator()); return "rational_const " + numerator + " / " + denominator; } u256 RationalNumberType::literalValue(Literal const*) const { // We ignore the literal and hope that the type was correctly determined to represent // its value. u256 value; bigint shiftedValue; if (!isFractional()) shiftedValue = m_value.numerator(); else { auto fixed = fixedPointType(); solAssert(fixed, "Rational number cannot be represented as fixed point type."); unsigned fractionalDigits = fixed->fractionalDigits(); shiftedValue = m_value.numerator() * boost::multiprecision::pow(bigint(10), fractionalDigits) / m_value.denominator(); } // we ignore the literal and hope that the type was correctly determined solAssert(shiftedValue <= u256(-1), "Number constant too large."); solAssert(shiftedValue >= -(bigint(1) << 255), "Number constant too small."); if (m_value >= rational(0)) value = u256(shiftedValue); else value = s2u(s256(shiftedValue)); return value; } Type const* RationalNumberType::mobileType() const { if (!isFractional()) return integerType(); else return fixedPointType(); } IntegerType const* RationalNumberType::integerType() const { solAssert(!isFractional(), "integerType() called for fractional number."); bigint value = m_value.numerator(); bool negative = (value < 0); if (negative) // convert to positive number of same bit requirements value = ((0 - value) - 1) << 1; if (value > u256(-1)) return nullptr; else return TypeProvider::integer( std::max(numberEncodingSize(value), 1u) * 8, negative ? IntegerType::Modifier::Signed : IntegerType::Modifier::Unsigned ); } FixedPointType const* RationalNumberType::fixedPointType() const { bool negative = (m_value < 0); unsigned fractionalDigits = 0; rational value = abs(m_value); // We care about the sign later. rational maxValue = negative ? rational(bigint(1) << 255, 1): rational((bigint(1) << 256) - 1, 1); while (value * 10 <= maxValue && value.denominator() != 1 && fractionalDigits < 80) { value *= 10; fractionalDigits++; } if (value > maxValue) return nullptr; // This means we round towards zero for positive and negative values. bigint v = value.numerator() / value.denominator(); if (negative && v != 0) // modify value to satisfy bit requirements for negative numbers: // add one bit for sign and decrement because negative numbers can be larger v = (v - 1) << 1; if (v > u256(-1)) return nullptr; unsigned totalBits = std::max(numberEncodingSize(v), 1u) * 8; solAssert(totalBits <= 256, ""); return TypeProvider::fixedPoint( totalBits, fractionalDigits, negative ? FixedPointType::Modifier::Signed : FixedPointType::Modifier::Unsigned ); } StringLiteralType::StringLiteralType(Literal const& _literal): m_value(_literal.value()) { } StringLiteralType::StringLiteralType(std::string _value): m_value{std::move(_value)} { } BoolResult StringLiteralType::isImplicitlyConvertibleTo(Type const& _convertTo) const { if (auto fixedBytes = dynamic_cast<FixedBytesType const*>(&_convertTo)) { if (static_cast<size_t>(fixedBytes->numBytes()) < m_value.size()) return BoolResult::err("Literal is larger than the type."); return true; } else if (auto arrayType = dynamic_cast<ArrayType const*>(&_convertTo)) { size_t invalidSequence; if (arrayType->isString() && !util::validateUTF8(value(), invalidSequence)) return BoolResult::err( "Contains invalid UTF-8 sequence at position " + util::toString(invalidSequence) + "." ); return arrayType->location() != DataLocation::CallData && arrayType->isByteArrayOrString() && !(arrayType->dataStoredIn(DataLocation::Storage) && arrayType->isPointer()); } else return false; } std::string StringLiteralType::richIdentifier() const { // Since we have to return a valid identifier and the std::string itself may contain // anything, we hash it. return "t_stringliteral_" + util::toHex(util::keccak256(m_value).asBytes()); } bool StringLiteralType::operator==(Type const& _other) const { if (_other.category() != category()) return false; return m_value == dynamic_cast<StringLiteralType const&>(_other).m_value; } std::string StringLiteralType::toString(bool) const { auto isPrintableASCII = [](std::string const& s) { for (auto c: s) { if (static_cast<unsigned>(c) <= 0x1f || static_cast<unsigned>(c) >= 0x7f) return false; } return true; }; return isPrintableASCII(m_value) ? ("literal_string \"" + m_value + "\"") : ("literal_string hex\"" + util::toHex(util::asBytes(m_value)) + "\""); } Type const* StringLiteralType::mobileType() const { return TypeProvider::stringMemory(); } FixedBytesType::FixedBytesType(unsigned _bytes): m_bytes(_bytes) { solAssert( m_bytes > 0 && m_bytes <= 32, "Invalid byte number for fixed bytes type: " + util::toString(m_bytes) ); } BoolResult FixedBytesType::isImplicitlyConvertibleTo(Type const& _convertTo) const { if (_convertTo.category() != category()) return false; FixedBytesType const& convertTo = dynamic_cast<FixedBytesType const&>(_convertTo); return convertTo.m_bytes >= m_bytes; } BoolResult FixedBytesType::isExplicitlyConvertibleTo(Type const& _convertTo) const { if (_convertTo.category() == category()) return true; else if (auto integerType = dynamic_cast<IntegerType const*>(&_convertTo)) return (!integerType->isSigned() && integerType->numBits() == numBytes() * 8); else if (auto addressType = dynamic_cast<AddressType const*>(&_convertTo)) return (addressType->stateMutability() != StateMutability::Payable) && (numBytes() == 20); else if (auto fixedPointType = dynamic_cast<FixedPointType const*>(&_convertTo)) return fixedPointType->numBits() == numBytes() * 8; return false; } TypeResult FixedBytesType::unaryOperatorResult(Token _operator) const { // "delete" and "~" is okay for FixedBytesType if (_operator == Token::Delete) return TypeResult{TypeProvider::emptyTuple()}; else if (_operator == Token::BitNot) return this; return nullptr; } TypeResult FixedBytesType::binaryOperatorResult(Token _operator, Type const* _other) const { if (TokenTraits::isShiftOp(_operator)) { if (isValidShiftAndAmountType(_operator, *_other)) return this; else return nullptr; } auto commonType = dynamic_cast<FixedBytesType const*>(Type::commonType(this, _other)); if (!commonType) return nullptr; // FixedBytes can be compared and have bitwise operators applied to them if (TokenTraits::isCompareOp(_operator) || TokenTraits::isBitOp(_operator)) return TypeResult(commonType); return nullptr; } MemberList::MemberMap FixedBytesType::nativeMembers(ASTNode const*) const { return MemberList::MemberMap{MemberList::Member{"length", TypeProvider::uint(8)}}; } std::string FixedBytesType::richIdentifier() const { return "t_bytes" + std::to_string(m_bytes); } bool FixedBytesType::operator==(Type const& _other) const { if (_other.category() != category()) return false; FixedBytesType const& other = dynamic_cast<FixedBytesType const&>(_other); return other.m_bytes == m_bytes; } u256 BoolType::literalValue(Literal const* _literal) const { solAssert(_literal, ""); if (_literal->token() == Token::TrueLiteral) return u256(1); else if (_literal->token() == Token::FalseLiteral) return u256(0); else solAssert(false, "Bool type constructed from non-boolean literal."); } TypeResult BoolType::unaryOperatorResult(Token _operator) const { if (_operator == Token::Delete) return TypeProvider::emptyTuple(); else if (_operator == Token::Not) return this; else return nullptr; } TypeResult BoolType::binaryOperatorResult(Token _operator, Type const* _other) const { if (category() != _other->category()) return nullptr; if (_operator == Token::Equal || _operator == Token::NotEqual || _operator == Token::And || _operator == Token::Or) return _other; else return nullptr; } Type const* ContractType::encodingType() const { if (isSuper()) return nullptr; if (isPayable()) return TypeProvider::payableAddress(); else return TypeProvider::address(); } BoolResult ContractType::isImplicitlyConvertibleTo(Type const& _convertTo) const { if (m_super) return false; if (*this == _convertTo) return true; if (_convertTo.category() == Category::Contract) { auto const& targetContractType = dynamic_cast<ContractType const&>(_convertTo); if (targetContractType.isSuper()) return false; auto const& bases = contractDefinition().annotation().linearizedBaseContracts; return find( bases.begin(), bases.end(), &targetContractType.contractDefinition() ) != bases.end(); } return false; } BoolResult ContractType::isExplicitlyConvertibleTo(Type const& _convertTo) const { if (m_super) return false; if (auto const* addressType = dynamic_cast<AddressType const*>(&_convertTo)) return isPayable() || (addressType->stateMutability() < StateMutability::Payable); return isImplicitlyConvertibleTo(_convertTo); } bool ContractType::isPayable() const { auto receiveFunction = m_contract.receiveFunction(); auto fallbackFunction = m_contract.fallbackFunction(); return receiveFunction || (fallbackFunction && fallbackFunction->isPayable()); } TypeResult ContractType::unaryOperatorResult(Token _operator) const { if (isSuper()) return nullptr; else if (_operator == Token::Delete) return TypeProvider::emptyTuple(); else return nullptr; } std::vector<Type const*> CompositeType::fullDecomposition() const { std::vector<Type const*> res = {this}; std::unordered_set<std::string> seen = {richIdentifier()}; for (size_t k = 0; k < res.size(); ++k) if (auto composite = dynamic_cast<CompositeType const*>(res[k])) for (Type const* next: composite->decomposition()) if (seen.count(next->richIdentifier()) == 0) { seen.insert(next->richIdentifier()); res.push_back(next); } return res; } Type const* ReferenceType::withLocation(DataLocation _location, bool _isPointer) const { return TypeProvider::withLocation(this, _location, _isPointer); } TypeResult ReferenceType::unaryOperatorResult(Token _operator) const { if (_operator != Token::Delete) return nullptr; // delete can be used on everything except calldata references or storage pointers // (storage references are ok) switch (location()) { case DataLocation::CallData: return nullptr; case DataLocation::Memory: return TypeProvider::emptyTuple(); case DataLocation::Storage: return isPointer() ? nullptr : TypeProvider::emptyTuple(); case DataLocation::Transient: solUnimplemented("Transient data location is only supported for value types."); } return nullptr; } bool ReferenceType::isPointer() const { if (m_location == DataLocation::Storage) return m_isPointer; else return true; } Type const* ReferenceType::copyForLocationIfReference(Type const* _type) const { return TypeProvider::withLocationIfReference(m_location, _type); } std::string ReferenceType::stringForReferencePart() const { switch (m_location) { case DataLocation::Storage: return std::string("storage ") + (isPointer() ? "pointer" : "ref"); case DataLocation::CallData: return "calldata"; case DataLocation::Memory: return "memory"; case DataLocation::Transient: solUnimplemented("Transient data location is only supported for value types."); break; } solAssert(false, ""); return ""; } std::string ReferenceType::identifierLocationSuffix() const { std::string id; switch (location()) { case DataLocation::Storage: id += "_storage"; break; case DataLocation::Transient: solUnimplemented("Transient data location is only supported for value types."); break; case DataLocation::Memory: id += "_memory"; break; case DataLocation::CallData: id += "_calldata"; break; } if (isPointer()) id += "_ptr"; return id; } ArrayType::ArrayType(DataLocation _location, bool _isString): ReferenceType(_location), m_arrayKind(_isString ? ArrayKind::String : ArrayKind::Bytes), m_baseType{TypeProvider::byte()} { } void ArrayType::clearCache() const { Type::clearCache(); m_interfaceType.reset(); m_interfaceType_library.reset(); } BoolResult ArrayType::isImplicitlyConvertibleTo(Type const& _convertTo) const { if (_convertTo.category() != category()) return false; auto& convertTo = dynamic_cast<ArrayType const&>(_convertTo); if (convertTo.isByteArray() != isByteArray() || convertTo.isString() != isString()) return false; // memory/calldata to storage can be converted, but only to a direct storage reference if (convertTo.location() == DataLocation::Storage && location() != DataLocation::Storage && convertTo.isPointer()) return false; if (convertTo.location() == DataLocation::CallData && location() != convertTo.location()) return false; if (convertTo.location() == DataLocation::Storage && !convertTo.isPointer()) { // Less restrictive conversion, since we need to copy anyway. if (!baseType()->isImplicitlyConvertibleTo(*convertTo.baseType())) return false; if (convertTo.isDynamicallySized()) return true; return !isDynamicallySized() && convertTo.length() >= length(); } else { // Conversion to storage pointer or to memory, we de not copy element-for-element here, so // require that the base type is the same, not only convertible. // This disallows assignment of nested dynamic arrays from storage to memory for now. if ( *TypeProvider::withLocationIfReference(location(), baseType()) != *TypeProvider::withLocationIfReference(location(), convertTo.baseType()) ) return false; if (isDynamicallySized() != convertTo.isDynamicallySized()) return false; // We also require that the size is the same. if (!isDynamicallySized() && length() != convertTo.length()) return false; return true; } } BoolResult ArrayType::isExplicitlyConvertibleTo(Type const& _convertTo) const { if (isImplicitlyConvertibleTo(_convertTo)) return true; // allow conversion bytes <-> std::string and bytes -> bytesNN if (_convertTo.category() != category()) return isByteArray() && _convertTo.category() == Type::Category::FixedBytes; auto& convertTo = dynamic_cast<ArrayType const&>(_convertTo); if (convertTo.location() != location()) return false; if (!isByteArrayOrString() || !convertTo.isByteArrayOrString()) return false; return true; } std::string ArrayType::richIdentifier() const { std::string id; if (isString()) id = "t_string"; else if (isByteArrayOrString()) id = "t_bytes"; else { id = "t_array"; id += identifierList(baseType()); if (isDynamicallySized()) id += "dyn"; else id += length().str(); } id += identifierLocationSuffix(); return id; } bool ArrayType::operator==(Type const& _other) const { if (_other.category() != category()) return false; ArrayType const& other = dynamic_cast<ArrayType const&>(_other); if ( !equals(other) || other.isByteArray() != isByteArray() || other.isString() != isString() || other.isDynamicallySized() != isDynamicallySized() ) return false; if (*other.baseType() != *baseType()) return false; return isDynamicallySized() || length() == other.length(); } BoolResult ArrayType::validForLocation(DataLocation _loc) const { if (auto arrayBaseType = dynamic_cast<ArrayType const*>(baseType())) { BoolResult result = arrayBaseType->validForLocation(_loc); if (!result) return result; } if (isDynamicallySized()) return true; switch (_loc) { case DataLocation::Memory: { bigint size = bigint(length()); auto type = m_baseType; while (auto arrayType = dynamic_cast<ArrayType const*>(type)) { if (arrayType->isDynamicallySized()) break; else { size *= arrayType->length(); type = arrayType->baseType(); } } if (type->isDynamicallySized()) size *= type->memoryHeadSize(); else size *= type->memoryDataSize(); if (size >= std::numeric_limits<unsigned>::max()) return BoolResult::err("Type too large for memory."); break; } case DataLocation::CallData: { if (unlimitedStaticCalldataSize(true) >= std::numeric_limits<unsigned>::max()) return BoolResult::err("Type too large for calldata."); break; } case DataLocation::Storage: if (storageSizeUpperBound() >= bigint(1) << 256) return BoolResult::err("Type too large for storage."); break; case DataLocation::Transient: solUnimplemented("Transient data location is only supported for value types."); break; } return true; } bigint ArrayType::unlimitedStaticCalldataSize(bool _padded) const { solAssert(!isDynamicallySized(), ""); bigint size = bigint(length()) * calldataStride(); if (_padded) size = ((size + 31) / 32) * 32; return size; } unsigned ArrayType::calldataEncodedSize(bool _padded) const { solAssert(!isDynamicallyEncoded(), ""); bigint size = unlimitedStaticCalldataSize(_padded); solAssert(size <= std::numeric_limits<unsigned>::max(), "Array size does not fit unsigned."); return unsigned(size); } unsigned ArrayType::calldataEncodedTailSize() const { solAssert(isDynamicallyEncoded(), ""); if (isDynamicallySized()) // We do not know the dynamic length itself, but at least the uint256 containing the // length must still be present. return 32; bigint size = unlimitedStaticCalldataSize(false); solAssert(size <= std::numeric_limits<unsigned>::max(), "Array size does not fit unsigned."); return unsigned(size); } bool ArrayType::isDynamicallyEncoded() const { return isDynamicallySized() || baseType()->isDynamicallyEncoded(); } bigint ArrayType::storageSizeUpperBound() const { if (isDynamicallySized()) return 1; else return length() * baseType()->storageSizeUpperBound(); } u256 ArrayType::storageSize() const { if (isDynamicallySized()) return 1; bigint size; unsigned baseBytes = baseType()->storageBytes(); if (baseBytes == 0) size = 1; else if (baseBytes < 32) { unsigned itemsPerSlot = 32 / baseBytes; size = (bigint(length()) + (itemsPerSlot - 1)) / itemsPerSlot; } else size = bigint(length()) * baseType()->storageSize(); solAssert(size < bigint(1) << 256, "Array too large for storage."); return std::max<u256>(1, u256(size)); } std::vector<std::tuple<std::string, Type const*>> ArrayType::makeStackItems() const { switch (m_location) { case DataLocation::CallData: if (isDynamicallySized()) return {std::make_tuple("offset", TypeProvider::uint256()), std::make_tuple("length", TypeProvider::uint256())}; else return {std::make_tuple("offset", TypeProvider::uint256())}; case DataLocation::Memory: return {std::make_tuple("mpos", TypeProvider::uint256())}; case DataLocation::Storage: // byte offset inside storage value is omitted return {std::make_tuple("slot", TypeProvider::uint256())}; case DataLocation::Transient: solUnimplemented("Transient data location is only supported for value types."); break; } solAssert(false, ""); } std::string ArrayType::toString(bool _withoutDataLocation) const { std::string ret; if (isString()) ret = "string"; else if (isByteArrayOrString()) ret = "bytes"; else { ret = baseType()->toString(_withoutDataLocation) + "["; if (!isDynamicallySized()) ret += length().str(); ret += "]"; } if (!_withoutDataLocation) ret += " " + stringForReferencePart(); return ret; } std::string ArrayType::humanReadableName() const { std::string ret; if (isString()) ret = "string"; else if (isByteArrayOrString()) ret = "bytes"; else { ret = baseType()->toString(true) + "["; if (!isDynamicallySized()) ret += length().str(); ret += "]"; } ret += " " + stringForReferencePart(); return ret; } std::string ArrayType::canonicalName() const { std::string ret; if (isString()) ret = "string"; else if (isByteArrayOrString()) ret = "bytes"; else { ret = baseType()->canonicalName() + "["; if (!isDynamicallySized()) ret += length().str(); ret += "]"; } return ret; } std::string ArrayType::signatureInExternalFunction(bool _structsByName) const { if (isByteArrayOrString()) return canonicalName(); else { solAssert(baseType(), ""); return baseType()->signatureInExternalFunction(_structsByName) + "[" + (isDynamicallySized() ? "" : length().str()) + "]"; } } MemberList::MemberMap ArrayType::nativeMembers(ASTNode const*) const { MemberList::MemberMap members; if (!isString()) { members.emplace_back("length", TypeProvider::uint256()); if (isDynamicallySized() && location() == DataLocation::Storage) { Type const* thisAsPointer = TypeProvider::withLocation(this, location(), true); members.emplace_back("push", TypeProvider::function( TypePointers{thisAsPointer}, TypePointers{baseType()}, strings{std::string()}, strings{std::string()}, FunctionType::Kind::ArrayPush )->withBoundFirstArgument()); members.emplace_back("push", TypeProvider::function( TypePointers{thisAsPointer, baseType()}, TypePointers{}, strings{std::string(),std::string()}, strings{}, FunctionType::Kind::ArrayPush )->withBoundFirstArgument()); members.emplace_back("pop", TypeProvider::function( TypePointers{thisAsPointer}, TypePointers{}, strings{std::string()}, strings{}, FunctionType::Kind::ArrayPop )->withBoundFirstArgument()); } } return members; } Type const* ArrayType::encodingType() const { if (location() == DataLocation::Storage) return TypeProvider::uint256(); else return TypeProvider::withLocation(this, DataLocation::Memory, true); } Type const* ArrayType::decodingType() const { if (location() == DataLocation::Storage) return TypeProvider::uint256(); else return this; } TypeResult ArrayType::interfaceType(bool _inLibrary) const { if (_inLibrary && m_interfaceType_library.has_value()) return *m_interfaceType_library; if (!_inLibrary && m_interfaceType.has_value()) return *m_interfaceType; TypeResult result{nullptr}; TypeResult baseInterfaceType = m_baseType->interfaceType(_inLibrary); if (!baseInterfaceType.get()) { solAssert(!baseInterfaceType.message().empty(), "Expected detailed error message!"); result = baseInterfaceType; } else if (_inLibrary && location() == DataLocation::Storage) result = this; else if (m_arrayKind != ArrayKind::Ordinary) result = TypeProvider::withLocation(this, DataLocation::Memory, true); else if (isDynamicallySized()) result = TypeProvider::array(DataLocation::Memory, baseInterfaceType); else result = TypeProvider::array(DataLocation::Memory, baseInterfaceType, m_length); if (_inLibrary) m_interfaceType_library = result; else m_interfaceType = result; return result; } Type const* ArrayType::finalBaseType(bool _breakIfDynamicArrayType) const { Type const* finalBaseType = this; while (auto arrayType = dynamic_cast<ArrayType const*>(finalBaseType)) { if (_breakIfDynamicArrayType && arrayType->isDynamicallySized()) break; finalBaseType = arrayType->baseType(); } return finalBaseType; } u256 ArrayType::memoryDataSize() const { solAssert(!isDynamicallySized(), ""); solAssert(m_location == DataLocation::Memory, ""); solAssert(!isByteArrayOrString(), ""); bigint size = bigint(m_length) * m_baseType->memoryHeadSize(); solAssert(size <= std::numeric_limits<u256>::max(), "Array size does not fit u256."); return u256(size); } std::unique_ptr<ReferenceType> ArrayType::copyForLocation(DataLocation _location, bool _isPointer) const { auto copy = std::make_unique<ArrayType>(_location); if (_location == DataLocation::Storage) copy->m_isPointer = _isPointer; copy->m_arrayKind = m_arrayKind; copy->m_baseType = copy->copyForLocationIfReference(m_baseType); copy->m_hasDynamicLength = m_hasDynamicLength; copy->m_length = m_length; return copy; } BoolResult ArraySliceType::isImplicitlyConvertibleTo(Type const& _other) const { return (*this) == _other || ( m_arrayType.dataStoredIn(DataLocation::CallData) && m_arrayType.isDynamicallySized() && m_arrayType.isImplicitlyConvertibleTo(_other) ); } BoolResult ArraySliceType::isExplicitlyConvertibleTo(Type const& _convertTo) const { return isImplicitlyConvertibleTo(_convertTo) || m_arrayType.isExplicitlyConvertibleTo(_convertTo); } std::string ArraySliceType::richIdentifier() const { return m_arrayType.richIdentifier() + "_slice"; } bool ArraySliceType::operator==(Type const& _other) const { if (auto const* other = dynamic_cast<ArraySliceType const*>(&_other)) return m_arrayType == other->m_arrayType; return false; } std::string ArraySliceType::toString(bool _withoutDataLocation) const { return m_arrayType.toString(_withoutDataLocation) + " slice"; } std::string ArraySliceType::humanReadableName() const { return m_arrayType.humanReadableName() + " slice"; } Type const* ArraySliceType::mobileType() const { if ( m_arrayType.dataStoredIn(DataLocation::CallData) && m_arrayType.isDynamicallySized() && !m_arrayType.baseType()->isDynamicallyEncoded() ) return &m_arrayType; else return this; } std::vector<std::tuple<std::string, Type const*>> ArraySliceType::makeStackItems() const { return {{"offset", TypeProvider::uint256()}, {"length", TypeProvider::uint256()}}; } std::string ContractType::richIdentifier() const { return (m_super ? "t_super" : "t_contract") + parenthesizeUserIdentifier(m_contract.name()) + std::to_string(m_contract.id()); } bool ContractType::operator==(Type const& _other) const { if (_other.category() != category()) return false; ContractType const& other = dynamic_cast<ContractType const&>(_other); return other.m_contract == m_contract && other.m_super == m_super; } std::string ContractType::toString(bool) const { return std::string(m_contract.isLibrary() ? "library " : "contract ") + std::string(m_super ? "super " : "") + m_contract.name(); } std::string ContractType::canonicalName() const { return *m_contract.annotation().canonicalName; } MemberList::MemberMap ContractType::nativeMembers(ASTNode const*) const { MemberList::MemberMap members; solAssert(!m_super, ""); if (!m_contract.isLibrary()) for (auto const& it: m_contract.interfaceFunctions()) members.emplace_back( &it.second->declaration(), it.second->asExternallyCallableFunction(m_contract.isLibrary()) ); return members; } FunctionType const* ContractType::newExpressionType() const { if (!m_constructorType) m_constructorType = FunctionType::newExpressionType(m_contract); return m_constructorType; } std::vector<std::tuple<VariableDeclaration const*, u256, unsigned>> ContractType::stateVariables(DataLocation _location) const { VariableDeclaration::Location location; switch (_location) { case DataLocation::Storage: location = VariableDeclaration::Location::Unspecified; break; case DataLocation::Transient: location = VariableDeclaration::Location::Transient; break; default: solAssert(false); } std::vector<VariableDeclaration const*> variables; for (ContractDefinition const* contract: m_contract.annotation().linearizedBaseContracts | ranges::views::reverse) for (VariableDeclaration const* variable: contract->stateVariables()) if (!(variable->isConstant() || variable->immutable()) && variable->referenceLocation() == location) variables.push_back(variable); TypePointers types; for (auto variable: variables) types.push_back(variable->annotation().type); StorageOffsets offsets; offsets.computeOffsets(types); std::vector<std::tuple<VariableDeclaration const*, u256, unsigned>> variablesAndOffsets; for (size_t index = 0; index < variables.size(); ++index) if (auto const* offset = offsets.offset(index)) variablesAndOffsets.emplace_back(variables[index], offset->first, offset->second); return variablesAndOffsets; } std::vector<VariableDeclaration const*> ContractType::immutableVariables() const { std::vector<VariableDeclaration const*> variables; for (ContractDefinition const* contract: m_contract.annotation().linearizedBaseContracts | ranges::views::reverse) for (VariableDeclaration const* variable: contract->stateVariables()) if (variable->immutable()) variables.push_back(variable); return variables; } std::vector<std::tuple<std::string, Type const*>> ContractType::makeStackItems() const { if (m_super) return {}; else return {std::make_tuple("address", isPayable() ? TypeProvider::payableAddress() : TypeProvider::address())}; } void StructType::clearCache() const { Type::clearCache(); m_interfaceType.reset(); m_interfaceType_library.reset(); } Type const* StructType::encodingType() const { if (location() != DataLocation::Storage) return this; return TypeProvider::uint256(); } BoolResult StructType::isImplicitlyConvertibleTo(Type const& _convertTo) const { if (_convertTo.category() != category()) return false; auto& convertTo = dynamic_cast<StructType const&>(_convertTo); // memory/calldata to storage can be converted, but only to a direct storage reference if (convertTo.location() == DataLocation::Storage && location() != DataLocation::Storage && convertTo.isPointer()) return false; if (convertTo.location() == DataLocation::CallData && location() != convertTo.location()) return false; return this->m_struct == convertTo.m_struct; } std::string StructType::richIdentifier() const { return "t_struct" + parenthesizeUserIdentifier(m_struct.name()) + std::to_string(m_struct.id()) + identifierLocationSuffix(); } bool StructType::operator==(Type const& _other) const { if (_other.category() != category()) return false; StructType const& other = dynamic_cast<StructType const&>(_other); return equals(other) && other.m_struct == m_struct; } unsigned StructType::calldataEncodedSize(bool) const { solAssert(!isDynamicallyEncoded(), ""); unsigned size = 0; for (auto const& member: members(nullptr)) { solAssert(!member.type->containsNestedMapping(), ""); // Struct members are always padded. size += member.type->calldataEncodedSize(); } return size; } unsigned StructType::calldataEncodedTailSize() const { solAssert(isDynamicallyEncoded(), ""); unsigned size = 0; for (auto const& member: members(nullptr)) { solAssert(!member.type->containsNestedMapping(), ""); // Struct members are always padded. size += member.type->calldataHeadSize(); } return size; } unsigned StructType::calldataOffsetOfMember(std::string const& _member) const { unsigned offset = 0; for (auto const& member: members(nullptr)) { solAssert(!member.type->containsNestedMapping(), ""); if (member.name == _member) return offset; // Struct members are always padded. offset += member.type->calldataHeadSize(); } solAssert(false, "Struct member not found."); } bool StructType::isDynamicallyEncoded() const { if (recursive()) return true; solAssert(interfaceType(false).get(), ""); for (auto t: memoryMemberTypes()) { solAssert(t, "Parameter should have external type."); t = t->interfaceType(false); if (t->isDynamicallyEncoded()) return true; } return false; } u256 StructType::memoryDataSize() const { u256 size; for (auto const& t: memoryMemberTypes()) size += t->memoryHeadSize(); return size; } bigint StructType::storageSizeUpperBound() const { bigint size = 1; for (auto const& member: members(nullptr)) size += member.type->storageSizeUpperBound(); return size; } u256 StructType::storageSize() const { return std::max<u256>(1, members(nullptr).storageSize()); } bool StructType::containsNestedMapping() const { if (!m_struct.annotation().containsNestedMapping.has_value()) { bool hasNestedMapping = false; util::BreadthFirstSearch<StructDefinition const*> breadthFirstSearch{{&m_struct}}; breadthFirstSearch.run( [&](StructDefinition const* _struct, auto&& _addChild) { for (auto const& member: _struct->members()) { Type const* memberType = member->annotation().type; solAssert(memberType, ""); if (auto arrayType = dynamic_cast<ArrayType const*>(memberType)) memberType = arrayType->finalBaseType(false); if (dynamic_cast<MappingType const*>(memberType)) { hasNestedMapping = true; breadthFirstSearch.abort(); } else if (auto structType = dynamic_cast<StructType const*>(memberType)) _addChild(&structType->structDefinition()); } }); m_struct.annotation().containsNestedMapping = hasNestedMapping; } return m_struct.annotation().containsNestedMapping.value(); } std::string StructType::toString(bool _withoutDataLocation) const { std::string ret = "struct " + *m_struct.annotation().canonicalName; if (!_withoutDataLocation) ret += " " + stringForReferencePart(); return ret; } MemberList::MemberMap StructType::nativeMembers(ASTNode const*) const { MemberList::MemberMap members; for (ASTPointer<VariableDeclaration> const& variable: m_struct.members()) { Type const* type = variable->annotation().type; solAssert(type, ""); solAssert(!(location() != DataLocation::Storage && type->containsNestedMapping()), ""); members.emplace_back( variable.get(), copyForLocationIfReference(type) ); } return members; } TypeResult StructType::interfaceType(bool _inLibrary) const { if (!_inLibrary) { if (!m_interfaceType.has_value()) { if (recursive()) m_interfaceType = TypeResult::err("Recursive type not allowed for public or external contract functions."); else { TypeResult result{nullptr}; for (ASTPointer<VariableDeclaration> const& member: m_struct.members()) { if (!member->annotation().type) { result = TypeResult::err("Invalid type!"); break; } auto interfaceType = member->annotation().type->interfaceType(false); if (!interfaceType.get()) { solAssert(!interfaceType.message().empty(), "Expected detailed error message!"); result = interfaceType; break; } } if (result.message().empty()) m_interfaceType = TypeProvider::withLocation(this, DataLocation::Memory, true); else m_interfaceType = result; } } return *m_interfaceType; } else if (m_interfaceType_library.has_value()) return *m_interfaceType_library; TypeResult result{nullptr}; if (recursive() && !(_inLibrary && location() == DataLocation::Storage)) return TypeResult::err( "Recursive structs can only be passed as storage pointers to libraries, " "not as memory objects to contract functions." ); util::BreadthFirstSearch<StructDefinition const*> breadthFirstSearch{{&m_struct}}; breadthFirstSearch.run( [&](StructDefinition const* _struct, auto&& _addChild) { // Check that all members have interface types. // Return an error if at least one struct member does not have a type. // This might happen, for example, if the type of the member does not exist. for (ASTPointer<VariableDeclaration> const& variable: _struct->members()) { // If the struct member does not have a type return false. // A TypeError is expected in this case. if (!variable->annotation().type) { result = TypeResult::err("Invalid type!"); breadthFirstSearch.abort(); return; } Type const* memberType = variable->annotation().type; while ( memberType->category() == Type::Category::Array || memberType->category() == Type::Category::Mapping ) { if (auto arrayType = dynamic_cast<ArrayType const*>(memberType)) memberType = arrayType->finalBaseType(false); else if (auto mappingType = dynamic_cast<MappingType const*>(memberType)) memberType = mappingType->valueType(); } if (StructType const* innerStruct = dynamic_cast<StructType const*>(memberType)) _addChild(&innerStruct->structDefinition()); else { auto iType = memberType->interfaceType(_inLibrary); if (!iType.get()) { solAssert(!iType.message().empty(), "Expected detailed error message!"); result = iType; breadthFirstSearch.abort(); return; } } } } ); if (!result.message().empty()) return result; if (location() == DataLocation::Storage) m_interfaceType_library = this; else m_interfaceType_library = TypeProvider::withLocation(this, DataLocation::Memory, true); return *m_interfaceType_library; } Declaration const* StructType::typeDefinition() const { return &structDefinition(); } BoolResult StructType::validForLocation(DataLocation _loc) const { for (auto const& member: m_struct.members()) if (auto referenceType = dynamic_cast<ReferenceType const*>(member->annotation().type)) { BoolResult result = referenceType->validForLocation(_loc); if (!result) return result; } if ( _loc == DataLocation::Storage && storageSizeUpperBound() >= bigint(1) << 256 ) return BoolResult::err("Type too large for storage."); return true; } bool StructType::recursive() const { solAssert(m_struct.annotation().recursive.has_value(), "Called StructType::recursive() before DeclarationTypeChecker."); return *m_struct.annotation().recursive; } std::unique_ptr<ReferenceType> StructType::copyForLocation(DataLocation _location, bool _isPointer) const { auto copy = std::make_unique<StructType>(m_struct, _location); if (_location == DataLocation::Storage) copy->m_isPointer = _isPointer; return copy; } std::string StructType::signatureInExternalFunction(bool _structsByName) const { if (_structsByName) return canonicalName(); else { TypePointers memberTypes = memoryMemberTypes(); auto memberTypeStrings = memberTypes | ranges::views::transform([&](Type const* _t) -> std::string { solAssert(_t, "Parameter should have external type."); auto t = _t->interfaceType(_structsByName); solAssert(t.get(), ""); return t.get()->signatureInExternalFunction(_structsByName); }); return "(" + boost::algorithm::join(memberTypeStrings, ",") + ")"; } } std::string StructType::canonicalName() const { return *m_struct.annotation().canonicalName; } FunctionTypePointer StructType::constructorType() const { TypePointers paramTypes; strings paramNames; solAssert(!containsNestedMapping(), ""); for (auto const& member: members(nullptr)) { paramNames.push_back(member.name); paramTypes.push_back(TypeProvider::withLocationIfReference(DataLocation::Memory, member.type)); } return TypeProvider::function( paramTypes, TypePointers{TypeProvider::withLocation(this, DataLocation::Memory, false)}, paramNames, strings(1, ""), FunctionType::Kind::Internal ); } std::pair<u256, unsigned> const& StructType::storageOffsetsOfMember(std::string const& _name) const { auto const* offsets = members(nullptr).memberStorageOffset(_name); solAssert(offsets, "Storage offset of non-existing member requested."); return *offsets; } u256 StructType::memoryOffsetOfMember(std::string const& _name) const { u256 offset; for (auto const& member: members(nullptr)) if (member.name == _name) return offset; else offset += member.type->memoryHeadSize(); solAssert(false, "Member not found in struct."); return 0; } TypePointers StructType::memoryMemberTypes() const { solAssert(!containsNestedMapping(), ""); TypePointers types; for (ASTPointer<VariableDeclaration> const& variable: m_struct.members()) types.push_back(TypeProvider::withLocationIfReference(DataLocation::Memory, variable->annotation().type)); return types; } std::vector<std::tuple<std::string, Type const*>> StructType::makeStackItems() const { switch (m_location) { case DataLocation::CallData: return {std::make_tuple("offset", TypeProvider::uint256())}; case DataLocation::Memory: return {std::make_tuple("mpos", TypeProvider::uint256())}; case DataLocation::Storage: return {std::make_tuple("slot", TypeProvider::uint256())}; case DataLocation::Transient: solUnimplemented("Transient data location is only supported for value types."); break; } solAssert(false, ""); } std::vector<Type const*> StructType::decomposition() const { std::vector<Type const*> res; for (MemberList::Member const& member: members(nullptr)) res.push_back(member.type); return res; } Type const* EnumType::encodingType() const { solAssert(numberOfMembers() <= 256, ""); return TypeProvider::uint(8); } Declaration const* EnumType::typeDefinition() const { return &enumDefinition(); } TypeResult EnumType::unaryOperatorResult(Token _operator) const { return _operator == Token::Delete ? TypeProvider::emptyTuple() : nullptr; } std::string EnumType::richIdentifier() const { return "t_enum" + parenthesizeUserIdentifier(m_enum.name()) + std::to_string(m_enum.id()); } bool EnumType::operator==(Type const& _other) const { if (_other.category() != category()) return false; EnumType const& other = dynamic_cast<EnumType const&>(_other); return other.m_enum == m_enum; } unsigned EnumType::storageBytes() const { solAssert(numberOfMembers() <= 256, ""); return 1; } std::string EnumType::toString(bool) const { return std::string("enum ") + *m_enum.annotation().canonicalName; } std::string EnumType::canonicalName() const { return *m_enum.annotation().canonicalName; } size_t EnumType::numberOfMembers() const { return m_enum.members().size(); } BoolResult EnumType::isExplicitlyConvertibleTo(Type const& _convertTo) const { if (_convertTo == *this) return true; else if (auto integerType = dynamic_cast<IntegerType const*>(&_convertTo)) return !integerType->isSigned(); return false; } unsigned EnumType::memberValue(ASTString const& _member) const { unsigned index = 0; for (ASTPointer<EnumValue> const& decl: m_enum.members()) { if (decl->name() == _member) return index; ++index; } solAssert(false, "Requested unknown enum value " + _member); } Type const& UserDefinedValueType::underlyingType() const { Type const* type = m_definition.underlyingType()->annotation().type; solAssert(type, ""); solAssert(type->category() != Category::UserDefinedValueType, ""); return *type; } Declaration const* UserDefinedValueType::typeDefinition() const { return &m_definition; } std::string UserDefinedValueType::richIdentifier() const { return "t_userDefinedValueType" + parenthesizeIdentifier(m_definition.name()) + std::to_string(m_definition.id()); } bool UserDefinedValueType::operator==(Type const& _other) const { if (_other.category() != category()) return false; UserDefinedValueType const& other = dynamic_cast<UserDefinedValueType const&>(_other); return other.definition() == definition(); } std::string UserDefinedValueType::toString(bool /* _withoutDataLocation */) const { return *definition().annotation().canonicalName; } std::string UserDefinedValueType::canonicalName() const { return *definition().annotation().canonicalName; } std::vector<std::tuple<std::string, Type const*>> UserDefinedValueType::makeStackItems() const { return underlyingType().stackItems(); } BoolResult TupleType::isImplicitlyConvertibleTo(Type const& _other) const { if (auto tupleType = dynamic_cast<TupleType const*>(&_other)) { TypePointers const& targets = tupleType->components(); if (targets.empty()) return components().empty(); if (components().size() != targets.size()) return false; for (size_t i = 0; i < targets.size(); ++i) if (!components()[i] && targets[i]) return false; else if (components()[i] && targets[i] && !components()[i]->isImplicitlyConvertibleTo(*targets[i])) return false; return true; } else return false; } std::string TupleType::richIdentifier() const { return "t_tuple" + identifierList(components()); } bool TupleType::operator==(Type const& _other) const { if (auto tupleType = dynamic_cast<TupleType const*>(&_other)) return components() == tupleType->components(); else return false; } std::string TupleType::toString(bool _withoutDataLocation) const { if (components().empty()) return "tuple()"; std::string str = "tuple("; for (auto const& t: components()) str += (t ? t->toString(_withoutDataLocation) : "") + ","; str.pop_back(); return str + ")"; } std::string TupleType::humanReadableName() const { if (components().empty()) return "tuple()"; std::string str = "tuple("; for (auto const& t: components()) str += (t ? t->humanReadableName() : "") + ","; str.pop_back(); return str + ")"; } u256 TupleType::storageSize() const { solAssert(false, "Storage size of non-storable tuple type requested."); } std::vector<std::tuple<std::string, Type const*>> TupleType::makeStackItems() const { std::vector<std::tuple<std::string, Type const*>> slots; unsigned i = 1; for (auto const& t: components()) { if (t) slots.emplace_back("component_" + std::to_string(i), t); ++i; } return slots; } Type const* TupleType::mobileType() const { TypePointers mobiles; for (auto const& c: components()) { if (c) { auto mt = c->mobileType(); if (!mt) return nullptr; mobiles.push_back(mt); } else mobiles.push_back(nullptr); } return TypeProvider::tuple(std::move(mobiles)); } FunctionType::FunctionType(FunctionDefinition const& _function, Kind _kind): m_kind(_kind), m_stateMutability(_function.stateMutability()), m_declaration(&_function) { solAssert( _kind == Kind::Internal || _kind == Kind::External || _kind == Kind::Declaration, "Only internal or external function types or function declaration types can be created from function definitions." ); if (_kind == Kind::Internal && m_stateMutability == StateMutability::Payable) m_stateMutability = StateMutability::NonPayable; for (ASTPointer<VariableDeclaration> const& var: _function.parameters()) { solAssert(var->annotation().type, "Parameter type is not yet available in the AST."); m_parameterNames.push_back(var->name()); m_parameterTypes.push_back(var->annotation().type); } for (ASTPointer<VariableDeclaration> const& var: _function.returnParameters()) { solAssert(var->annotation().type, "Return parameter type is not yet available in the AST."); m_returnParameterNames.push_back(var->name()); m_returnParameterTypes.push_back(var->annotation().type); } solAssert( m_parameterNames.size() == m_parameterTypes.size(), "Parameter names list must match parameter types list!" ); solAssert( m_returnParameterNames.size() == m_returnParameterTypes.size(), "Return parameter names list must match return parameter types list!" ); } FunctionType::FunctionType(VariableDeclaration const& _varDecl): m_kind(Kind::External), m_stateMutability(StateMutability::View), m_declaration(&_varDecl) { auto returnType = _varDecl.annotation().type; ASTString returnName; while (true) { if (auto mappingType = dynamic_cast<MappingType const*>(returnType)) { m_parameterTypes.push_back(mappingType->keyType()); m_parameterNames.push_back(mappingType->keyName()); returnType = mappingType->valueType(); returnName = mappingType->valueName(); } else if (auto arrayType = dynamic_cast<ArrayType const*>(returnType)) { if (arrayType->isByteArrayOrString()) // Return byte arrays as whole. break; returnType = arrayType->baseType(); m_parameterNames.emplace_back(""); m_parameterTypes.push_back(TypeProvider::uint256()); } else break; } if (auto structType = dynamic_cast<StructType const*>(returnType)) { for (auto const& member: structType->members(nullptr)) { solAssert(member.type, ""); if (member.type->category() != Category::Mapping) { if (auto arrayType = dynamic_cast<ArrayType const*>(member.type)) if (!arrayType->isByteArrayOrString()) continue; m_returnParameterTypes.push_back(TypeProvider::withLocationIfReference( DataLocation::Memory, member.type )); m_returnParameterNames.push_back(member.name); } } } else { m_returnParameterTypes.push_back(TypeProvider::withLocationIfReference( DataLocation::Memory, returnType )); m_returnParameterNames.emplace_back(returnName); } solAssert( m_parameterNames.size() == m_parameterTypes.size(), "Parameter names list must match parameter types list!" ); solAssert( m_returnParameterNames.size() == m_returnParameterTypes.size(), "Return parameter names list must match return parameter types list!" ); } FunctionType::FunctionType(EventDefinition const& _event): m_kind(Kind::Event), m_stateMutability(StateMutability::NonPayable), m_declaration(&_event) { for (ASTPointer<VariableDeclaration> const& var: _event.parameters()) { m_parameterNames.push_back(var->name()); m_parameterTypes.push_back(var->annotation().type); } solAssert( m_parameterNames.size() == m_parameterTypes.size(), "Parameter names list must match parameter types list!" ); solAssert( m_returnParameterNames.size() == 0 && m_returnParameterTypes.size() == 0, "" ); } FunctionType::FunctionType(ErrorDefinition const& _error): m_kind(Kind::Error), m_stateMutability(StateMutability::Pure), m_declaration(&_error) { for (ASTPointer<VariableDeclaration> const& var: _error.parameters()) { m_parameterNames.push_back(var->name()); m_parameterTypes.push_back(var->annotation().type); } m_returnParameterNames.push_back(""); m_returnParameterTypes.push_back(TypeProvider::magic(MagicType::Kind::Error)); solAssert( m_parameterNames.size() == m_parameterTypes.size(), "Parameter names list must match parameter types list!" ); solAssert( m_returnParameterNames.size() == m_returnParameterTypes.size(), "" ); } FunctionType::FunctionType(FunctionTypeName const& _typeName): m_parameterNames(_typeName.parameterTypes().size(), ""), m_returnParameterNames(_typeName.returnParameterTypes().size(), ""), m_kind(_typeName.visibility() == Visibility::External ? Kind::External : Kind::Internal), m_stateMutability(_typeName.stateMutability()) { if (_typeName.isPayable()) solAssert(m_kind == Kind::External, "Internal payable function type used."); for (auto const& t: _typeName.parameterTypes()) { solAssert(t->annotation().type, "Type not set for parameter."); m_parameterTypes.push_back(t->annotation().type); } for (auto const& t: _typeName.returnParameterTypes()) { solAssert(t->annotation().type, "Type not set for return parameter."); m_returnParameterTypes.push_back(t->annotation().type); } solAssert( m_parameterNames.size() == m_parameterTypes.size(), "Parameter names list must match parameter types list!" ); solAssert( m_returnParameterNames.size() == m_returnParameterTypes.size(), "Return parameter names list must match return parameter types list!" ); } FunctionTypePointer FunctionType::newExpressionType(ContractDefinition const& _contract) { FunctionDefinition const* constructor = _contract.constructor(); TypePointers parameters; strings parameterNames; StateMutability stateMutability = StateMutability::NonPayable; solAssert(!_contract.isInterface(), ""); if (constructor) { for (ASTPointer<VariableDeclaration> const& var: constructor->parameters()) { parameterNames.push_back(var->name()); parameters.push_back(var->annotation().type); } if (constructor->isPayable()) stateMutability = StateMutability::Payable; } return TypeProvider::function( parameters, TypePointers{TypeProvider::contract(_contract)}, parameterNames, strings{""}, Kind::Creation, stateMutability ); } std::vector<std::string> FunctionType::parameterNames() const { if (!hasBoundFirstArgument()) return m_parameterNames; return std::vector<std::string>(m_parameterNames.cbegin() + 1, m_parameterNames.cend()); } TypePointers FunctionType::returnParameterTypesWithoutDynamicTypes() const { TypePointers returnParameterTypes = m_returnParameterTypes; if ( m_kind == Kind::External || m_kind == Kind::DelegateCall || m_kind == Kind::BareCall || m_kind == Kind::BareCallCode || m_kind == Kind::BareDelegateCall || m_kind == Kind::BareStaticCall ) for (auto& param: returnParameterTypes) { solAssert(param->decodingType(), ""); if (param->decodingType()->isDynamicallyEncoded()) param = TypeProvider::inaccessibleDynamic(); } return returnParameterTypes; } TypePointers FunctionType::parameterTypes() const { if (!hasBoundFirstArgument()) return m_parameterTypes; return TypePointers(m_parameterTypes.cbegin() + 1, m_parameterTypes.cend()); } TypePointers const& FunctionType::parameterTypesIncludingSelf() const { return m_parameterTypes; } std::string FunctionType::richIdentifier() const { std::string id = "t_function_"; switch (m_kind) { case Kind::Declaration: id += "declaration"; break; case Kind::Internal: id += "internal"; break; case Kind::External: id += "external"; break; case Kind::DelegateCall: id += "delegatecall"; break; case Kind::BareCall: id += "barecall"; break; case Kind::BareCallCode: id += "barecallcode"; break; case Kind::BareDelegateCall: id += "baredelegatecall"; break; case Kind::BareStaticCall: id += "barestaticcall"; break; case Kind::Creation: id += "creation"; break; case Kind::Send: id += "send"; break; case Kind::Transfer: id += "transfer"; break; case Kind::KECCAK256: id += "keccak256"; break; case Kind::Selfdestruct: id += "selfdestruct"; break; case Kind::Revert: id += "revert"; break; case Kind::ECRecover: id += "ecrecover"; break; case Kind::SHA256: id += "sha256"; break; case Kind::RIPEMD160: id += "ripemd160"; break; case Kind::GasLeft: id += "gasleft"; break; case Kind::Event: id += "event"; break; case Kind::Error: id += "error"; break; case Kind::Wrap: id += "wrap"; break; case Kind::Unwrap: id += "unwrap"; break; case Kind::SetGas: id += "setgas"; break; case Kind::SetValue: id += "setvalue"; break; case Kind::BlockHash: id += "blockhash"; break; case Kind::AddMod: id += "addmod"; break; case Kind::MulMod: id += "mulmod"; break; case Kind::ArrayPush: id += "arraypush"; break; case Kind::ArrayPop: id += "arraypop"; break; case Kind::BytesConcat: id += "bytesconcat"; break; case Kind::StringConcat: id += "stringconcat"; break; case Kind::ObjectCreation: id += "objectcreation"; break; case Kind::Assert: id += "assert"; break; case Kind::Require: id += "require"; break; case Kind::ABIEncode: id += "abiencode"; break; case Kind::ABIEncodePacked: id += "abiencodepacked"; break; case Kind::ABIEncodeWithSelector: id += "abiencodewithselector"; break; case Kind::ABIEncodeCall: id += "abiencodecall"; break; case Kind::ABIEncodeWithSignature: id += "abiencodewithsignature"; break; case Kind::ABIDecode: id += "abidecode"; break; case Kind::BlobHash: id += "blobhash"; break; case Kind::MetaType: id += "metatype"; break; } id += "_" + stateMutabilityToString(m_stateMutability); id += identifierList(m_parameterTypes) + "returns" + identifierList(m_returnParameterTypes); if (gasSet()) id += "gas"; if (valueSet()) id += "value"; if (saltSet()) id += "salt"; if (hasBoundFirstArgument()) id += "attached_to" + identifierList(selfType()); return id; } bool FunctionType::operator==(Type const& _other) const { if (_other.category() != category()) return false; FunctionType const& other = dynamic_cast<FunctionType const&>(_other); if (!equalExcludingStateMutability(other)) return false; if (m_stateMutability != other.stateMutability()) return false; return true; } BoolResult FunctionType::isExplicitlyConvertibleTo(Type const& _convertTo) const { if (_convertTo.category() == category()) { auto const& convertToType = dynamic_cast<FunctionType const&>(_convertTo); return (m_kind == FunctionType::Kind::Declaration) == (convertToType.kind() == FunctionType::Kind::Declaration); } return false; } BoolResult FunctionType::isImplicitlyConvertibleTo(Type const& _convertTo) const { if (_convertTo.category() != category()) return false; FunctionType const& convertTo = dynamic_cast<FunctionType const&>(_convertTo); // These two checks are duplicated in equalExcludingStateMutability, but are added here for error reporting. if (convertTo.hasBoundFirstArgument() != hasBoundFirstArgument()) return BoolResult::err("Attached functions cannot be converted into unattached functions."); if (convertTo.kind() != kind()) return BoolResult::err("Special functions cannot be converted to function types."); if ( kind() == FunctionType::Kind::Declaration && m_declaration != convertTo.m_declaration ) return BoolResult::err("Function declaration types referring to different functions cannot be converted to each other."); if (!equalExcludingStateMutability(convertTo)) return false; // non-payable should not be convertible to payable if (m_stateMutability != StateMutability::Payable && convertTo.stateMutability() == StateMutability::Payable) return false; // payable should be convertible to non-payable, because you are free to pay 0 ether if (m_stateMutability == StateMutability::Payable && convertTo.stateMutability() == StateMutability::NonPayable) return true; // e.g. pure should be convertible to view, but not the other way around. if (m_stateMutability > convertTo.stateMutability()) return false; return true; } TypeResult FunctionType::unaryOperatorResult(Token _operator) const { if (_operator == Token::Delete) return TypeResult(TypeProvider::emptyTuple()); return nullptr; } TypeResult FunctionType::binaryOperatorResult(Token _operator, Type const* _other) const { if (_other->category() != category() || !(_operator == Token::Equal || _operator == Token::NotEqual)) return nullptr; FunctionType const& other = dynamic_cast<FunctionType const&>(*_other); if (kind() == Kind::Internal && sizeOnStack() == 1 && other.kind() == Kind::Internal && other.sizeOnStack() == 1) return commonType(this, _other); else if ( kind() == Kind::External && sizeOnStack() == 2 && !hasBoundFirstArgument() && other.kind() == Kind::External && other.sizeOnStack() == 2 && !other.hasBoundFirstArgument() ) return commonType(this, _other); return nullptr; } std::string FunctionType::canonicalName() const { solAssert(m_kind == Kind::External, ""); return "function"; } std::string FunctionType::humanReadableName() const { switch (m_kind) { case Kind::Error: return "error " + m_declaration->name() + toStringInParentheses(m_parameterTypes, /* _withoutDataLocation */ true); case Kind::Event: return "event " + m_declaration->name() + toStringInParentheses(m_parameterTypes, /* _withoutDataLocation */ true); default: return toString(/* _withoutDataLocation */ false); } } std::string FunctionType::toString(bool _withoutDataLocation) const { std::string name = "function "; if (m_kind == Kind::Declaration) { auto const* functionDefinition = dynamic_cast<FunctionDefinition const*>(m_declaration); solAssert(functionDefinition, ""); if (auto const* contract = dynamic_cast<ContractDefinition const*>(functionDefinition->scope())) name += *contract->annotation().canonicalName + "."; name += functionDefinition->name(); } name += toStringInParentheses(m_parameterTypes, _withoutDataLocation); if (m_stateMutability != StateMutability::NonPayable) name += " " + stateMutabilityToString(m_stateMutability); if (m_kind == Kind::External) name += " external"; if (!m_returnParameterTypes.empty()) { name += " returns "; name += toStringInParentheses(m_returnParameterTypes, _withoutDataLocation); } return name; } unsigned FunctionType::calldataEncodedSize(bool _padded) const { unsigned size = storageBytes(); if (_padded) size = ((size + 31) / 32) * 32; return size; } u256 FunctionType::storageSize() const { if (m_kind == Kind::External || m_kind == Kind::Internal) return 1; else solAssert(false, "Storage size of non-storable function type requested."); } bool FunctionType::leftAligned() const { return m_kind == Kind::External; } unsigned FunctionType::storageBytes() const { if (m_kind == Kind::External) return 20 + 4; else if (m_kind == Kind::Internal) return 8; // it should really not be possible to create larger programs else solAssert(false, "Storage size of non-storable function type requested."); } bool FunctionType::nameable() const { return (m_kind == Kind::Internal || m_kind == Kind::External) && !hasBoundFirstArgument() && !takesArbitraryParameters() && !gasSet() && !valueSet() && !saltSet(); } std::vector<std::tuple<std::string, Type const*>> FunctionType::makeStackItems() const { std::vector<std::tuple<std::string, Type const*>> slots; Kind kind = m_kind; if (m_kind == Kind::SetGas || m_kind == Kind::SetValue) { solAssert(m_returnParameterTypes.size() == 1, ""); kind = dynamic_cast<FunctionType const&>(*m_returnParameterTypes.front()).m_kind; } switch (kind) { case Kind::External: case Kind::DelegateCall: slots = { std::make_tuple("address", TypeProvider::address()), std::make_tuple("functionSelector", TypeProvider::uint(32)) }; break; case Kind::BareCall: case Kind::BareCallCode: case Kind::BareDelegateCall: case Kind::BareStaticCall: case Kind::Transfer: case Kind::Send: slots = {std::make_tuple("address", TypeProvider::address())}; break; case Kind::Internal: slots = {std::make_tuple("functionIdentifier", TypeProvider::uint256())}; break; case Kind::ArrayPush: case Kind::ArrayPop: solAssert(hasBoundFirstArgument(), ""); slots = {}; break; default: break; } if (gasSet()) slots.emplace_back("gas", TypeProvider::uint256()); if (valueSet()) slots.emplace_back("value", TypeProvider::uint256()); if (saltSet()) slots.emplace_back("salt", TypeProvider::fixedBytes(32)); if (hasBoundFirstArgument()) slots.emplace_back("self", m_parameterTypes.front()); return slots; } FunctionTypePointer FunctionType::interfaceFunctionType() const { // Note that m_declaration might also be a state variable! solAssert(m_declaration, "Declaration needed to determine interface function type."); bool isLibraryFunction = false; if (kind() != Kind::Event && kind() != Kind::Error) if (auto const* contract = dynamic_cast<ContractDefinition const*>(m_declaration->scope())) isLibraryFunction = contract->isLibrary(); util::Result<TypePointers> paramTypes = transformParametersToExternal(m_parameterTypes, isLibraryFunction); if (!paramTypes.message().empty()) return FunctionTypePointer(); util::Result<TypePointers> retParamTypes = transformParametersToExternal(m_returnParameterTypes, isLibraryFunction); if (!retParamTypes.message().empty()) return FunctionTypePointer(); auto variable = dynamic_cast<VariableDeclaration const*>(m_declaration); if (variable && retParamTypes.get().empty()) return FunctionTypePointer(); solAssert(!takesArbitraryParameters()); return TypeProvider::function( paramTypes, retParamTypes, m_parameterNames, m_returnParameterNames, m_kind, m_stateMutability, m_declaration ); } MemberList::MemberMap FunctionType::nativeMembers(ASTNode const* _scope) const { switch (m_kind) { case Kind::Declaration: if (declaration().isPartOfExternalInterface()) return {{"selector", TypeProvider::fixedBytes(4)}}; else return MemberList::MemberMap(); case Kind::Internal: if ( auto const* functionDefinition = dynamic_cast<FunctionDefinition const*>(m_declaration); functionDefinition && _scope && functionDefinition->annotation().contract && _scope != functionDefinition->annotation().contract && functionDefinition->isPartOfExternalInterface() ) { auto const* contractScope = dynamic_cast<ContractDefinition const*>(_scope); solAssert(contractScope && contractScope->derivesFrom(*functionDefinition->annotation().contract), ""); return {{"selector", TypeProvider::fixedBytes(4)}}; } else return MemberList::MemberMap(); case Kind::External: case Kind::Creation: case Kind::BareCall: case Kind::BareCallCode: case Kind::BareDelegateCall: case Kind::BareStaticCall: { MemberList::MemberMap members; if (m_kind == Kind::External) { members.emplace_back("selector", TypeProvider::fixedBytes(4)); members.emplace_back("address", TypeProvider::address()); } if (m_kind != Kind::BareDelegateCall) { if (isPayable()) members.emplace_back( "value", TypeProvider::function( parseElementaryTypeVector({"uint"}), TypePointers{copyAndSetCallOptions(false, true, false)}, strings(1, ""), strings(1, ""), Kind::SetValue, StateMutability::Pure, nullptr, Options::fromFunctionType(*this) ) ); } if (m_kind != Kind::Creation) members.emplace_back( "gas", TypeProvider::function( parseElementaryTypeVector({"uint"}), TypePointers{copyAndSetCallOptions(true, false, false)}, strings(1, ""), strings(1, ""), Kind::SetGas, StateMutability::Pure, nullptr, Options::fromFunctionType(*this) ) ); return members; } case Kind::DelegateCall: { if (auto const* functionDefinition = dynamic_cast<FunctionDefinition const*>(m_declaration)) { solAssert(functionDefinition->visibility() > Visibility::Internal, ""); auto const *contract = dynamic_cast<ContractDefinition const*>(m_declaration->scope()); solAssert(contract, ""); solAssert(contract->isLibrary(), ""); return {{"selector", TypeProvider::fixedBytes(4)}}; } return {}; } case Kind::Error: return {{"selector", TypeProvider::fixedBytes(4)}}; case Kind::Event: { if (!(dynamic_cast<EventDefinition const&>(declaration()).isAnonymous())) return {{"selector", TypeProvider::fixedBytes(32)}}; return MemberList::MemberMap(); } default: return MemberList::MemberMap(); } } Type const* FunctionType::encodingType() const { if (gasSet() || valueSet()) return nullptr; // Only external functions can be encoded, internal functions cannot leave code boundaries. if (m_kind == Kind::External) return this; else return nullptr; } TypeResult FunctionType::interfaceType(bool /*_inLibrary*/) const { if (m_kind == Kind::External) return this; else return TypeResult::err("Internal type is not allowed for public or external functions."); } Type const* FunctionType::mobileType() const { if (valueSet() || gasSet() || saltSet() || hasBoundFirstArgument()) return nullptr; // Special function types do not get a mobile type, such that they cannot be used in complex expressions. if (m_kind != FunctionType::Kind::Internal && m_kind != FunctionType::Kind::External && m_kind != FunctionType::Kind::DelegateCall) return nullptr; // return function without parameter names and without declaration return TypeProvider::function( m_parameterTypes, m_returnParameterTypes, strings(m_parameterTypes.size()), strings(m_returnParameterNames.size()), m_kind, m_stateMutability, nullptr, Options::fromFunctionType(*this) ); } bool FunctionType::canTakeArguments( FuncCallArguments const& _arguments, Type const* _selfType ) const { solAssert(!hasBoundFirstArgument() || _selfType, ""); if (hasBoundFirstArgument() && !_selfType->isImplicitlyConvertibleTo(*selfType())) return false; TypePointers paramTypes = parameterTypes(); std::vector<std::string> const paramNames = parameterNames(); if (takesArbitraryParameters()) return true; else if (_arguments.numArguments() != paramTypes.size()) return false; else if (!_arguments.hasNamedArguments()) return equal( _arguments.types.cbegin(), _arguments.types.cend(), paramTypes.cbegin(), [](Type const* argumentType, Type const* parameterType) { return argumentType->isImplicitlyConvertibleTo(*parameterType); } ); else if (paramNames.size() != _arguments.numNames()) return false; else { solAssert(_arguments.numArguments() == _arguments.numNames(), "Expected equal sized type & name vectors"); size_t matchedNames = 0; for (size_t a = 0; a < _arguments.names.size(); a++) for (size_t p = 0; p < paramNames.size(); p++) if (*_arguments.names[a] == paramNames[p]) { matchedNames++; if (!_arguments.types[a]->isImplicitlyConvertibleTo(*paramTypes[p])) return false; } if (matchedNames == _arguments.numNames()) return true; return false; } } bool FunctionType::hasEqualParameterTypes(FunctionType const& _other) const { if (m_parameterTypes.size() != _other.m_parameterTypes.size()) return false; return equal( m_parameterTypes.cbegin(), m_parameterTypes.cend(), _other.m_parameterTypes.cbegin(), [](Type const* _a, Type const* _b) -> bool { return *_a == *_b; } ); } bool FunctionType::hasEqualReturnTypes(FunctionType const& _other) const { if (m_returnParameterTypes.size() != _other.m_returnParameterTypes.size()) return false; return equal( m_returnParameterTypes.cbegin(), m_returnParameterTypes.cend(), _other.m_returnParameterTypes.cbegin(), [](Type const* _a, Type const* _b) -> bool { return *_a == *_b; } ); } bool FunctionType::equalExcludingStateMutability(FunctionType const& _other) const { if (m_kind != _other.m_kind) return false; if (!hasEqualParameterTypes(_other) || !hasEqualReturnTypes(_other)) return false; //@todo this is ugly, but cannot be prevented right now if (gasSet() != _other.gasSet() || valueSet() != _other.valueSet() || saltSet() != _other.saltSet()) return false; if (hasBoundFirstArgument() != _other.hasBoundFirstArgument()) return false; solAssert(!hasBoundFirstArgument() || *selfType() == *_other.selfType(), ""); return true; } bool FunctionType::isBareCall() const { switch (m_kind) { case Kind::BareCall: case Kind::BareCallCode: case Kind::BareDelegateCall: case Kind::BareStaticCall: case Kind::ECRecover: case Kind::SHA256: case Kind::RIPEMD160: return true; default: return false; } } std::string FunctionType::externalSignature() const { solAssert(m_declaration != nullptr, "External signature of function needs declaration"); solAssert(!m_declaration->name().empty(), "Fallback function has no signature."); switch (kind()) { case Kind::Internal: case Kind::External: case Kind::DelegateCall: case Kind::Event: case Kind::Error: case Kind::Declaration: break; default: solAssert(false, "Invalid function type for requesting external signature."); } // "inLibrary" is only relevant if this is neither an event nor an error. bool inLibrary = false; if (kind() != Kind::Event && kind() != Kind::Error) if (auto const* contract = dynamic_cast<ContractDefinition const*>(m_declaration->scope())) inLibrary = contract->isLibrary(); auto extParams = transformParametersToExternal(m_parameterTypes, inLibrary); solAssert(extParams.message().empty(), extParams.message()); auto typeStrings = extParams.get() | ranges::views::transform([&](Type const* _t) -> std::string { std::string typeName = _t->signatureInExternalFunction(inLibrary); if (inLibrary && _t->dataStoredIn(DataLocation::Storage)) typeName += " storage"; return typeName; }); return m_declaration->name() + "(" + boost::algorithm::join(typeStrings, ",") + ")"; } u256 FunctionType::externalIdentifier() const { return util::selectorFromSignatureU32(externalSignature()); } std::string FunctionType::externalIdentifierHex() const { return util::selectorFromSignatureH32(externalSignature()).hex(); } bool FunctionType::isPure() const { // TODO: replace this with m_stateMutability == StateMutability::Pure once // the callgraph analyzer is in place return m_kind == Kind::KECCAK256 || m_kind == Kind::ECRecover || m_kind == Kind::SHA256 || m_kind == Kind::RIPEMD160 || m_kind == Kind::AddMod || m_kind == Kind::MulMod || m_kind == Kind::ObjectCreation || m_kind == Kind::ABIEncode || m_kind == Kind::ABIEncodePacked || m_kind == Kind::ABIEncodeWithSelector || m_kind == Kind::ABIEncodeCall || m_kind == Kind::ABIEncodeWithSignature || m_kind == Kind::ABIDecode || m_kind == Kind::MetaType || m_kind == Kind::Wrap || m_kind == Kind::Unwrap; } TypePointers FunctionType::parseElementaryTypeVector(strings const& _types) { TypePointers pointers; pointers.reserve(_types.size()); for (std::string const& type: _types) pointers.push_back(TypeProvider::fromElementaryTypeName(type)); return pointers; } Type const* FunctionType::copyAndSetCallOptions(bool _setGas, bool _setValue, bool _setSalt) const { solAssert(m_kind != Kind::Declaration, ""); Options options = Options::fromFunctionType(*this); if (_setGas) options.gasSet = true; if (_setValue) options.valueSet = true; if (_setSalt) options.saltSet = true; return TypeProvider::function( m_parameterTypes, m_returnParameterTypes, m_parameterNames, m_returnParameterNames, m_kind, m_stateMutability, m_declaration, options ); } FunctionTypePointer FunctionType::withBoundFirstArgument() const { solAssert(!m_parameterTypes.empty(), ""); solAssert(!gasSet(), ""); solAssert(!valueSet(), ""); solAssert(!saltSet(), ""); Options options = Options::fromFunctionType(*this); options.hasBoundFirstArgument = true; return TypeProvider::function( m_parameterTypes, m_returnParameterTypes, m_parameterNames, m_returnParameterNames, m_kind, m_stateMutability, m_declaration, options ); } FunctionTypePointer FunctionType::asExternallyCallableFunction(bool _inLibrary) const { TypePointers parameterTypes; for (auto const& t: m_parameterTypes) if (TypeProvider::isReferenceWithLocation(t, DataLocation::CallData)) parameterTypes.push_back( TypeProvider::withLocationIfReference(DataLocation::Memory, t, true) ); else parameterTypes.push_back(t); TypePointers returnParameterTypes; for (auto const& returnParamType: m_returnParameterTypes) if (TypeProvider::isReferenceWithLocation(returnParamType, DataLocation::CallData)) returnParameterTypes.push_back( TypeProvider::withLocationIfReference(DataLocation::Memory, returnParamType, true) ); else returnParameterTypes.push_back(returnParamType); Kind kind = m_kind; if (_inLibrary) { solAssert(!!m_declaration, "Declaration has to be available."); solAssert(m_declaration->isPublic(), ""); kind = Kind::DelegateCall; } return TypeProvider::function( parameterTypes, returnParameterTypes, m_parameterNames, m_returnParameterNames, kind, m_stateMutability, m_declaration, Options::fromFunctionType(*this) ); } Type const* FunctionType::selfType() const { solAssert(hasBoundFirstArgument(), "Function is not attached to a type."); solAssert(m_parameterTypes.size() > 0, "Function has no self type."); return m_parameterTypes.at(0); } ASTPointer<StructuredDocumentation> FunctionType::documentation() const { auto function = dynamic_cast<StructurallyDocumented const*>(m_declaration); if (function) return function->documentation(); return ASTPointer<StructuredDocumentation>(); } bool FunctionType::padArguments() const { // No padding only for hash functions, low-level calls and the packed encoding function. switch (m_kind) { case Kind::BareCall: case Kind::BareCallCode: case Kind::BareDelegateCall: case Kind::BareStaticCall: case Kind::SHA256: case Kind::RIPEMD160: case Kind::KECCAK256: case Kind::ABIEncodePacked: return false; default: return true; } return true; } Type const* MappingType::encodingType() const { return TypeProvider::integer(256, IntegerType::Modifier::Unsigned); } std::string MappingType::richIdentifier() const { return "t_mapping" + identifierList(m_keyType, m_valueType); } bool MappingType::operator==(Type const& _other) const { if (_other.category() != category()) return false; MappingType const& other = dynamic_cast<MappingType const&>(_other); return *other.m_keyType == *m_keyType && *other.m_valueType == *m_valueType; } std::string MappingType::toString(bool _withoutDataLocation) const { return "mapping(" + keyType()->toString(_withoutDataLocation) + " => " + valueType()->toString(_withoutDataLocation) + ")"; } std::string MappingType::canonicalName() const { return "mapping(" + keyType()->canonicalName() + " => " + valueType()->canonicalName() + ")"; } TypeResult MappingType::interfaceType(bool _inLibrary) const { solAssert(keyType()->interfaceType(_inLibrary).get(), "Must be an elementary type!"); if (_inLibrary) { auto iType = valueType()->interfaceType(_inLibrary); if (!iType.get()) { solAssert(!iType.message().empty(), "Expected detailed error message!"); return iType; } } else return TypeResult::err( "Types containing (nested) mappings can only be parameters or " "return variables of internal or library functions." ); return this; } std::vector<std::tuple<std::string, Type const*>> MappingType::makeStackItems() const { return {std::make_tuple("slot", TypeProvider::uint256())}; } std::string TypeType::richIdentifier() const { return "t_type" + identifierList(actualType()); } bool TypeType::operator==(Type const& _other) const { if (_other.category() != category()) return false; TypeType const& other = dynamic_cast<TypeType const&>(_other); return *actualType() == *other.actualType(); } u256 TypeType::storageSize() const { solAssert(false, "Storage size of non-storable type type requested."); } std::vector<std::tuple<std::string, Type const*>> TypeType::makeStackItems() const { if (auto contractType = dynamic_cast<ContractType const*>(m_actualType)) if (contractType->contractDefinition().isLibrary()) { solAssert(!contractType->isSuper(), ""); return {std::make_tuple("address", TypeProvider::address())}; } return {}; } MemberList::MemberMap TypeType::nativeMembers(ASTNode const* _currentScope) const { MemberList::MemberMap members; if (m_actualType->category() == Category::Contract) { auto contractType = dynamic_cast<ContractType const*>(m_actualType); ContractDefinition const& contract = contractType->contractDefinition(); if (contractType->isSuper()) { // add the most derived of all functions which are visible in derived contracts auto bases = contract.annotation().linearizedBaseContracts; solAssert(bases.size() >= 1, "linearizedBaseContracts should at least contain the most derived contract."); // `sliced(1, ...)` ignores the most derived contract, which should not be searchable from `super`. for (ContractDefinition const* base: bases | ranges::views::tail) for (FunctionDefinition const* function: base->definedFunctions()) { if (!function->isVisibleInDerivedContracts() || !function->isImplemented()) continue; auto functionType = TypeProvider::function(*function, FunctionType::Kind::Internal); bool functionWithEqualArgumentsFound = false; for (auto const& member: members) { if (member.name != function->name()) continue; auto memberType = dynamic_cast<FunctionType const*>(member.type); solAssert(!!memberType, "Override changes type."); if (!memberType->hasEqualParameterTypes(*functionType)) continue; functionWithEqualArgumentsFound = true; break; } if (!functionWithEqualArgumentsFound) members.emplace_back(function, functionType); } } else { auto const* contractScope = dynamic_cast<ContractDefinition const*>(_currentScope); bool inDerivingScope = contractScope && contractScope->derivesFrom(contract); for (auto const* declaration: contract.declarations()) { if (dynamic_cast<ModifierDefinition const*>(declaration)) continue; if (declaration->name().empty()) continue; if (!contract.isLibrary() && inDerivingScope && declaration->isVisibleInDerivedContracts()) { if ( auto const* functionDefinition = dynamic_cast<FunctionDefinition const*>(declaration); functionDefinition && !functionDefinition->isImplemented() ) members.emplace_back(declaration, declaration->typeViaContractName()); else members.emplace_back(declaration, declaration->type()); } else if ( (contract.isLibrary() && declaration->isVisibleAsLibraryMember()) || declaration->isVisibleViaContractTypeAccess() ) members.emplace_back(declaration, declaration->typeViaContractName()); } } } else if (m_actualType->category() == Category::Enum) { EnumDefinition const& enumDef = dynamic_cast<EnumType const&>(*m_actualType).enumDefinition(); auto enumType = TypeProvider::enumType(enumDef); for (ASTPointer<EnumValue> const& enumValue: enumDef.members()) members.emplace_back(enumValue.get(), enumType); } else if (m_actualType->category() == Category::UserDefinedValueType) { auto& userDefined = dynamic_cast<UserDefinedValueType const&>(*m_actualType); members.emplace_back( "wrap", TypeProvider::function( TypePointers{&userDefined.underlyingType()}, TypePointers{&userDefined}, strings{std::string{}}, strings{std::string{}}, FunctionType::Kind::Wrap, StateMutability::Pure ) ); members.emplace_back( "unwrap", TypeProvider::function( TypePointers{&userDefined}, TypePointers{&userDefined.underlyingType()}, strings{std::string{}}, strings{std::string{}}, FunctionType::Kind::Unwrap, StateMutability::Pure ) ); } else if ( auto const* arrayType = dynamic_cast<ArrayType const*>(m_actualType); arrayType && arrayType->isByteArrayOrString() ) members.emplace_back("concat", TypeProvider::function( TypePointers{}, TypePointers{arrayType->isString() ? TypeProvider::stringMemory() : TypeProvider::bytesMemory()}, strings{}, strings{std::string{}}, arrayType->isString() ? FunctionType::Kind::StringConcat : FunctionType::Kind::BytesConcat, StateMutability::Pure, nullptr, FunctionType::Options::withArbitraryParameters() )); return members; } BoolResult TypeType::isExplicitlyConvertibleTo(Type const& _convertTo) const { if (auto const* address = dynamic_cast<AddressType const*>(&_convertTo)) if (address->stateMutability() == StateMutability::NonPayable) if (auto const* contractType = dynamic_cast<ContractType const*>(m_actualType)) return contractType->contractDefinition().isLibrary(); return isImplicitlyConvertibleTo(_convertTo); } ModifierType::ModifierType(ModifierDefinition const& _modifier) { TypePointers params; params.reserve(_modifier.parameters().size()); for (ASTPointer<VariableDeclaration> const& var: _modifier.parameters()) params.push_back(var->annotation().type); swap(params, m_parameterTypes); } u256 ModifierType::storageSize() const { solAssert(false, "Storage size of non-storable type type requested."); } std::string ModifierType::richIdentifier() const { return "t_modifier" + identifierList(m_parameterTypes); } bool ModifierType::operator==(Type const& _other) const { if (_other.category() != category()) return false; ModifierType const& other = dynamic_cast<ModifierType const&>(_other); if (m_parameterTypes.size() != other.m_parameterTypes.size()) return false; auto typeCompare = [](Type const* _a, Type const* _b) -> bool { return *_a == *_b; }; if (!equal( m_parameterTypes.cbegin(), m_parameterTypes.cend(), other.m_parameterTypes.cbegin(), typeCompare )) return false; return true; } std::string ModifierType::toString(bool _withoutDataLocation) const { std::string name = "modifier ("; for (auto it = m_parameterTypes.begin(); it != m_parameterTypes.end(); ++it) name += (*it)->toString(_withoutDataLocation) + (it + 1 == m_parameterTypes.end() ? "" : ","); return name + ")"; } std::string ModuleType::richIdentifier() const { return "t_module_" + std::to_string(m_sourceUnit.id()); } bool ModuleType::operator==(Type const& _other) const { if (_other.category() != category()) return false; return &m_sourceUnit == &dynamic_cast<ModuleType const&>(_other).m_sourceUnit; } MemberList::MemberMap ModuleType::nativeMembers(ASTNode const*) const { MemberList::MemberMap symbols; for (auto const& [name, declarations]: *m_sourceUnit.annotation().exportedSymbols) for (Declaration const* symbol: declarations) symbols.emplace_back(symbol, symbol->type(), name); return symbols; } std::string ModuleType::toString(bool) const { return std::string("module \"") + *m_sourceUnit.annotation().path + std::string("\""); } std::string MagicType::richIdentifier() const { switch (m_kind) { case Kind::Block: return "t_magic_block"; case Kind::Message: return "t_magic_message"; case Kind::Transaction: return "t_magic_transaction"; case Kind::ABI: return "t_magic_abi"; case Kind::MetaType: solAssert(m_typeArgument, ""); return "t_magic_meta_type_" + m_typeArgument->richIdentifier(); case Kind::Error: return "t_error"; } return ""; } bool MagicType::operator==(Type const& _other) const { if (_other.category() != category()) return false; MagicType const& other = dynamic_cast<MagicType const&>(_other); return other.m_kind == m_kind; } MemberList::MemberMap MagicType::nativeMembers(ASTNode const*) const { switch (m_kind) { case Kind::Block: return MemberList::MemberMap({ {"coinbase", TypeProvider::payableAddress()}, {"timestamp", TypeProvider::uint256()}, {"blockhash", TypeProvider::function(strings{"uint"}, strings{"bytes32"}, FunctionType::Kind::BlockHash, StateMutability::View)}, {"difficulty", TypeProvider::uint256()}, {"prevrandao", TypeProvider::uint256()}, {"number", TypeProvider::uint256()}, {"gaslimit", TypeProvider::uint256()}, {"chainid", TypeProvider::uint256()}, {"basefee", TypeProvider::uint256()}, {"blobbasefee", TypeProvider::uint256()} }); case Kind::Message: return MemberList::MemberMap({ {"sender", TypeProvider::address()}, {"gas", TypeProvider::uint256()}, {"value", TypeProvider::uint256()}, {"data", TypeProvider::array(DataLocation::CallData)}, {"sig", TypeProvider::fixedBytes(4)} }); case Kind::Transaction: return MemberList::MemberMap({ {"origin", TypeProvider::address()}, {"gasprice", TypeProvider::uint256()} }); case Kind::ABI: return MemberList::MemberMap({ {"encode", TypeProvider::function( TypePointers{}, TypePointers{TypeProvider::array(DataLocation::Memory)}, strings{}, strings{1, ""}, FunctionType::Kind::ABIEncode, StateMutability::Pure, nullptr, FunctionType::Options::withArbitraryParameters() )}, {"encodePacked", TypeProvider::function( TypePointers{}, TypePointers{TypeProvider::array(DataLocation::Memory)}, strings{}, strings{1, ""}, FunctionType::Kind::ABIEncodePacked, StateMutability::Pure, nullptr, FunctionType::Options::withArbitraryParameters() )}, {"encodeWithSelector", TypeProvider::function( TypePointers{TypeProvider::fixedBytes(4)}, TypePointers{TypeProvider::array(DataLocation::Memory)}, strings{1, ""}, strings{1, ""}, FunctionType::Kind::ABIEncodeWithSelector, StateMutability::Pure, nullptr, FunctionType::Options::withArbitraryParameters() )}, {"encodeCall", TypeProvider::function( TypePointers{}, TypePointers{TypeProvider::array(DataLocation::Memory)}, strings{}, strings{1, ""}, FunctionType::Kind::ABIEncodeCall, StateMutability::Pure, nullptr, FunctionType::Options::withArbitraryParameters() )}, {"encodeWithSignature", TypeProvider::function( TypePointers{TypeProvider::array(DataLocation::Memory, true)}, TypePointers{TypeProvider::array(DataLocation::Memory)}, strings{1, ""}, strings{1, ""}, FunctionType::Kind::ABIEncodeWithSignature, StateMutability::Pure, nullptr, FunctionType::Options::withArbitraryParameters() )}, {"decode", TypeProvider::function( TypePointers(), TypePointers(), strings{}, strings{}, FunctionType::Kind::ABIDecode, StateMutability::Pure, nullptr, FunctionType::Options::withArbitraryParameters() )} }); case Kind::Error: return {}; case Kind::MetaType: { solAssert( m_typeArgument && ( m_typeArgument->category() == Type::Category::Contract || m_typeArgument->category() == Type::Category::Integer || m_typeArgument->category() == Type::Category::Enum ), "Only enums, contracts or integer types supported for now" ); if (m_typeArgument->category() == Type::Category::Contract) { ContractDefinition const& contract = dynamic_cast<ContractType const&>(*m_typeArgument).contractDefinition(); if (contract.canBeDeployed()) return MemberList::MemberMap({ {"creationCode", TypeProvider::array(DataLocation::Memory)}, {"runtimeCode", TypeProvider::array(DataLocation::Memory)}, {"name", TypeProvider::stringMemory()}, }); else return MemberList::MemberMap({ {"interfaceId", TypeProvider::fixedBytes(4)}, {"name", TypeProvider::stringMemory()}, }); } else if (m_typeArgument->category() == Type::Category::Integer) { IntegerType const* integerTypePointer = dynamic_cast<IntegerType const*>(m_typeArgument); return MemberList::MemberMap({ {"min", integerTypePointer}, {"max", integerTypePointer}, }); } else if (m_typeArgument->category() == Type::Category::Enum) { EnumType const* enumTypePointer = dynamic_cast<EnumType const*>(m_typeArgument); return MemberList::MemberMap({ {"min", enumTypePointer}, {"max", enumTypePointer}, }); } } } solAssert(false, "Unknown kind of magic."); return {}; } std::string MagicType::toString(bool _withoutDataLocation) const { switch (m_kind) { case Kind::Block: return "block"; case Kind::Message: return "msg"; case Kind::Transaction: return "tx"; case Kind::ABI: return "abi"; case Kind::MetaType: solAssert(m_typeArgument, ""); return "type(" + m_typeArgument->toString(_withoutDataLocation) + ")"; case Kind::Error: return "error"; } solAssert(false, "Unknown kind of magic."); return {}; } Type const* MagicType::typeArgument() const { solAssert(m_kind == Kind::MetaType, ""); solAssert(m_typeArgument, ""); return m_typeArgument; } Type const* InaccessibleDynamicType::decodingType() const { return TypeProvider::integer(256, IntegerType::Modifier::Unsigned); }
126,615
C++
.cpp
3,840
30.331771
168
0.731856
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
3,249
StringUtils.cpp
ethereum_solidity/libsolutil/StringUtils.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 /** @file StringUtils.h * @author Balajiganapathi S <balajiganapathi.s@gmail.com> * @date 2017 * * String routines */ #include <libsolutil/StringUtils.h> #include <boost/algorithm/string/trim.hpp> #include <sstream> #include <string> #include <vector> using namespace solidity; using namespace solidity::util; bool solidity::util::stringWithinDistance(std::string const& _str1, std::string const& _str2, size_t _maxDistance, size_t _lenThreshold) { if (_str1 == _str2) return true; size_t n1 = _str1.size(); size_t n2 = _str2.size(); if (_lenThreshold > 0 && n1 * n2 > _lenThreshold) return false; size_t distance = stringDistance(_str1, _str2); // if distance is not greater than _maxDistance, and distance is strictly less than length of both names, they can be considered similar // this is to avoid irrelevant suggestions return distance <= _maxDistance && distance < n1 && distance < n2; } size_t solidity::util::stringDistance(std::string const& _str1, std::string const& _str2) { size_t n1 = _str1.size(); size_t n2 = _str2.size(); // Optimize by storing only last 2 rows and current row. So first index is considered modulo 3 // This is a two-dimensional array of size 3 x (n2 + 1). std::vector<size_t> dp(3 * (n2 + 1)); // In this dp formulation of Damerau–Levenshtein distance we are assuming that the strings are 1-based to make base case storage easier. // So index accesser to _name1 and _name2 have to be adjusted accordingly for (size_t i1 = 0; i1 <= n1; ++i1) for (size_t i2 = 0; i2 <= n2; ++i2) { size_t x = 0; if (std::min(i1, i2) == 0) // base case x = std::max(i1, i2); else { size_t left = dp[(i1 - 1) % 3 + i2 * 3]; size_t up = dp[(i1 % 3) + (i2 - 1) * 3]; size_t upleft = dp[((i1 - 1) % 3) + (i2 - 1) * 3]; // deletion and insertion x = std::min(left + 1, up + 1); if (_str1[i1-1] == _str2[i2-1]) // same chars, can skip x = std::min(x, upleft); else // different chars so try substitution x = std::min(x, upleft + 1); // transposing if (i1 > 1 && i2 > 1 && _str1[i1 - 1] == _str2[i2 - 2] && _str1[i1 - 2] == _str2[i2 - 1]) x = std::min(x, dp[((i1 - 2) % 3) + (i2 - 2) * 3] + 1); } dp[(i1 % 3) + i2 * 3] = x; } return dp[(n1 % 3) + n2 * 3]; } std::string solidity::util::quotedAlternativesList(std::vector<std::string> const& suggestions) { std::vector<std::string> quotedSuggestions; for (auto& suggestion: suggestions) quotedSuggestions.emplace_back("\"" + suggestion + "\""); return joinHumanReadable(quotedSuggestions, ", ", " or "); } std::string solidity::util::suffixedVariableNameList(std::string const& _baseName, size_t _startSuffix, size_t _endSuffix) { std::string result; if (_startSuffix < _endSuffix) { result = _baseName + std::to_string(_startSuffix++); while (_startSuffix < _endSuffix) result += ", " + _baseName + std::to_string(_startSuffix++); } else if (_endSuffix < _startSuffix) { result = _baseName + std::to_string(_endSuffix++); while (_endSuffix < _startSuffix) result = _baseName + std::to_string(_endSuffix++) + ", " + result; } return result; } namespace { /// Try to format as N * 2**x std::optional<std::string> tryFormatPowerOfTwo(bigint const& _value) { bigint prefix = _value; // when multiple trailing zero bytes, format as N * 2**x int i = 0; for (; (prefix & 0xff) == 0; prefix >>= 8) ++i; if (i <= 2) return std::nullopt; // 0x100 yields 2**8 (N is 1 and redundant) if (prefix == 1) return {fmt::format("2**{}", i * 8)}; else if ((prefix & (prefix - 1)) == 0) { int j = 0; for (; (prefix & 0x1) == 0; prefix >>= 1) j++; return {fmt::format("2**{}", i * 8 + j)}; } else return {fmt::format( "{} * 2**{}", toHex(toCompactBigEndian(prefix), HexPrefix::Add, HexCase::Mixed), i * 8 )}; } } std::string solidity::util::formatNumberReadable(bigint const& _value, bool _useTruncation) { bool const isNegative = _value < 0; bigint const absValue = isNegative ? (bigint(-1) * _value) : bigint(_value); std::string const sign = isNegative ? "-" : ""; // smaller numbers return as decimal if (absValue <= 0x1000000) return sign + absValue.str(); if (auto result = tryFormatPowerOfTwo(absValue)) return {sign + *result}; else if (auto result = tryFormatPowerOfTwo(absValue + 1)) return {sign + *result + (isNegative ? " + 1" : " - 1")}; std::string str = toHex(toCompactBigEndian(absValue), HexPrefix::Add, HexCase::Mixed); if (_useTruncation) { // return as interior-truncated hex. size_t len = str.size(); if (len < 24) return sign + str; size_t const initialChars = 6; size_t const finalChars = 4; size_t numSkipped = len - initialChars - finalChars; return fmt::format( "{}{}...{{+{} more}}...{}", sign, str.substr(0, initialChars), numSkipped, str.substr(len-finalChars, len) ); } return sign + str; } std::string solidity::util::prefixLines( std::string const& _input, std::string const& _prefix, bool _trimPrefix ) { std::ostringstream output; printPrefixed(output, _input, _prefix, _trimPrefix, false /* _ensureFinalNewline */); return output.str(); } void solidity::util::printPrefixed( std::ostream& _output, std::string const& _input, std::string const& _prefix, bool _trimPrefix, bool _ensureFinalNewline ) { std::istringstream input(_input); std::string line; while (std::getline(input, line)) { if (line.empty() && _trimPrefix) _output << boost::trim_right_copy(_prefix); else _output << _prefix << line; if (!input.eof() || _ensureFinalNewline) _output << '\n'; } }
6,315
C++
.cpp
192
30.276042
139
0.668364
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,250
Profiler.cpp
ethereum_solidity/libsolutil/Profiler.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libsolutil/Profiler.h> #include <fmt/format.h> #include <algorithm> #include <iostream> #include <vector> using namespace std::chrono; using namespace solidity; #ifdef PROFILE_OPTIMIZER_STEPS util::Profiler::Probe::Probe(std::string _scopeName): m_scopeName(std::move(_scopeName)), m_startTime(steady_clock::now()) { } util::Profiler::Probe::~Probe() { steady_clock::time_point endTime = steady_clock::now(); auto [metricsIt, inserted] = Profiler::singleton().m_metrics.try_emplace(m_scopeName, Metrics{0us, 0}); metricsIt->second.durationInMicroseconds += duration_cast<microseconds>(endTime - m_startTime); ++metricsIt->second.callCount; } util::Profiler::~Profiler() { outputPerformanceMetrics(); } util::Profiler& util::Profiler::singleton() { static Profiler profiler; return profiler; } void util::Profiler::outputPerformanceMetrics() { std::vector<std::pair<std::string, Metrics>> sortedMetrics(m_metrics.begin(), m_metrics.end()); std::sort( sortedMetrics.begin(), sortedMetrics.end(), [](std::pair<std::string, Metrics> const& _lhs, std::pair<std::string, Metrics> const& _rhs) -> bool { return _lhs.second.durationInMicroseconds < _rhs.second.durationInMicroseconds; } ); std::chrono::microseconds totalDurationInMicroseconds = 0us; size_t totalCallCount = 0; for (auto&& [scopeName, scopeMetrics]: sortedMetrics) { totalDurationInMicroseconds += scopeMetrics.durationInMicroseconds; totalCallCount += scopeMetrics.callCount; } std::cerr << "PERFORMANCE METRICS FOR PROFILED SCOPES\n\n"; std::cerr << "| Time % | Time | Calls | Scope |\n"; std::cerr << "|-------:|-----------:|--------:|--------------------------------|\n"; double totalDurationInSeconds = duration_cast<duration<double>>(totalDurationInMicroseconds).count(); for (auto&& [scopeName, scopeMetrics]: sortedMetrics) { double durationInSeconds = duration_cast<duration<double>>(scopeMetrics.durationInMicroseconds).count(); double percentage = 100.0 * durationInSeconds / totalDurationInSeconds; std::cerr << fmt::format( "| {:5.1f}% | {:8.3f} s | {:7} | {:30} |\n", percentage, durationInSeconds, scopeMetrics.callCount, scopeName ); } std::cerr << fmt::format("| {:5.1f}% | {:8.3f} s | {:7} | {:30} |\n", 100.0, totalDurationInSeconds, totalCallCount, "**TOTAL**"); } #endif
3,059
C++
.cpp
80
36.0625
131
0.72104
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,251
Numeric.cpp
ethereum_solidity/libsolutil/Numeric.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libsolutil/Numeric.h> #include <liblangutil/Exceptions.h> using namespace solidity; bool solidity::fitsPrecisionBaseX(bigint const& _mantissa, double _log2OfBase, uint32_t _exp) { if (_mantissa == 0) return true; solAssert(_mantissa > 0, ""); size_t const bitsMax = 4096; size_t mostSignificantMantissaBit = static_cast<size_t>(boost::multiprecision::msb(_mantissa)); if (mostSignificantMantissaBit > bitsMax) // _mantissa >= 2 ^ 4096 return false; bigint bitsNeeded = mostSignificantMantissaBit + bigint(floor(double(_exp) * _log2OfBase)) + 1; return bitsNeeded <= bitsMax; }
1,291
C++
.cpp
29
42.37931
96
0.77458
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
3,252
Whiskers.cpp
ethereum_solidity/libsolutil/Whiskers.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 /** @file Whiskers.cpp * @author Chris <chis@ethereum.org> * @date 2017 * * Moustache-like templates. */ #include <libsolutil/Whiskers.h> #include <libsolutil/Assertions.h> #include <regex> using namespace solidity::util; Whiskers::Whiskers(std::string _template): m_template(std::move(_template)) { checkTemplateValid(); } Whiskers& Whiskers::operator()(std::string _parameter, std::string _value) { checkParameterValid(_parameter); checkParameterUnknown(_parameter); checkTemplateContainsTags(_parameter, {""}); m_parameters[std::move(_parameter)] = std::move(_value); return *this; } Whiskers& Whiskers::operator()(std::string _parameter, bool _value) { checkParameterValid(_parameter); checkParameterUnknown(_parameter); checkTemplateContainsTags(_parameter, {"?", "/"}); m_conditions[std::move(_parameter)] = _value; return *this; } Whiskers& Whiskers::operator()( std::string _listParameter, std::vector<std::map<std::string, std::string>> _values ) { checkParameterValid(_listParameter); checkParameterUnknown(_listParameter); checkTemplateContainsTags(_listParameter, {"#", "/"}); for (auto const& element: _values) for (auto const& val: element) checkParameterValid(val.first); m_listParameters[std::move(_listParameter)] = std::move(_values); return *this; } std::string Whiskers::render() const { return replace(m_template, m_parameters, m_conditions, m_listParameters); } void Whiskers::checkTemplateValid() const { std::regex validTemplate("<[#?!\\/]\\+{0,1}[a-zA-Z0-9_$-]+(?:[^a-zA-Z0-9_$>-]|$)"); std::smatch match; assertThrow( !regex_search(m_template, match, validTemplate), WhiskersError, "Template contains an invalid/unclosed tag " + match.str() ); } void Whiskers::checkParameterValid(std::string const& _parameter) const { static std::regex validParam("^" + paramRegex() + "$"); assertThrow( regex_match(_parameter, validParam), WhiskersError, "Parameter" + _parameter + " contains invalid characters." ); } void Whiskers::checkParameterUnknown(std::string const& _parameter) const { assertThrow( !m_parameters.count(_parameter), WhiskersError, _parameter + " already set as value parameter." ); assertThrow( !m_conditions.count(_parameter), WhiskersError, _parameter + " already set as condition parameter." ); assertThrow( !m_listParameters.count(_parameter), WhiskersError, _parameter + " already set as list parameter." ); } void Whiskers::checkTemplateContainsTags(std::string const& _parameter, std::vector<std::string> const& _prefixes) const { for (auto const& prefix: _prefixes) { std::string tag{"<" + prefix + _parameter + ">"}; assertThrow( m_template.find(tag) != std::string::npos, WhiskersError, "Tag '" + tag + "' not found in template:\n" + m_template ); } } namespace { template<class ReplaceCallback> std::string regex_replace( std::string const& _source, std::regex const& _pattern, ReplaceCallback _replace, std::regex_constants::match_flag_type _flags = std::regex_constants::match_default ) { std::sregex_iterator curMatch(_source.begin(), _source.end(), _pattern, _flags); std::sregex_iterator matchEnd; std::string::const_iterator lastMatchedPos(_source.cbegin()); std::string result; while (curMatch != matchEnd) { result.append(curMatch->prefix().first, curMatch->prefix().second); result.append(_replace(*curMatch)); lastMatchedPos = (*curMatch)[0].second; ++curMatch; } result.append(lastMatchedPos, _source.cend()); return result; } } std::string Whiskers::replace( std::string const& _template, StringMap const& _parameters, std::map<std::string, bool> const& _conditions, std::map<std::string, std::vector<StringMap>> const& _listParameters ) { static std::regex listOrTag( "<(" + paramRegex() + ")>|" "<#(" + paramRegex() + ")>((?:.|\\r|\\n)*?)</\\2>|" "<\\?(\\+?" + paramRegex() + ")>((?:.|\\r|\\n)*?)(<!\\4>((?:.|\\r|\\n)*?))?</\\4>" ); return regex_replace(_template, listOrTag, [&](std::match_results<std::string::const_iterator> _match) -> std::string { std::string tagName(_match[1]); std::string listName(_match[2]); std::string conditionName(_match[4]); if (!tagName.empty()) { assertThrow( _parameters.count(tagName), WhiskersError, "Value for tag " + tagName + " not provided.\n" + "Template:\n" + _template ); return _parameters.at(tagName); } else if (!listName.empty()) { std::string templ(_match[3]); assertThrow( _listParameters.count(listName), WhiskersError, "List parameter " + listName + " not set." ); std::string replacement; for (auto const& parameters: _listParameters.at(listName)) replacement += replace(templ, joinMaps(_parameters, parameters), _conditions); return replacement; } else { assertThrow(!conditionName.empty(), WhiskersError, ""); bool conditionValue = false; if (conditionName[0] == '+') { std::string tag = conditionName.substr(1); if (_parameters.count(tag)) conditionValue = !_parameters.at(tag).empty(); else if (_listParameters.count(tag)) conditionValue = !_listParameters.at(tag).empty(); else assertThrow(false, WhiskersError, "Tag " + tag + " used as condition but was not set."); } else { assertThrow( _conditions.count(conditionName), WhiskersError, "Condition parameter " + conditionName + " not set." ); conditionValue = _conditions.at(conditionName); } return replace( conditionValue ? _match[5] : _match[7], _parameters, _conditions, _listParameters ); } }); } Whiskers::StringMap Whiskers::joinMaps( Whiskers::StringMap const& _a, Whiskers::StringMap const& _b ) { Whiskers::StringMap ret = _a; for (auto const& x: _b) assertThrow( ret.insert(x).second, WhiskersError, "Parameter collision" ); return ret; }
6,551
C++
.cpp
222
26.887387
120
0.707356
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
3,254
Exceptions.cpp
ethereum_solidity/libsolutil/Exceptions.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libsolutil/Exceptions.h> #include <liblangutil/Exceptions.h> using namespace solidity::util; using namespace solidity::langutil; char const* Exception::what() const noexcept { // Return the comment if available. if (std::string const* cmt = comment()) return cmt->data(); // Fallback to base what(). // Boost accepts nullptr, but the C++ standard doesn't // and crashes on some platforms. return std::exception::what(); } std::string Exception::lineInfo() const { char const* const* file = boost::get_error_info<boost::throw_file>(*this); int const* line = boost::get_error_info<boost::throw_line>(*this); std::string ret; if (file) ret += *file; ret += ':'; if (line) ret += std::to_string(*line); return ret; } std::string const* Exception::comment() const noexcept { return boost::get_error_info<errinfo_comment>(*this); } SourceLocation Exception::sourceLocation() const noexcept { if (SourceLocation const* sourceLocation = boost::get_error_info<errinfo_sourceLocation>(*this)) return *sourceLocation; return SourceLocation{}; }
1,761
C++
.cpp
50
33.3
97
0.758235
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,255
JSON.cpp
ethereum_solidity/libsolutil/JSON.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 /** @file JSON.cpp * @author Alexander Arlt <alexander.arlt@arlt-labs.com> * @date 2018 */ #include <libsolutil/JSON.h> #include <libsolutil/CommonData.h> #include <boost/algorithm/string.hpp> #include <sstream> namespace solidity::util { namespace { /// Takes a JSON value (@ _json) and removes all its members with value 'null' recursively. void removeNullMembersHelper(Json& _json) { if (_json.is_array()) { for (auto& child: _json) removeNullMembersHelper(child); } else if (_json.is_object()) { for (auto it = _json.begin(); it != _json.end();) { if (it->is_null()) it = _json.erase(it); else { removeNullMembersHelper(*it); ++it; } } } } std::string escapeNewlinesAndTabsWithinStringLiterals(std::string const& _json) { std::stringstream fixed; bool inQuotes = false; for (size_t i = 0; i < _json.size(); ++i) { char c = _json[i]; // Originally we had just this here: // if (c == '"' && (i == 0 || _json[i - 1] != '\\')) // inQuotes = !inQuotes; // However, this is not working if the escape character itself was escaped. e.g. "\n\r'\"\\". if (c == '"') { size_t backslashCount = 0; size_t j = i; while (j > 0 && _json[j - 1] == '\\') { backslashCount++; j--; } if (backslashCount % 2 == 0) { inQuotes = !inQuotes; fixed << c; continue; } } if (inQuotes) { if (c == '\n') fixed << "\\n"; else if (c == '\t') fixed << "\\t"; else fixed << c; } else fixed << c; } return fixed.str(); } } // end anonymous namespace Json removeNullMembers(Json _json) { removeNullMembersHelper(_json); return _json; } std::string removeNlohmannInternalErrorIdentifier(std::string const& _input) { std::string result = _input; std::size_t startPos = result.find('['); std::size_t endPos = result.find(']', startPos); if (startPos != std::string::npos && endPos != std::string::npos) result.erase(startPos, endPos - startPos + 1); return boost::trim_copy(result); } std::string jsonPrettyPrint(Json const& _input) { return jsonPrint(_input, JsonFormat{JsonFormat::Pretty}); } std::string jsonCompactPrint(Json const& _input) { return jsonPrint(_input, JsonFormat{JsonFormat::Compact}); } std::string jsonPrint(Json const& _input, JsonFormat const& _format) { // NOTE: -1 here means no new lines (it is also the default setting) std::string dumped = _input.dump( /* indent */ (_format.format == JsonFormat::Pretty) ? static_cast<int>(_format.indent) : -1, /* indent_char */ ' ', /* ensure_ascii */ true ); return dumped; } bool jsonParseStrict(std::string const& _input, Json& _json, std::string* _errs /* = nullptr */) { try { _json = Json::parse( // TODO: remove this in the next breaking release? escapeNewlinesAndTabsWithinStringLiterals(_input), /* callback */ nullptr, /* allow exceptions */ true, /* ignore_comments */true ); _errs = {}; return true; } catch (Json::parse_error const& e) { if (_errs) { std::stringstream escaped; for (char c: removeNlohmannInternalErrorIdentifier(e.what())) if (std::isprint(c)) escaped << c; else escaped << "\\x" + toHex(static_cast<uint8_t>(c)); *_errs = escaped.str(); } return false; } } std::optional<Json> jsonValueByPath(Json const& _node, std::string_view _jsonPath) { if (!_node.is_object() || _jsonPath.empty()) return {}; std::string memberName = std::string(_jsonPath.substr(0, _jsonPath.find_first_of('.'))); if (!_node.contains(memberName)) return {}; if (memberName == _jsonPath) return _node[memberName]; return jsonValueByPath(_node[memberName], _jsonPath.substr(memberName.size() + 1)); } } // namespace solidity::util
4,412
C++
.cpp
157
25.343949
111
0.67416
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,256
TemporaryDirectory.cpp
ethereum_solidity/libsolutil/TemporaryDirectory.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libsolutil/TemporaryDirectory.h> #include <liblangutil/Exceptions.h> #include <boost/algorithm/string/predicate.hpp> #include <boost/filesystem.hpp> #include <regex> #include <iostream> using namespace solidity; using namespace solidity::util; namespace fs = boost::filesystem; TemporaryDirectory::TemporaryDirectory(std::string const& _prefix): m_path(fs::temp_directory_path() / fs::unique_path(_prefix + "-%%%%-%%%%-%%%%-%%%%")) { // Prefix should just be a file name and not contain anything that would make us step out of /tmp. solAssert(fs::path(_prefix) == fs::path(_prefix).stem(), ""); fs::create_directory(m_path); } TemporaryDirectory::TemporaryDirectory( std::vector<boost::filesystem::path> const& _subdirectories, std::string const& _prefix ): TemporaryDirectory(_prefix) { for (boost::filesystem::path const& subdirectory: _subdirectories) { solAssert(!subdirectory.is_absolute() && subdirectory.root_path() != "/", ""); solAssert( m_path.lexically_relative(subdirectory).empty() || *m_path.lexically_relative(subdirectory).begin() != "..", "" ); boost::filesystem::create_directories(m_path / subdirectory); } } TemporaryDirectory::~TemporaryDirectory() { // A few paranoid sanity checks just to be extra sure we're not deleting someone's homework. solAssert(m_path.string().find(fs::temp_directory_path().string()) == 0, ""); solAssert(!fs::equivalent(m_path, fs::temp_directory_path()), ""); solAssert(!fs::equivalent(m_path, m_path.root_path()), ""); solAssert(!m_path.empty(), ""); boost::system::error_code errorCode; uintmax_t numRemoved = fs::remove_all(m_path, errorCode); if (errorCode.value() != boost::system::errc::success) { std::cerr << "Failed to completely remove temporary directory '" << m_path << "'. "; std::cerr << "Only " << numRemoved << " files were actually removed." << std::endl; std::cerr << "Reason: " << errorCode.message() << std::endl; } } TemporaryWorkingDirectory::TemporaryWorkingDirectory(fs::path const& _newDirectory): m_originalWorkingDirectory(fs::current_path()) { fs::current_path(_newDirectory); } TemporaryWorkingDirectory::~TemporaryWorkingDirectory() { fs::current_path(m_originalWorkingDirectory); }
2,917
C++
.cpp
72
38.5
99
0.739837
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
3,259
DisjointSet.cpp
ethereum_solidity/libsolutil/DisjointSet.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libsolutil/DisjointSet.h> #include <liblangutil/Exceptions.h> #include <numeric> using namespace solidity::util; ContiguousDisjointSet::ContiguousDisjointSet(size_t const _numNodes): m_parents(_numNodes), m_neighbors(_numNodes), m_sizes(_numNodes, static_cast<value_type>(1)), m_numSets(_numNodes) { // each is their own neighbor and parent std::iota(m_parents.begin(), m_parents.end(), 0); std::iota(m_neighbors.begin(), m_neighbors.end(), 0); } size_t ContiguousDisjointSet::numSets() const { return m_numSets; } ContiguousDisjointSet::value_type ContiguousDisjointSet::find(value_type const _element) const { solAssert(_element < m_parents.size()); // path halving value_type rootElement = _element; while (rootElement != m_parents[rootElement]) { m_parents[rootElement] = m_parents[m_parents[rootElement]]; rootElement = m_parents[rootElement]; } return rootElement; } void ContiguousDisjointSet::merge(value_type const _x, value_type const _y, bool const _mergeBySize) { auto xRoot = find(_x); auto yRoot = find(_y); if (xRoot == yRoot) return; // we're done, nothing to merge here // if merge by size: merge smaller (yRoot) into larger (xRoot) subset; // otherwise if _x is the representative of subset(_x), it will stay representative if (_mergeBySize && m_sizes[xRoot] < m_sizes[yRoot]) std::swap(xRoot, yRoot); m_parents[yRoot] = xRoot; m_sizes[xRoot] += m_sizes[yRoot]; std::swap(m_neighbors[xRoot], m_neighbors[yRoot]); --m_numSets; } bool ContiguousDisjointSet::sameSubset(value_type const _x, value_type const _y) const { return find(_x) == find(_y); } ContiguousDisjointSet::size_type ContiguousDisjointSet::sizeOfSubset(value_type const _x) const { return m_sizes[find(_x)]; } std::set<ContiguousDisjointSet::value_type> ContiguousDisjointSet::subset(value_type const _x) const { solAssert(_x < m_parents.size()); std::set<value_type> result{_x}; value_type neighbor = m_neighbors[_x]; while (neighbor != _x) { result.insert(neighbor); neighbor = m_neighbors[neighbor]; } return result; } std::vector<std::set<ContiguousDisjointSet::value_type>> ContiguousDisjointSet::subsets() const { std::vector<std::set<value_type>> result; std::vector<std::uint8_t> visited(m_parents.size(), false); for (value_type x = 0; x < m_parents.size(); ++x) { auto xRoot = find(x); if (!visited[xRoot]) { result.push_back(subset(xRoot)); visited[xRoot] = true; } } return result; }
3,154
C++
.cpp
91
32.626374
100
0.745484
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,261
CommonIO.cpp
ethereum_solidity/libsolutil/CommonIO.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 /** @file CommonIO.cpp * @author Gav Wood <i@gavwood.com> * @date 2014 */ #include <libsolutil/CommonIO.h> #include <libsolutil/Assertions.h> #include <fstream> #if defined(_WIN32) #include <windows.h> #else #include <unistd.h> #include <termios.h> #endif using namespace solidity::util; namespace { template <typename T> inline T readFile(boost::filesystem::path const& _file) { assertThrow(boost::filesystem::exists(_file), FileNotFound, _file.string()); // ifstream does not always fail when the path leads to a directory. Instead it might succeed // with tellg() returning a nonsensical value so that std::length_error gets raised in resize(). assertThrow(boost::filesystem::is_regular_file(_file), NotAFile, _file.string()); T ret; size_t const c_elementSize = sizeof(typename T::value_type); std::ifstream is(_file.string(), std::ifstream::binary); // Technically, this can still fail even though we checked above because FS content can change at any time. assertThrow(is, FileNotFound, _file.string()); // get length of file: is.seekg(0, is.end); std::streamoff length = is.tellg(); if (length == 0) return ret; // do not read empty file (MSVC does not like it) is.seekg(0, is.beg); ret.resize((static_cast<size_t>(length) + c_elementSize - 1) / c_elementSize); is.read(const_cast<char*>(reinterpret_cast<char const*>(ret.data())), static_cast<std::streamsize>(length)); return ret; } } std::string solidity::util::readFileAsString(boost::filesystem::path const& _file) { return readFile<std::string>(_file); } std::string solidity::util::readUntilEnd(std::istream& _stdin) { std::ostringstream ss; ss << _stdin.rdbuf(); return ss.str(); } std::string solidity::util::readBytes(std::istream& _input, size_t _length) { std::string output; output.resize(_length); _input.read(output.data(), static_cast<std::streamsize>(_length)); // If read() reads fewer bytes it sets failbit in addition to eofbit. if (_input.fail()) output.resize(static_cast<size_t>(_input.gcount())); return output; } #if defined(_WIN32) class DisableConsoleBuffering { public: DisableConsoleBuffering() { m_stdin = GetStdHandle(STD_INPUT_HANDLE); GetConsoleMode(m_stdin, &m_oldMode); SetConsoleMode(m_stdin, m_oldMode & (~(ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT))); } ~DisableConsoleBuffering() { SetConsoleMode(m_stdin, m_oldMode); } private: HANDLE m_stdin; DWORD m_oldMode; }; #else class DisableConsoleBuffering { public: DisableConsoleBuffering() { tcgetattr(0, &m_termios); m_termios.c_lflag &= ~tcflag_t(ICANON); m_termios.c_lflag &= ~tcflag_t(ECHO); m_termios.c_cc[VMIN] = 1; m_termios.c_cc[VTIME] = 0; tcsetattr(0, TCSANOW, &m_termios); } ~DisableConsoleBuffering() { m_termios.c_lflag |= ICANON; m_termios.c_lflag |= ECHO; tcsetattr(0, TCSADRAIN, &m_termios); } private: struct termios m_termios; }; #endif int solidity::util::readStandardInputChar() { DisableConsoleBuffering disableConsoleBuffering; return std::cin.get(); } std::string solidity::util::absolutePath(std::string const& _path, std::string const& _reference) { boost::filesystem::path p(_path); // Anything that does not start with `.` is an absolute path. if (p.begin() == p.end() || (*p.begin() != "." && *p.begin() != "..")) return _path; boost::filesystem::path result(_reference); // If filename is "/", then remove_filename() throws. // See: https://github.com/boostorg/filesystem/issues/176 if (result.filename() != boost::filesystem::path("/")) result.remove_filename(); for (boost::filesystem::path::iterator it = p.begin(); it != p.end(); ++it) if (*it == "..") result = result.parent_path(); else if (*it != ".") result /= *it; return result.generic_string(); } std::string solidity::util::sanitizePath(std::string const& _path) { return boost::filesystem::path(_path).generic_string(); }
4,558
C++
.cpp
140
30.6
109
0.728617
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
3,262
EVMVersion.cpp
ethereum_solidity/liblangutil/EVMVersion.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 /** * EVM versioning. */ #include <liblangutil/EVMVersion.h> #include <libevmasm/Instruction.h> using namespace solidity; using namespace solidity::evmasm; using namespace solidity::langutil; bool EVMVersion::hasOpcode(Instruction _opcode, std::optional<uint8_t> _eofVersion) const { // EOF version can be only defined since prague assert(!_eofVersion.has_value() || this->m_version >= prague()); switch (_opcode) { case Instruction::RETURNDATACOPY: case Instruction::RETURNDATASIZE: return supportsReturndata(); case Instruction::STATICCALL: return !_eofVersion.has_value() && hasStaticCall(); case Instruction::SHL: case Instruction::SHR: case Instruction::SAR: return hasBitwiseShifting(); case Instruction::CREATE2: return !_eofVersion.has_value() && hasCreate2(); case Instruction::EXTCODEHASH: return !_eofVersion.has_value() && hasExtCodeHash(); case Instruction::CHAINID: return hasChainID(); case Instruction::SELFBALANCE: return hasSelfBalance(); case Instruction::BASEFEE: return hasBaseFee(); case Instruction::BLOBHASH: return hasBlobHash(); case Instruction::BLOBBASEFEE: return hasBlobBaseFee(); case Instruction::MCOPY: return hasMcopy(); case Instruction::TSTORE: case Instruction::TLOAD: return supportsTransientStorage(); // Instructions below are deprecated in EOF case Instruction::CALL: case Instruction::CALLCODE: case Instruction::DELEGATECALL: case Instruction::SELFDESTRUCT: case Instruction::JUMP: case Instruction::JUMPI: case Instruction::PC: case Instruction::CREATE: case Instruction::CODESIZE: case Instruction::CODECOPY: case Instruction::EXTCODESIZE: case Instruction::EXTCODECOPY: case Instruction::GAS: return !_eofVersion.has_value(); // Instructions below available only in EOF case Instruction::EOFCREATE: case Instruction::RETURNCONTRACT: case Instruction::DATALOADN: return _eofVersion.has_value(); default: return true; } }
2,627
C++
.cpp
80
30.7125
89
0.785827
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,264
SourceLocation.cpp
ethereum_solidity/liblangutil/SourceLocation.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <liblangutil/Exceptions.h> #include <boost/algorithm/string/split.hpp> #include <boost/algorithm/string.hpp> #include <iostream> using namespace solidity; using namespace solidity::langutil; SourceLocation solidity::langutil::parseSourceLocation(std::string const& _input, std::vector<std::shared_ptr<std::string const>> const& _sourceNames) { // Expected input: "start:length:sourceindex" enum SrcElem: size_t { Start, Length, Index }; std::vector<std::string> pos; boost::algorithm::split(pos, _input, boost::is_any_of(":")); solAssert(pos.size() == 3, "SourceLocation string must have 3 colon separated numeric fields."); auto const sourceIndex = stoi(pos[Index]); astAssert( sourceIndex == -1 || (0 <= sourceIndex && static_cast<size_t>(sourceIndex) < _sourceNames.size()), "'src'-field ill-formatted or src-index too high" ); int start = stoi(pos[Start]); int end = start + stoi(pos[Length]); SourceLocation result{start, end, {}}; if (sourceIndex != -1) result.sourceName = _sourceNames.at(static_cast<size_t>(sourceIndex)); return result; } std::ostream& solidity::langutil::operator<<(std::ostream& _out, SourceLocation const& _location) { if (!_location.isValid()) return _out << "NO_LOCATION_SPECIFIED"; if (_location.sourceName) _out << *_location.sourceName; _out << "[" << _location.start << "," << _location.end << "]"; return _out; }
2,085
C++
.cpp
48
41.270833
150
0.742447
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
3,266
CharStream.cpp
ethereum_solidity/liblangutil/CharStream.cpp
/* * This file is part of solidity. * * solidity is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * solidity is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with solidity. If not, see <http://www.gnu.org/licenses/>. * * This file is derived from the file "scanner.cc", which was part of the * V8 project. The original copyright header follows: * * Copyright 2006-2012, the V8 project authors. All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * Character stream / input file. */ #include <liblangutil/CharStream.h> #include <liblangutil/Exceptions.h> using namespace solidity; using namespace solidity::langutil; char CharStream::advanceAndGet(size_t _chars) { if (isPastEndOfInput()) return 0; m_position += _chars; if (isPastEndOfInput()) return 0; return m_source[m_position]; } char CharStream::rollback(size_t _amount) { solAssert(m_position >= _amount, ""); m_position -= _amount; return get(); } char CharStream::setPosition(size_t _location) { solAssert(_location <= m_source.size(), "Attempting to set position past end of source."); m_position = _location; return get(); } std::string CharStream::lineAtPosition(int _position) const { // if _position points to \n, it returns the line before the \n using size_type = std::string::size_type; size_type searchStart = std::min<size_type>(m_source.size(), size_type(_position)); if (searchStart > 0) searchStart--; size_type lineStart = m_source.rfind('\n', searchStart); if (lineStart == std::string::npos) lineStart = 0; else lineStart++; std::string line = m_source.substr( lineStart, std::min(m_source.find('\n', lineStart), m_source.size()) - lineStart ); if (!line.empty() && line.back() == '\r') line.pop_back(); return line; } LineColumn CharStream::translatePositionToLineColumn(int _position) const { using size_type = std::string::size_type; using diff_type = std::string::difference_type; size_type searchPosition = std::min<size_type>(m_source.size(), size_type(_position)); int lineNumber = static_cast<int>(count(m_source.begin(), m_source.begin() + diff_type(searchPosition), '\n')); size_type lineStart; if (searchPosition == 0) lineStart = 0; else { lineStart = m_source.rfind('\n', searchPosition - 1); lineStart = lineStart == std::string::npos ? 0 : lineStart + 1; } return LineColumn{lineNumber, static_cast<int>(searchPosition - lineStart)}; } std::string_view CharStream::text(SourceLocation const& _location) const { if (!_location.hasText()) return {}; solAssert(_location.sourceName && *_location.sourceName == m_name, ""); solAssert(static_cast<size_t>(_location.end) <= m_source.size(), ""); return std::string_view{m_source}.substr( static_cast<size_t>(_location.start), static_cast<size_t>(_location.end - _location.start) ); } std::string CharStream::singleLineSnippet(std::string const& _sourceCode, SourceLocation const& _location) { if (!_location.hasText()) return {}; if (static_cast<size_t>(_location.start) >= _sourceCode.size()) return {}; std::string cut = _sourceCode.substr(static_cast<size_t>(_location.start), static_cast<size_t>(_location.end - _location.start)); auto newLinePos = cut.find_first_of("\n\r"); if (newLinePos != std::string::npos) cut = cut.substr(0, newLinePos) + "..."; return cut; } std::optional<int> CharStream::translateLineColumnToPosition(LineColumn const& _lineColumn) const { return translateLineColumnToPosition(m_source, _lineColumn); } std::optional<int> CharStream::translateLineColumnToPosition(std::string const& _text, LineColumn const& _input) { if (_input.line < 0) return std::nullopt; size_t offset = 0; for (int i = 0; i < _input.line; i++) { offset = _text.find('\n', offset); if (offset == _text.npos) return std::nullopt; offset++; // Skip linefeed. } size_t endOfLine = _text.find('\n', offset); if (endOfLine == std::string::npos) endOfLine = _text.size(); if (offset + static_cast<size_t>(_input.column) > endOfLine) return std::nullopt; return offset + static_cast<size_t>(_input.column); }
5,997
C++
.cpp
156
36.384615
130
0.738108
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
3,267
ParserBase.cpp
ethereum_solidity/liblangutil/ParserBase.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 /** * @author Christian <c@ethdev.com> * @date 2016 * Solidity parser shared functionality. */ #include <liblangutil/ParserBase.h> #include <liblangutil/Scanner.h> #include <liblangutil/ErrorReporter.h> using namespace solidity; using namespace solidity::langutil; SourceLocation ParserBase::currentLocation() const { return m_scanner->currentLocation(); } Token ParserBase::currentToken() const { return m_scanner->currentToken(); } Token ParserBase::peekNextToken() const { return m_scanner->peekNextToken(); } std::string ParserBase::currentLiteral() const { return m_scanner->currentLiteral(); } Token ParserBase::advance() { return m_scanner->next(); } std::string ParserBase::tokenName(Token _token) { if (_token == Token::Identifier) return "identifier"; else if (_token == Token::EOS) return "end of source"; else if (TokenTraits::isReservedKeyword(_token)) return "reserved keyword '" + TokenTraits::friendlyName(_token) + "'"; else if (TokenTraits::isElementaryTypeName(_token)) //for the sake of accuracy in reporting { ElementaryTypeNameToken elemTypeName = m_scanner->currentElementaryTypeNameToken(); return "'" + elemTypeName.toString() + "'"; } else return "'" + TokenTraits::friendlyName(_token) + "'"; } void ParserBase::expectToken(Token _value, bool _advance) { Token tok = m_scanner->currentToken(); if (tok != _value) fatalParserError( 2314_error, "Expected " + ParserBase::tokenName(_value) + " but got " + tokenName(tok) ); if (_advance) advance(); } void ParserBase::increaseRecursionDepth() { m_recursionDepth++; if (m_recursionDepth >= 1200) fatalParserError(7319_error, "Maximum recursion depth reached during parsing."); } void ParserBase::decreaseRecursionDepth() { solAssert(m_recursionDepth > 0, ""); m_recursionDepth--; } void ParserBase::parserWarning(ErrorId _error, std::string const& _description) { m_errorReporter.warning(_error, currentLocation(), _description); } void ParserBase::parserWarning(ErrorId _error, SourceLocation const& _location, std::string const& _description) { m_errorReporter.warning(_error, _location, _description); } void ParserBase::parserError(ErrorId _error, SourceLocation const& _location, std::string const& _description) { m_errorReporter.parserError(_error, _location, _description); } void ParserBase::parserError(ErrorId _error, std::string const& _description) { parserError(_error, currentLocation(), _description); } void ParserBase::fatalParserError(ErrorId _error, std::string const& _description) { fatalParserError(_error, currentLocation(), _description); } void ParserBase::fatalParserError(ErrorId _error, SourceLocation const& _location, std::string const& _description) { m_errorReporter.fatalParserError(_error, _location, _description); }
3,483
C++
.cpp
106
31.04717
115
0.769735
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,268
DebugInfoSelection.cpp
ethereum_solidity/liblangutil/DebugInfoSelection.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <liblangutil/DebugInfoSelection.h> #include <liblangutil/Exceptions.h> #include <libsolutil/StringUtils.h> #include <boost/algorithm/string/trim.hpp> #include <range/v3/range/conversion.hpp> #include <range/v3/view/map.hpp> #include <range/v3/view/split.hpp> #include <vector> using namespace solidity; using namespace solidity::langutil; using namespace solidity::util; DebugInfoSelection const DebugInfoSelection::All(bool _value) noexcept { DebugInfoSelection result; for (bool DebugInfoSelection::* member: componentMap() | ranges::views::values) result.*member = _value; return result; } DebugInfoSelection const DebugInfoSelection::Only(bool DebugInfoSelection::* _member) noexcept { DebugInfoSelection result{}; result.*_member = true; return result; } std::optional<DebugInfoSelection> DebugInfoSelection::fromString(std::string_view _input) { // TODO: Make more stuff constexpr and make it a static_assert(). solAssert(componentMap().count("all") == 0, ""); solAssert(componentMap().count("none") == 0, ""); if (_input == "all") return All(); if (_input == "none") return None(); return fromComponents(_input | ranges::views::split(',') | ranges::to<std::vector<std::string>>); } std::optional<DebugInfoSelection> DebugInfoSelection::fromComponents( std::vector<std::string> const& _componentNames, bool _acceptWildcards ) { solAssert(componentMap().count("*") == 0, ""); DebugInfoSelection selection; for (auto const& component: _componentNames) { if (component == "*") return (_acceptWildcards ? std::make_optional(DebugInfoSelection::All()) : std::nullopt); if (!selection.enable(component)) return std::nullopt; } return selection; } bool DebugInfoSelection::enable(std::string const& _component) { auto memberIt = componentMap().find(boost::trim_copy(_component)); if (memberIt == componentMap().end()) return false; this->*(memberIt->second) = true; return true; } bool DebugInfoSelection::any() const noexcept { for (bool DebugInfoSelection::* member: componentMap() | ranges::views::values) if (this->*member) return true; return false; } bool DebugInfoSelection::all() const noexcept { for (bool DebugInfoSelection::* member: componentMap() | ranges::views::values) if (!(this->*member)) return false; return true; } DebugInfoSelection& DebugInfoSelection::operator&=(DebugInfoSelection const& _other) { for (bool DebugInfoSelection::* member: componentMap() | ranges::views::values) this->*member &= _other.*member; return *this; } DebugInfoSelection& DebugInfoSelection::operator|=(DebugInfoSelection const& _other) { for (bool DebugInfoSelection::* member: componentMap() | ranges::views::values) this->*member |= _other.*member; return *this; } DebugInfoSelection DebugInfoSelection::operator&(DebugInfoSelection _other) const noexcept { _other &= *this; return _other; } DebugInfoSelection DebugInfoSelection::operator|(DebugInfoSelection _other) const noexcept { _other |= *this; return _other; } bool DebugInfoSelection::operator==(DebugInfoSelection const& _other) const noexcept { for (bool DebugInfoSelection::* member: componentMap() | ranges::views::values) if (this->*member != _other.*member) return false; return true; } std::ostream& langutil::operator<<(std::ostream& _stream, DebugInfoSelection const& _selection) { std::vector<std::string> selectedComponentNames; for (auto const& [name, member]: _selection.componentMap()) if (_selection.*member) selectedComponentNames.push_back(name); return _stream << joinHumanReadable(selectedComponentNames, ","); }
4,299
C++
.cpp
124
32.653226
98
0.762491
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
3,269
Exceptions.cpp
ethereum_solidity/liblangutil/Exceptions.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 /** * @author Liana <liana@ethdev.com> * @date 2015 * Solidity exception hierarchy. */ #include <liblangutil/Exceptions.h> #include <boost/algorithm/string/case_conv.hpp> #include <boost/algorithm/string/trim.hpp> using namespace solidity; using namespace solidity::langutil; std::map<Error::Type, std::string> const Error::m_errorTypeNames = { {Error::Type::IOError, "IOError"}, {Error::Type::FatalError, "FatalError"}, {Error::Type::JSONError, "JSONError"}, {Error::Type::InternalCompilerError, "InternalCompilerError"}, {Error::Type::CompilerError, "CompilerError"}, {Error::Type::Exception, "Exception"}, {Error::Type::CodeGenerationError, "CodeGenerationError"}, {Error::Type::DeclarationError, "DeclarationError"}, {Error::Type::DocstringParsingError, "DocstringParsingError"}, {Error::Type::ParserError, "ParserError"}, {Error::Type::SyntaxError, "SyntaxError"}, {Error::Type::TypeError, "TypeError"}, {Error::Type::UnimplementedFeatureError, "UnimplementedFeatureError"}, {Error::Type::YulException, "YulException"}, {Error::Type::SMTLogicException, "SMTLogicException"}, {Error::Type::Warning, "Warning"}, {Error::Type::Info, "Info"}, }; Error::Error( ErrorId _errorId, Error::Type _type, std::string const& _description, SourceLocation const& _location, SecondarySourceLocation const& _secondaryLocation ): m_errorId(_errorId), m_type(_type) { if (_location.isValid()) *this << errinfo_sourceLocation(_location); if (!_secondaryLocation.infos.empty()) *this << errinfo_secondarySourceLocation(_secondaryLocation); if (!_description.empty()) *this << util::errinfo_comment(_description); } SourceLocation const* Error::sourceLocation() const noexcept { return boost::get_error_info<errinfo_sourceLocation>(*this); } SecondarySourceLocation const* Error::secondarySourceLocation() const noexcept { return boost::get_error_info<errinfo_secondarySourceLocation>(*this); }
2,608
C++
.cpp
67
37.044776
78
0.769261
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,270
SourceReferenceExtractor.cpp
ethereum_solidity/liblangutil/SourceReferenceExtractor.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <liblangutil/SourceReferenceExtractor.h> #include <liblangutil/Exceptions.h> #include <liblangutil/CharStreamProvider.h> #include <liblangutil/CharStream.h> #include <algorithm> #include <cmath> #include <variant> using namespace solidity; using namespace solidity::langutil; SourceReferenceExtractor::Message SourceReferenceExtractor::extract( CharStreamProvider const& _charStreamProvider, util::Exception const& _exception, std::variant<Error::Type, Error::Severity> _typeOrSeverity ) { SourceLocation const* location = boost::get_error_info<errinfo_sourceLocation>(_exception); std::string const* message = boost::get_error_info<util::errinfo_comment>(_exception); SourceReference primary = extract(_charStreamProvider, location, message ? *message : ""); std::vector<SourceReference> secondary; auto secondaryLocation = boost::get_error_info<errinfo_secondarySourceLocation>(_exception); if (secondaryLocation && !secondaryLocation->infos.empty()) for (auto const& info: secondaryLocation->infos) secondary.emplace_back(extract(_charStreamProvider, &info.second, info.first)); return Message{std::move(primary), _typeOrSeverity, std::move(secondary), std::nullopt}; } SourceReferenceExtractor::Message SourceReferenceExtractor::extract( CharStreamProvider const& _charStreamProvider, Error const& _error, std::variant<Error::Type, Error::Severity> _typeOrSeverity ) { Message message = extract(_charStreamProvider, static_cast<util::Exception>(_error), _typeOrSeverity); message.errorId = _error.errorId(); return message; } SourceReference SourceReferenceExtractor::extract( CharStreamProvider const& _charStreamProvider, SourceLocation const* _location, std::string message ) { if (!_location || !_location->sourceName) // Nothing we can extract here return SourceReference::MessageOnly(std::move(message)); if (!_location->hasText()) // No source text, so we can only extract the source name return SourceReference::MessageOnly(std::move(message), *_location->sourceName); CharStream const& charStream = _charStreamProvider.charStream(*_location->sourceName); LineColumn const interest = charStream.translatePositionToLineColumn(_location->start); LineColumn start = interest; LineColumn end = charStream.translatePositionToLineColumn(_location->end); bool const isMultiline = start.line != end.line; std::string line = charStream.lineAtPosition(_location->start); int locationLength = isMultiline ? int(line.length()) - start.column : end.column - start.column; if (locationLength > 150) { auto const lhs = static_cast<size_t>(start.column) + 35; std::string::size_type const rhs = (isMultiline ? line.length() : static_cast<size_t>(end.column)) - 35; line = line.substr(0, lhs) + " ... " + line.substr(rhs); end.column = start.column + 75; locationLength = 75; } if (line.length() > 150) { int const len = static_cast<int>(line.length()); line = line.substr( static_cast<size_t>(std::max(0, start.column - 35)), static_cast<size_t>(std::min(start.column, 35)) + static_cast<size_t>( std::min(locationLength + 35, len - start.column) ) ); if (start.column + locationLength + 35 < len) line += " ..."; if (start.column > 35) { line = " ... " + line; start.column = 40; } end.column = start.column + static_cast<int>(locationLength); } return SourceReference{ std::move(message), *_location->sourceName, interest, isMultiline, line, std::min(start.column, static_cast<int>(line.length())), std::min(end.column, static_cast<int>(line.length())) }; }
4,281
C++
.cpp
105
38.390476
106
0.757517
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
3,273
SourceReferenceFormatter.cpp
ethereum_solidity/liblangutil/SourceReferenceFormatter.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 /** * Formatting functions for errors referencing positions and locations in the source. */ #include <liblangutil/SourceReferenceFormatter.h> #include <liblangutil/Exceptions.h> #include <liblangutil/CharStream.h> #include <liblangutil/CharStreamProvider.h> #include <libsolutil/UTF8.h> #include <iomanip> #include <string_view> #include <variant> using namespace solidity; using namespace solidity::langutil; using namespace solidity::util; using namespace solidity::util::formatting; namespace { std::string replaceNonTabs(std::string_view _utf8Input, char _filler) { std::string output; for (char const c: _utf8Input) if ((c & 0xc0) != 0x80) output.push_back(c == '\t' ? '\t' : _filler); return output; } } std::string SourceReferenceFormatter::formatErrorInformation(Error const& _error, CharStream const& _charStream) { return formatErrorInformation( _error, SingletonCharStreamProvider(_charStream) ); } char const* SourceReferenceFormatter::errorTextColor(Error::Severity _severity) { switch (_severity) { case Error::Severity::Error: return RED; case Error::Severity::Warning: return YELLOW; case Error::Severity::Info: return WHITE; } util::unreachable(); } char const* SourceReferenceFormatter::errorHighlightColor(Error::Severity _severity) { switch (_severity) { case Error::Severity::Error: return RED_BACKGROUND; case Error::Severity::Warning: return ORANGE_BACKGROUND_256; case Error::Severity::Info: return GRAY_BACKGROUND; } util::unreachable(); } AnsiColorized SourceReferenceFormatter::normalColored() const { return AnsiColorized(m_stream, m_colored, {WHITE}); } AnsiColorized SourceReferenceFormatter::frameColored() const { return AnsiColorized(m_stream, m_colored, {BOLD, BLUE}); } AnsiColorized SourceReferenceFormatter::errorColored(std::ostream& _stream, bool _colored, Error::Severity _severity) { return AnsiColorized(_stream, _colored, {BOLD, errorTextColor(_severity)}); } AnsiColorized SourceReferenceFormatter::messageColored(std::ostream& _stream, bool _colored) { return AnsiColorized(_stream, _colored, {BOLD, WHITE}); } AnsiColorized SourceReferenceFormatter::secondaryColored() const { return AnsiColorized(m_stream, m_colored, {BOLD, CYAN}); } AnsiColorized SourceReferenceFormatter::highlightColored() const { return AnsiColorized(m_stream, m_colored, {YELLOW}); } AnsiColorized SourceReferenceFormatter::diagColored() const { return AnsiColorized(m_stream, m_colored, {BOLD, YELLOW}); } void SourceReferenceFormatter::printSourceLocation(SourceReference const& _ref) { if (_ref.sourceName.empty()) return; // Nothing we can print here if (_ref.position.line < 0) { frameColored() << "-->"; m_stream << ' ' << _ref.sourceName << '\n'; return; // No line available, nothing else to print } std::string line = std::to_string(_ref.position.line + 1); // one-based line number as string std::string leftpad = std::string(line.size(), ' '); // line 0: source name m_stream << leftpad; frameColored() << "-->"; m_stream << ' ' << _ref.sourceName << ':' << line << ':' << (_ref.position.column + 1) << ":\n"; std::string_view text = _ref.text; if (m_charStreamProvider.charStream(_ref.sourceName).isImportedFromAST()) return; if (!_ref.multiline) { size_t const locationLength = static_cast<size_t>(_ref.endColumn - _ref.startColumn); // line 1: m_stream << leftpad << ' '; frameColored() << '|'; m_stream << '\n'; // line 2: frameColored() << line << " |"; m_stream << ' ' << text.substr(0, static_cast<size_t>(_ref.startColumn)); highlightColored() << text.substr(static_cast<size_t>(_ref.startColumn), locationLength); m_stream << text.substr(static_cast<size_t>(_ref.endColumn)) << '\n'; // line 3: m_stream << leftpad << ' '; frameColored() << '|'; m_stream << ' ' << replaceNonTabs(text.substr(0, static_cast<size_t>(_ref.startColumn)), ' '); diagColored() << ( locationLength == 0 ? "^" : replaceNonTabs(text.substr(static_cast<size_t>(_ref.startColumn), locationLength), '^') ); m_stream << '\n'; } else { // line 1: m_stream << leftpad << ' '; frameColored() << '|'; m_stream << '\n'; // line 2: frameColored() << line << " |"; m_stream << ' ' << text.substr(0, static_cast<size_t>(_ref.startColumn)); highlightColored() << text.substr(static_cast<size_t>(_ref.startColumn)) << '\n'; // line 3: m_stream << leftpad << ' '; frameColored() << '|'; m_stream << ' ' << replaceNonTabs(text.substr(0, static_cast<size_t>(_ref.startColumn)), ' '); diagColored() << "^ (Relevant source part starts here and spans across multiple lines)."; m_stream << '\n'; } } void SourceReferenceFormatter::printPrimaryMessage( std::ostream& _stream, std::string _message, std::variant<Error::Type, Error::Severity> _typeOrSeverity, std::optional<ErrorId> _errorId, bool _colored, bool _withErrorIds ) { errorColored(_stream, _colored, Error::errorSeverityOrType(_typeOrSeverity)) << Error::formatTypeOrSeverity(_typeOrSeverity); if (_withErrorIds && _errorId.has_value()) errorColored(_stream, _colored, Error::errorSeverityOrType(_typeOrSeverity)) << " (" << _errorId.value().error << ")"; messageColored(_stream, _colored) << ": " << _message << '\n'; } void SourceReferenceFormatter::printExceptionInformation(SourceReferenceExtractor::Message const& _msg) { printPrimaryMessage(m_stream, _msg.primary.message, _msg._typeOrSeverity, _msg.errorId, m_colored, m_withErrorIds); printSourceLocation(_msg.primary); for (auto const& secondary: _msg.secondary) { secondaryColored() << "Note"; messageColored() << ":" << (secondary.message.empty() ? "" : (" " + secondary.message)) << '\n'; printSourceLocation(secondary); } m_stream << '\n'; } void SourceReferenceFormatter::printExceptionInformation(util::Exception const& _exception, Error::Type _type) { printExceptionInformation(SourceReferenceExtractor::extract(m_charStreamProvider, _exception, _type)); } void SourceReferenceFormatter::printExceptionInformation(util::Exception const& _exception, Error::Severity _severity) { printExceptionInformation(SourceReferenceExtractor::extract(m_charStreamProvider, _exception, _severity)); } void SourceReferenceFormatter::printErrorInformation(ErrorList const& _errors) { for (auto const& error: _errors) printErrorInformation(*error); } void SourceReferenceFormatter::printErrorInformation(Error const& _error) { SourceReferenceExtractor::Message message = SourceReferenceExtractor::extract( m_charStreamProvider, _error, Error::errorSeverity(_error.type()) ); printExceptionInformation(message); }
7,319
C++
.cpp
204
33.740196
126
0.736321
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
3,275
SMTPortfolio.cpp
ethereum_solidity/libsmtutil/SMTPortfolio.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libsmtutil/SMTPortfolio.h> #include <libsmtutil/SMTLib2Interface.h> using namespace solidity; using namespace solidity::util; using namespace solidity::frontend; using namespace solidity::smtutil; SMTPortfolio::SMTPortfolio( std::vector<std::unique_ptr<BMCSolverInterface>> _solvers, std::optional<unsigned> _queryTimeout ): BMCSolverInterface(_queryTimeout), m_solvers(std::move(_solvers)) {} void SMTPortfolio::reset() { for (auto const& s: m_solvers) s->reset(); } void SMTPortfolio::push() { for (auto const& s: m_solvers) s->push(); } void SMTPortfolio::pop() { for (auto const& s: m_solvers) s->pop(); } void SMTPortfolio::declareVariable(std::string const& _name, SortPointer const& _sort) { smtAssert(_sort, ""); for (auto const& s: m_solvers) s->declareVariable(_name, _sort); } void SMTPortfolio::addAssertion(Expression const& _expr) { for (auto const& s: m_solvers) s->addAssertion(_expr); } /* * Broadcasts the SMT query to all solvers and returns a single result. * This comment explains how this result is decided. * * When a solver is queried, there are four possible answers: * SATISFIABLE (SAT), UNSATISFIABLE (UNSAT), UNKNOWN, CONFLICTING, ERROR * We say that a solver _answered_ the query if it returns either: * SAT or UNSAT * A solver did not answer the query if it returns either: * UNKNOWN (it tried but couldn't solve it) or ERROR (crash, internal error, API error, etc). * * Ideally all solvers answer the query and agree on what the answer is * (all say SAT or all say UNSAT). * * The actual logic as as follows: * 1) If at least one solver answers the query, all the non-answer results are ignored. * Here SAT/UNSAT is preferred over UNKNOWN since it's an actual answer, and over ERROR * because one buggy solver/integration shouldn't break the portfolio. * * 2) If at least one solver answers SAT and at least one answers UNSAT, at least one of them is buggy * and the result is CONFLICTING. * In the future if we have more than 2 solvers enabled we could go with the majority. * * 3) If NO solver answers the query: * If at least one solver returned UNKNOWN (where the rest returned ERROR), the result is UNKNOWN. * This is preferred over ERROR since the SMTChecker might decide to abstract the query * when it is told that this is a hard query to solve. * * If all solvers return ERROR, the result is ERROR. */ std::pair<CheckResult, std::vector<std::string>> SMTPortfolio::check(std::vector<Expression> const& _expressionsToEvaluate) { CheckResult lastResult = CheckResult::ERROR; std::vector<std::string> finalValues; for (auto const& s: m_solvers) { CheckResult result; std::vector<std::string> values; tie(result, values) = s->check(_expressionsToEvaluate); if (solverAnswered(result)) { if (!solverAnswered(lastResult)) { lastResult = result; finalValues = std::move(values); } else if (lastResult != result) { lastResult = CheckResult::CONFLICTING; break; } } else if (result == CheckResult::UNKNOWN && lastResult == CheckResult::ERROR) lastResult = result; } return std::make_pair(lastResult, finalValues); } std::vector<std::string> SMTPortfolio::unhandledQueries() { // This code assumes that the constructor guarantees that // SmtLib2Interface is in position 0, if enabled. if (!m_solvers.empty()) if (auto smtlib2 = dynamic_cast<SMTLib2Interface*>(m_solvers.front().get())) return smtlib2->unhandledQueries(); return {}; } bool SMTPortfolio::solverAnswered(CheckResult result) { return result == CheckResult::SATISFIABLE || result == CheckResult::UNSATISFIABLE; } std::string SMTPortfolio::dumpQuery(std::vector<Expression> const& _expressionsToEvaluate) { // This code assumes that the constructor guarantees that // SmtLib2Interface is in position 0, if enabled. auto smtlib2 = dynamic_cast<SMTLib2Interface*>(m_solvers.front().get()); solAssert(smtlib2, "Must use SMTLib2 solver to dump queries"); return smtlib2->dumpQuery(_expressionsToEvaluate); }
4,744
C++
.cpp
130
34.361538
123
0.7531
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
3,276
SMTLib2Context.cpp
ethereum_solidity/libsmtutil/SMTLib2Context.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libsmtutil/SMTLib2Context.h> #include <boost/functional/hash.hpp> #include <range/v3/algorithm/find_if.hpp> namespace solidity::smtutil { std::size_t SortPairHash::operator()(std::pair<SortId, SortId> const& _pair) const { std::size_t seed = 0; boost::hash_combine(seed, _pair.first); boost::hash_combine(seed, _pair.second); return seed; } SMTLib2Context::SMTLib2Context() { clear(); } bool SMTLib2Context::isDeclared(std::string const& _name) const { return m_functions.count(_name) > 0; } void SMTLib2Context::declare(std::string const& _name, SortPointer const& _sort) { auto [_, inserted] = m_functions.insert({_name, _sort}); smtAssert(inserted, "Trying to redeclare SMT function!"); } SortPointer SMTLib2Context::getDeclaredSort(std::string const& _name) const { smtAssert(isDeclared(_name)); return m_functions.at(_name); } void SMTLib2Context::clear() { m_functions.clear(); m_knownTypes.clear(); m_arraySorts.clear(); m_tupleSorts.clear(); m_bitVectorSorts.clear(); m_callback = {}; m_knownTypes.emplace_back(std::make_unique<SMTLibSort>(Kind::Bool, std::string("Bool"), std::vector<SortId>{}, SortId{0u})); m_knownTypes.emplace_back(std::make_unique<SMTLibSort>(Kind::Int, std::string("Int"), std::vector<SortId>{}, SortId{1u})); assert(m_boolSort == m_knownTypes[0]->id); assert(m_intSort == m_knownTypes[1]->id); } SortId SMTLib2Context::resolve(SortPointer const& _sort) { switch (_sort->kind) { case Kind::Int: return m_intSort; case Kind::Bool: return m_boolSort; case Kind::BitVector: return resolveBitVectorSort(dynamic_cast<BitVectorSort const&>(*_sort)); case Kind::Array: return resolveArraySort(dynamic_cast<ArraySort const&>(*_sort)); case Kind::Tuple: return resolveTupleSort(dynamic_cast<TupleSort const&>(*_sort)); default: smtAssert(false, "Invalid SMT sort"); } } SortPointer SMTLib2Context::unresolve(SortId _sortId) const { smtAssert(_sortId < m_knownTypes.size()); auto const& type = *m_knownTypes[_sortId]; switch (type.kind) { case Kind::Int: return SortProvider::sintSort; case Kind::Bool: return SortProvider::boolSort; case Kind::BitVector: { auto it = ranges::find_if(m_bitVectorSorts, [&](auto const& entry) { return entry.second == _sortId; }); smtAssert(it != m_bitVectorSorts.end()); return std::make_shared<BitVectorSort>(it->first); } case Kind::Array: { auto it = ranges::find_if(m_arraySorts, [&](auto const& entry) { return entry.second == _sortId; }); smtAssert(it != m_arraySorts.end()); return std::make_shared<ArraySort>(unresolve(it->first.first), unresolve(it->first.second)); } case Kind::Tuple: { auto const& tupleType = dynamic_cast<TupleType const&>(type); std::vector<std::string> memberNames; std::vector<SortPointer> memberTypes; for (auto&& [name, sortId] : tupleType.accessors) { memberNames.push_back(name); memberTypes.push_back(unresolve(sortId)); } return std::make_shared<TupleSort>(tupleType.name, std::move(memberNames), std::move(memberTypes)); } default: smtAssert(false, "Invalid SMT sort"); } } SortId SMTLib2Context::resolveBitVectorSort(BitVectorSort const& _sort) { auto size = _sort.size; auto it = m_bitVectorSorts.find(size); if (it == m_bitVectorSorts.end()) { auto newId = static_cast<uint32_t>(m_knownTypes.size()); m_knownTypes.emplace_back(std::make_unique<SMTLibSort>(Kind::BitVector, "(_ BitVec " + std::to_string(size) + ')', std::vector<SortId>{}, SortId{newId})); auto&& [newIt, inserted] = m_bitVectorSorts.emplace(size, SortId{newId}); smtAssert(inserted); return newIt->second; } return it->second; } SortId SMTLib2Context::resolveArraySort(ArraySort const& _sort) { smtAssert(_sort.domain && _sort.range); auto domainSort = resolve(_sort.domain); auto rangeSort = resolve(_sort.range); auto pair = std::make_pair(domainSort, rangeSort); auto it = m_arraySorts.find(pair); if (it == m_arraySorts.end()) { auto newId = static_cast<uint32_t>(m_knownTypes.size()); m_knownTypes.emplace_back(std::make_unique<SMTLibSort>(Kind::Array, "Array", std::vector<SortId>{domainSort, rangeSort}, SortId{newId})); auto&& [newIt, inserted] = m_arraySorts.emplace(pair, SortId{newId}); smtAssert(inserted); return newIt->second; } return it->second; } SortId SMTLib2Context::resolveTupleSort(TupleSort const& _sort) { auto const& tupleName = _sort.name; auto it = m_tupleSorts.find(tupleName); if (it == m_tupleSorts.end()) { std::vector<std::pair<std::string, SortId>> accessors; smtAssert(_sort.members.size() == _sort.components.size()); for (std::size_t i = 0u; i < _sort.members.size(); ++i) accessors.emplace_back(_sort.members[i], resolve(_sort.components[i])); auto newId = static_cast<uint32_t>(m_knownTypes.size()); m_knownTypes.emplace_back(std::make_unique<TupleType>(tupleName, std::move(accessors), SortId{newId})); auto&& [newIt, inserted] = m_tupleSorts.emplace(tupleName, SortId{newId}); smtAssert(inserted); if (m_callback) m_callback(_sort); return newIt->second; } return it->second; } std::string SMTLib2Context::toString(SortId _id) { auto const& sort = m_knownTypes.at(_id); switch (sort->kind) { case Kind::Int: return "Int"; case Kind::Bool: return "Bool"; case Kind::BitVector: return dynamic_cast<SMTLibSort const&>(*sort).name; case Kind::Array: { auto const& arraySort = dynamic_cast<SMTLibSort const&>(*sort); smtAssert(arraySort.args.size() == 2); return "(Array " + toString(arraySort.args.at(0)) + ' ' + toString(arraySort.args.at(1)) + ')'; } case Kind::Tuple: { auto const& tupleType = dynamic_cast<TupleType const&>(*sort); return '|' + tupleType.name + '|'; } default: smtAssert(false, "Invalid SMT sort"); } } std::string SMTLib2Context::toSmtLibSort(solidity::smtutil::SortPointer const& _sort) { return toString(resolve(_sort)); } std::string SMTLib2Context::toSExpr(Expression const& _expr) { if (_expr.arguments.empty()) return _expr.name; std::string sexpr = "("; if (_expr.name == "int2bv") { size_t size = std::stoul(_expr.arguments[1].name); auto arg = toSExpr(_expr.arguments.front()); auto int2bv = "(_ int2bv " + std::to_string(size) + ")"; // Some solvers treat all BVs as unsigned, so we need to manually apply 2's complement if needed. sexpr += std::string("ite ") + "(>= " + arg + " 0) " + "(" + int2bv + " " + arg + ") " + "(bvneg (" + int2bv + " (- " + arg + ")))"; } else if (_expr.name == "bv2int") { auto intSort = std::dynamic_pointer_cast<IntSort>(_expr.sort); smtAssert(intSort, ""); auto arg = toSExpr(_expr.arguments.front()); auto nat = "(bv2nat " + arg + ")"; if (!intSort->isSigned) return nat; auto bvSort = std::dynamic_pointer_cast<BitVectorSort>(_expr.arguments.front().sort); smtAssert(bvSort, ""); auto size = std::to_string(bvSort->size); auto pos = std::to_string(bvSort->size - 1); // Some solvers treat all BVs as unsigned, so we need to manually apply 2's complement if needed. sexpr += std::string("ite ") + "(= ((_ extract " + pos + " " + pos + ")" + arg + ") #b0) " + nat + " " + "(- (bv2nat (bvneg " + arg + ")))"; } else if (_expr.name == "const_array") { smtAssert(_expr.arguments.size() == 2, ""); auto sortSort = std::dynamic_pointer_cast<SortSort>(_expr.arguments.at(0).sort); smtAssert(sortSort, ""); auto arraySort = std::dynamic_pointer_cast<ArraySort>(sortSort->inner); smtAssert(arraySort, ""); sexpr += "(as const " + toSmtLibSort(arraySort) + ") "; sexpr += toSExpr(_expr.arguments.at(1)); } else if (_expr.name == "tuple_get") { smtAssert(_expr.arguments.size() == 2, ""); auto tupleSort = std::dynamic_pointer_cast<TupleSort>(_expr.arguments.at(0).sort); size_t index = std::stoul(_expr.arguments.at(1).name); smtAssert(index < tupleSort->members.size(), ""); sexpr += "|" + tupleSort->members.at(index) + "| " + toSExpr(_expr.arguments.at(0)); } else if (_expr.name == "tuple_constructor") { auto tupleSort = std::dynamic_pointer_cast<TupleSort>(_expr.sort); smtAssert(tupleSort, ""); sexpr += "|" + tupleSort->name + "|"; for (auto const& arg: _expr.arguments) sexpr += " " + toSExpr(arg); } else { sexpr += _expr.name; for (auto const& arg: _expr.arguments) sexpr += " " + toSExpr(arg); } sexpr += ")"; return sexpr; } std::optional<SortPointer> SMTLib2Context::getTupleType(std::string const& _name) const { auto it = m_tupleSorts.find(_name); return it == m_tupleSorts.end() ? std::nullopt : std::optional<SortPointer>(unresolve(it->second)); } std::optional<std::pair<std::string, SortPointer>> SMTLib2Context::getTupleAccessor(std::string const& _name) const { for (auto&& [_, sortId] : m_tupleSorts) { auto const& type = m_knownTypes.at(sortId); smtAssert(type->kind == Kind::Tuple); auto const& tupleType = dynamic_cast<TupleType const&>(*type); for (auto&& [memberName, memberSort] : tupleType.accessors) if (memberName == _name) return std::make_pair(memberName, unresolve(memberSort)); } return std::nullopt; } void SMTLib2Context::setTupleDeclarationCallback(TupleDeclarationCallback _callback) { m_callback = std::move(_callback); } } // namespace solidity::smtutil
9,906
C++
.cpp
285
32.442105
156
0.703503
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,277
SMTLib2Interface.cpp
ethereum_solidity/libsmtutil/SMTLib2Interface.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libsmtutil/SMTLib2Interface.h> #include <libsmtutil/SMTLib2Parser.h> #include <libsolutil/Keccak256.h> #include <boost/algorithm/string/join.hpp> #include <boost/algorithm/string/predicate.hpp> #include <range/v3/algorithm/find_if.hpp> #include <array> #include <fstream> #include <iostream> #include <memory> #include <stdexcept> #include <string> #include <utility> using namespace solidity; using namespace solidity::util; using namespace solidity::frontend; using namespace solidity::smtutil; SMTLib2Interface::SMTLib2Interface( std::map<h256, std::string> _queryResponses, ReadCallback::Callback _smtCallback, std::optional<unsigned> _queryTimeout ): BMCSolverInterface(_queryTimeout), m_queryResponses(std::move(_queryResponses)), m_smtCallback(std::move(_smtCallback)) { reset(); } void SMTLib2Interface::reset() { m_commands.clear(); m_context.clear(); m_commands.setOption("produce-models", "true"); if (m_queryTimeout) m_commands.setOption("timeout", std::to_string(*m_queryTimeout)); m_commands.setLogic("ALL"); m_context.setTupleDeclarationCallback([&](TupleSort const& tupleSort){ m_commands.declareTuple( tupleSort.name, tupleSort.members, tupleSort.components | ranges::views::transform([&](SortPointer const& sort){ return m_context.toSmtLibSort(sort); }) | ranges::to<std::vector>() ); }); } void SMTLib2Interface::push() { m_commands.push(); } void SMTLib2Interface::pop() { m_commands.pop(); } void SMTLib2Interface::declareVariable(std::string const& _name, SortPointer const& _sort) { smtAssert(_sort); if (_sort->kind == Kind::Function) declareFunction(_name, _sort); else if (!m_context.isDeclared(_name)) { m_context.declare(_name, _sort); m_commands.declareVariable(_name, toSmtLibSort(_sort)); } } void SMTLib2Interface::declareFunction(std::string const& _name, SortPointer const& _sort) { smtAssert(_sort); smtAssert(_sort->kind == Kind::Function); if (!m_context.isDeclared(_name)) { auto const& fSort = std::dynamic_pointer_cast<FunctionSort>(_sort); auto domain = toSmtLibSort(fSort->domain); std::string codomain = toSmtLibSort(fSort->codomain); m_context.declare(_name, _sort); m_commands.declareFunction(_name, domain, codomain); } } void SMTLib2Interface::addAssertion(Expression const& _expr) { m_commands.assertion(toSExpr(_expr)); } namespace { std::vector<std::string> parseValuesFromResponse(std::string const& _response) { std::stringstream ss(_response); std::string answer; ss >> answer; smtSolverInteractionRequire(answer == "sat", "SMT: Parsing model values only possible after sat answer"); std::vector<SMTLib2Expression> parsedOutput; SMTLib2Parser parser(ss); try { while (!parser.isEOF()) parsedOutput.push_back(parser.parseExpression()); } catch(SMTLib2Parser::ParsingException&) { smtSolverInteractionRequire(false, "Error during parsing SMT answer"); } smtSolverInteractionRequire(parsedOutput.size() == 1, "SMT: Expected model values as a single s-expression"); auto const& values = parsedOutput[0]; smtSolverInteractionRequire(!isAtom(values), "Invalid format of values in SMT answer"); std::vector<std::string> parsedValues; for (auto const& nameValuePair: asSubExpressions(values)) { smtSolverInteractionRequire(!isAtom(nameValuePair), "Invalid format of values in SMT answer"); smtSolverInteractionRequire(asSubExpressions(nameValuePair).size() == 2, "Invalid format of values in SMT answer"); auto const& value = asSubExpressions(nameValuePair)[1]; parsedValues.push_back(value.toString()); } return parsedValues; } } // namespace std::pair<CheckResult, std::vector<std::string>> SMTLib2Interface::check(std::vector<Expression> const& _expressionsToEvaluate) { std::string response = querySolver(dumpQuery(_expressionsToEvaluate)); CheckResult result; // TODO proper parsing if (boost::starts_with(response, "sat")) result = CheckResult::SATISFIABLE; else if (boost::starts_with(response, "unsat")) result = CheckResult::UNSATISFIABLE; else if (boost::starts_with(response, "unknown")) result = CheckResult::UNKNOWN; else result = CheckResult::ERROR; std::vector<std::string> values; if (result == CheckResult::SATISFIABLE && !_expressionsToEvaluate.empty()) values = parseValuesFromResponse(response); return std::make_pair(result, values); } std::string SMTLib2Interface::toSmtLibSort(SortPointer _sort) { return m_context.toSmtLibSort(std::move(_sort)); } std::vector<std::string> SMTLib2Interface::toSmtLibSort(std::vector<SortPointer> const& _sorts) { std::vector<std::string> ssorts; ssorts.reserve(_sorts.size()); for (auto const& sort: _sorts) ssorts.push_back(toSmtLibSort(sort)); return ssorts; } std::string SMTLib2Interface::toSExpr(solidity::smtutil::Expression const& _expr) { return m_context.toSExpr(_expr); } std::string SMTLib2Interface::checkSatAndGetValuesCommand(std::vector<Expression> const& _expressionsToEvaluate) { std::string command; if (_expressionsToEvaluate.empty()) command = "(check-sat)\n"; else { // TODO make sure these are unique for (size_t i = 0; i < _expressionsToEvaluate.size(); i++) { auto const& e = _expressionsToEvaluate.at(i); smtAssert(e.sort->kind == Kind::Int || e.sort->kind == Kind::Bool, "Invalid sort for expression to evaluate."); command += "(declare-const |EVALEXPR_" + std::to_string(i) + "| " + (e.sort->kind == Kind::Int ? "Int" : "Bool") + ")\n"; command += "(assert (= |EVALEXPR_" + std::to_string(i) + "| " + toSExpr(e) + "))\n"; } command += "(check-sat)\n"; command += "(get-value ("; for (size_t i = 0; i < _expressionsToEvaluate.size(); i++) command += "|EVALEXPR_" + std::to_string(i) + "| "; command += "))\n"; } return command; } std::string SMTLib2Interface::querySolver(std::string const& _input) { h256 inputHash = keccak256(_input); if (m_queryResponses.count(inputHash)) return m_queryResponses.at(inputHash); if (m_smtCallback) { setupSmtCallback(); auto result = m_smtCallback(ReadCallback::kindString(ReadCallback::Kind::SMTQuery), _input); if (result.success) return result.responseOrErrorMessage; } m_unhandledQueries.push_back(_input); return "unknown\n"; } std::string SMTLib2Interface::dumpQuery(std::vector<Expression> const& _expressionsToEvaluate) { return m_commands.toString() + '\n' + checkSatAndGetValuesCommand(_expressionsToEvaluate); } void SMTLib2Commands::push() { m_frameLimits.push_back(m_commands.size()); } void SMTLib2Commands::pop() { smtAssert(!m_commands.empty()); auto limit = m_frameLimits.back(); m_frameLimits.pop_back(); while (m_commands.size() > limit) m_commands.pop_back(); } std::string SMTLib2Commands::toString() const { return boost::algorithm::join(m_commands, "\n"); } void SMTLib2Commands::clear() { m_commands.clear(); m_frameLimits.clear(); } void SMTLib2Commands::assertion(std::string _expr) { m_commands.push_back("(assert " + std::move(_expr) + ')'); } void SMTLib2Commands::setOption(std::string _name, std::string _value) { m_commands.push_back("(set-option :" + std::move(_name) + ' ' + std::move(_value) + ')'); } void SMTLib2Commands::setLogic(std::string _logic) { m_commands.push_back("(set-logic " + std::move(_logic) + ')'); } void SMTLib2Commands::declareVariable(std::string _name, std::string _sort) { m_commands.push_back("(declare-fun |" + std::move(_name) + "| () " + std::move(_sort) + ')'); } void SMTLib2Commands::declareFunction(std::string const& _name, std::vector<std::string> const& _domain, std::string const& _codomain) { std::stringstream ss; ss << "(declare-fun |" << _name << "| " << '(' << boost::join(_domain, " ") << ')' << ' ' << _codomain << ')'; m_commands.push_back(ss.str()); } void SMTLib2Commands::declareTuple( std::string const& _name, std::vector<std::string> const& _memberNames, std::vector<std::string> const& _memberSorts ) { auto quotedName = '|' + _name + '|'; std::stringstream ss; ss << "(declare-datatypes ((" << quotedName << " 0)) (((" << quotedName; for (auto && [memberName, memberSort]: ranges::views::zip(_memberNames, _memberSorts)) ss << " (|" << memberName << "| " << memberSort << ")"; ss << "))))"; auto declaration = ss.str(); m_commands.push_back(ss.str()); }
8,956
C++
.cpp
259
32.540541
134
0.731893
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,278
CHCSmtLib2Interface.cpp
ethereum_solidity/libsmtutil/CHCSmtLib2Interface.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libsmtutil/CHCSmtLib2Interface.h> #include <libsmtutil/SMTLib2Parser.h> #include <libsolutil/Keccak256.h> #include <libsolutil/StringUtils.h> #include <libsolutil/Visitor.h> #include <boost/algorithm/string/join.hpp> #include <boost/algorithm/string/predicate.hpp> #include <range/v3/algorithm/all_of.hpp> #include <range/v3/algorithm/sort.hpp> #include <range/v3/view.hpp> #include <array> #include <fstream> #include <iostream> #include <memory> #include <stdexcept> using namespace solidity; using namespace solidity::util; using namespace solidity::frontend; using namespace solidity::smtutil; CHCSmtLib2Interface::CHCSmtLib2Interface( std::map<h256, std::string> _queryResponses, ReadCallback::Callback _smtCallback, std::optional<unsigned> _queryTimeout ): CHCSolverInterface(_queryTimeout), m_queryResponses(std::move(_queryResponses)), m_smtCallback(std::move(_smtCallback)) { reset(); } void CHCSmtLib2Interface::reset() { m_unhandledQueries.clear(); m_commands.clear(); m_context.clear(); createHeader(); m_context.setTupleDeclarationCallback([&](TupleSort const& _tupleSort){ m_commands.declareTuple( _tupleSort.name, _tupleSort.members, _tupleSort.components | ranges::views::transform([&](SortPointer const& _sort){ return m_context.toSmtLibSort(_sort); }) | ranges::to<std::vector>() ); }); } void CHCSmtLib2Interface::registerRelation(Expression const& _expr) { smtAssert(_expr.sort); smtAssert(_expr.sort->kind == Kind::Function); if (m_context.isDeclared(_expr.name)) return; auto const& fSort = std::dynamic_pointer_cast<FunctionSort>(_expr.sort); smtAssert(fSort->codomain); auto domain = toSmtLibSort(fSort->domain); std::string codomain = toSmtLibSort(fSort->codomain); m_commands.declareFunction(_expr.name, domain, codomain); m_context.declare(_expr.name, _expr.sort); } void CHCSmtLib2Interface::addRule(Expression const& _expr, std::string const& /*_name*/) { m_commands.assertion("(forall" + forall(_expr) + '\n' + m_context.toSExpr(_expr) + ")\n"); } CHCSolverInterface::QueryResult CHCSmtLib2Interface::query(Expression const& _block) { std::string query = dumpQuery(_block); try { std::string response = querySolver(query); CheckResult result; // NOTE: Our internal semantics is UNSAT -> SAFE and SAT -> UNSAFE, which corresponds to usual SMT-based model checking // However, with CHC solvers, the meaning is flipped, UNSAT -> UNSAFE and SAT -> SAFE. // So we have to flip the answer. if (boost::starts_with(response, "sat")) { auto maybeInvariants = invariantsFromSolverResponse(response); return {CheckResult::UNSATISFIABLE, maybeInvariants.value_or(Expression(true)), {}}; } else if (boost::starts_with(response, "unsat")) result = CheckResult::SATISFIABLE; else if (boost::starts_with(response, "unknown")) result = CheckResult::UNKNOWN; else result = CheckResult::ERROR; return {result, Expression(true), {}}; } catch(smtutil::SMTSolverInteractionError const&) { return {CheckResult::ERROR, Expression(true), {}}; } } void CHCSmtLib2Interface::declareVariable(std::string const& _name, SortPointer const& _sort) { smtAssert(_sort); if (!m_context.isDeclared(_name)) m_context.declare(_name, _sort); } std::string CHCSmtLib2Interface::toSmtLibSort(SortPointer const& _sort) { return m_context.toSmtLibSort(_sort); } std::vector<std::string> CHCSmtLib2Interface::toSmtLibSort(std::vector<SortPointer> const& _sorts) { return applyMap(_sorts, [this](auto const& sort) { return toSmtLibSort(sort); }); } std::set<std::string> CHCSmtLib2Interface::collectVariableNames(Expression const& _expr) const { std::set<std::string> names; auto dfs = [&](Expression const& _current, auto _recurse) -> void { if (_current.arguments.empty()) { if (m_context.isDeclared(_current.name)) names.insert(_current.name); } else for (auto const& arg: _current.arguments) _recurse(arg, _recurse); }; dfs(_expr, dfs); return names; } std::string CHCSmtLib2Interface::forall(Expression const& _expr) { auto varNames = collectVariableNames(_expr); std::string vars("("); for (auto const& name: varNames) { auto sort = m_context.getDeclaredSort(name); if (sort->kind != Kind::Function) vars += " (" + name + " " + toSmtLibSort(sort) + ")"; } vars += ")"; return vars; } std::string CHCSmtLib2Interface::querySolver(std::string const& _input) { util::h256 inputHash = util::keccak256(_input); if (m_queryResponses.count(inputHash)) return m_queryResponses.at(inputHash); if (m_smtCallback) { auto result = m_smtCallback(ReadCallback::kindString(ReadCallback::Kind::SMTQuery), _input); if (result.success) return result.responseOrErrorMessage; } m_unhandledQueries.push_back(_input); return "unknown\n"; } std::string CHCSmtLib2Interface::dumpQuery(Expression const& _expr) { return m_commands.toString() + createQueryAssertion(_expr.name) + '\n' + "(check-sat)" + '\n'; } void CHCSmtLib2Interface::createHeader() { if (m_queryTimeout) m_commands.setOption("timeout", std::to_string(*m_queryTimeout)); m_commands.setLogic("HORN"); } std::string CHCSmtLib2Interface::createQueryAssertion(std::string _name) { return "(assert\n(forall ((UNUSED Bool))\n(=> " + std::move(_name) + " false)))"; } namespace { bool isNumber(std::string const& _expr) { return ranges::all_of(_expr, [](char c) { return isDigit(c) || c == '.'; }); } bool isBitVectorHexConstant(std::string const& _string) { if (_string.substr(0, 2) != "#x") return false; if (_string.find_first_not_of("0123456789abcdefABCDEF", 2) != std::string::npos) return false; return true; } bool isBitVectorConstant(std::string const& _string) { if (_string.substr(0, 2) != "#b") return false; if (_string.find_first_not_of("01", 2) != std::string::npos) return false; return true; } } void CHCSmtLib2Interface::ScopedParser::addVariableDeclaration(std::string _name, solidity::smtutil::SortPointer _sort) { m_localVariables.emplace(std::move(_name), std::move(_sort)); } std::optional<SortPointer> CHCSmtLib2Interface::ScopedParser::lookupKnownTupleSort(std::string const& _name) const { return m_context.getTupleType(_name); } SortPointer CHCSmtLib2Interface::ScopedParser::toSort(SMTLib2Expression const& _expr) { if (isAtom(_expr)) { auto const& name = asAtom(_expr); if (name == "Int") return SortProvider::sintSort; if (name == "Bool") return SortProvider::boolSort; auto tupleSort = lookupKnownTupleSort(name); if (tupleSort) return tupleSort.value(); } else { auto const& args = asSubExpressions(_expr); if (asAtom(args[0]) == "Array") { smtSolverInteractionRequire(args.size() == 3, "Wrong format of Array sort in solver's response"); auto domainSort = toSort(args[1]); auto codomainSort = toSort(args[2]); return std::make_shared<ArraySort>(std::move(domainSort), std::move(codomainSort)); } if (args.size() == 3 && isAtom(args[0]) && asAtom(args[0]) == "_" && isAtom(args[1]) && asAtom(args[1]) == "int2bv") return std::make_shared<BitVectorSort>(std::stoul(asAtom(args[2]))); } smtSolverInteractionRequire(false, "Unknown sort encountered"); } smtutil::Expression CHCSmtLib2Interface::ScopedParser::parseQuantifier( std::string const& _quantifierName, std::vector<SMTLib2Expression> const& _varList, SMTLib2Expression const& _coreExpression) { std::vector<std::pair<std::string, SortPointer>> boundVariables; for (auto const& sortedVar: _varList) { smtSolverInteractionRequire(!isAtom(sortedVar), "Wrong format of quantified expression in solver's response"); auto varSortPair = asSubExpressions(sortedVar); smtSolverInteractionRequire(varSortPair.size() == 2, "Wrong format of quantified expression in solver's response"); boundVariables.emplace_back(asAtom(varSortPair[0]), toSort(varSortPair[1])); } for (auto const& [var, sort]: boundVariables) { smtSolverInteractionRequire(m_localVariables.count(var) == 0, "Quantifying over previously encountered variable"); // TODO: deal with shadowing? m_localVariables.emplace(var, sort); } auto core = toSMTUtilExpression(_coreExpression); for (auto const& [var, sort]: boundVariables) { smtSolverInteractionRequire(m_localVariables.count(var) != 0, "Error in processing quantified expression"); m_localVariables.erase(var); } return Expression(_quantifierName, {core}, SortProvider::boolSort); // TODO: what about the bound variables? } smtutil::Expression CHCSmtLib2Interface::ScopedParser::toSMTUtilExpression(SMTLib2Expression const& _expr) { return std::visit( GenericVisitor{ [&](std::string const& _atom) { if (_atom == "true" || _atom == "false") return smtutil::Expression(_atom == "true"); else if (isNumber(_atom)) return smtutil::Expression(_atom, {}, SortProvider::sintSort); else if (isBitVectorHexConstant(_atom)) return smtutil::Expression(_atom, {}, std::make_shared<BitVectorSort>((_atom.size() - 2) * 4)); else if (isBitVectorConstant(_atom)) return smtutil::Expression(_atom, {}, std::make_shared<BitVectorSort>(_atom.size() - 2)); else if (auto it = m_localVariables.find(_atom); it != m_localVariables.end()) return smtutil::Expression(_atom, {}, it->second); else if (m_context.isDeclared(_atom)) return smtutil::Expression(_atom, {}, m_context.getDeclaredSort(_atom)); else if (auto maybeTupleType = m_context.getTupleType(_atom); maybeTupleType.has_value()) { // 0-ary tuple type, can happen return smtutil::Expression(_atom, {}, std::make_shared<TupleSort>(_atom, std::vector<std::string>{}, std::vector<SortPointer>{})); } else smtSolverInteractionRequire(false, "Unhandled atomic SMT expression"); }, [&](std::vector<SMTLib2Expression> const& _subExpr) { SortPointer sort; std::vector<smtutil::Expression> arguments; if (isAtom(_subExpr.front())) { std::string const& op = asAtom(_subExpr.front()); if (op == "!") { // named term, we ignore the name smtSolverInteractionRequire(_subExpr.size() > 2, "Wrong format of named SMT-LIB term"); return toSMTUtilExpression(_subExpr[1]); } if (op == "exists" || op == "forall") { smtSolverInteractionRequire(_subExpr.size() == 3, "Wrong format of quantified expression"); smtSolverInteractionRequire(!isAtom(_subExpr[1]), "Wrong format of quantified expression"); return parseQuantifier(op, asSubExpressions(_subExpr[1]), _subExpr[2]); } for (size_t i = 1; i < _subExpr.size(); i++) arguments.emplace_back(toSMTUtilExpression(_subExpr[i])); if (auto tupleSort = lookupKnownTupleSort(op); tupleSort) { auto sortSort = std::make_shared<SortSort>(tupleSort.value()); return Expression::tuple_constructor(Expression(sortSort), arguments); } if (m_context.isDeclared(op)) return smtutil::Expression(op, std::move(arguments), m_context.getDeclaredSort(op)); if (auto maybeTupleAccessor = m_context.getTupleAccessor(op); maybeTupleAccessor.has_value()) { auto accessor = maybeTupleAccessor.value(); return smtutil::Expression("dt_accessor_" + accessor.first, std::move(arguments), accessor.second); } else { std::set<std::string> boolOperators{"and", "or", "not", "=", "<", ">", "<=", ">=", "=>"}; sort = contains(boolOperators, op) ? SortProvider::boolSort : arguments.back().sort; return smtutil::Expression(op, std::move(arguments), std::move(sort)); } smtSolverInteractionRequire(false, "Unhandled case in expression conversion"); } else { // check for const array if (_subExpr.size() == 2 and !isAtom(_subExpr[0])) { auto const& typeArgs = asSubExpressions(_subExpr.front()); if (typeArgs.size() == 3 && typeArgs[0].toString() == "as" && typeArgs[1].toString() == "const") { auto arraySort = toSort(typeArgs[2]); auto sortSort = std::make_shared<SortSort>(arraySort); return smtutil::Expression:: const_array(Expression(sortSort), toSMTUtilExpression(_subExpr[1])); } if (typeArgs.size() == 3 && typeArgs[0].toString() == "_" && typeArgs[1].toString() == "int2bv") { auto bvSort = std::dynamic_pointer_cast<BitVectorSort>(toSort(_subExpr[0])); smtSolverInteractionRequire(bvSort, "Invalid format of bitvector sort"); return smtutil::Expression::int2bv(toSMTUtilExpression(_subExpr[1]), bvSort->size); } if (typeArgs.size() == 4 && typeArgs[0].toString() == "_" && typeArgs[1].toString() == "extract") return smtutil::Expression( "extract", {toSMTUtilExpression(typeArgs[2]), toSMTUtilExpression(typeArgs[3])}, SortProvider::bitVectorSort // TODO: Compute bit size properly? ); } smtSolverInteractionRequire(false, "Unhandled case in expression conversion"); } } }, _expr.data ); } std::optional<smtutil::Expression> CHCSmtLib2Interface::invariantsFromSolverResponse(std::string const& _response) const { std::stringstream ss(_response); std::string answer; ss >> answer; smtSolverInteractionRequire(answer == "sat", "CHC model can only be extracted from sat answer"); SMTLib2Parser parser(ss); if (parser.isEOF()) return {}; std::vector<SMTLib2Expression> parsedOutput; try { while (!parser.isEOF()) parsedOutput.push_back(parser.parseExpression()); } catch(SMTLib2Parser::ParsingException&) { smtSolverInteractionRequire(false, "Error during parsing CHC model"); } smtSolverInteractionRequire(parser.isEOF(), "Error during parsing CHC model"); smtSolverInteractionRequire(!parsedOutput.empty(), "Error during parsing CHC model"); auto& commands = parsedOutput.size() == 1 ? asSubExpressions(parsedOutput[0]) : parsedOutput; std::vector<Expression> definitions; for (auto& command: commands) { auto& args = asSubExpressions(command); smtSolverInteractionRequire(args.size() == 5, "Invalid format of CHC model"); // args[0] = "define-fun" // args[1] = predicate name // args[2] = formal arguments of the predicate // args[3] = return sort // args[4] = body of the predicate's interpretation smtSolverInteractionRequire(isAtom(args[0]) && asAtom(args[0]) == "define-fun", "Invalid format of CHC model"); smtSolverInteractionRequire(isAtom(args[1]), "Invalid format of CHC model"); smtSolverInteractionRequire(!isAtom(args[2]), "Invalid format of CHC model"); smtSolverInteractionRequire(isAtom(args[3]) && asAtom(args[3]) == "Bool", "Invalid format of CHC model"); auto& interpretation = args[4]; inlineLetExpressions(interpretation); ScopedParser scopedParser(m_context); auto const& formalArguments = asSubExpressions(args[2]); std::vector<Expression> predicateArgs; for (auto const& formalArgument: formalArguments) { smtSolverInteractionRequire(!isAtom(formalArgument), "Invalid format of CHC model"); auto const& nameSortPair = asSubExpressions(formalArgument); smtSolverInteractionRequire(nameSortPair.size() == 2, "Invalid format of CHC model"); smtSolverInteractionRequire(isAtom(nameSortPair[0]), "Invalid format of CHC model"); SortPointer varSort = scopedParser.toSort(nameSortPair[1]); scopedParser.addVariableDeclaration(asAtom(nameSortPair[0]), varSort); // FIXME: Why Expression here? Expression arg = scopedParser.toSMTUtilExpression(nameSortPair[0]); predicateArgs.push_back(arg); } auto parsedInterpretation = scopedParser.toSMTUtilExpression(interpretation); // Hack to make invariants more stable across operating systems if (parsedInterpretation.name == "and" || parsedInterpretation.name == "or") ranges::sort(parsedInterpretation.arguments, [](Expression const& first, Expression const& second) { return first.name < second.name; }); Expression predicate(asAtom(args[1]), predicateArgs, SortProvider::boolSort); definitions.push_back(predicate == parsedInterpretation); } return Expression::mkAnd(std::move(definitions)); } namespace { struct LetBindings { using BindingRecord = std::vector<SMTLib2Expression>; std::unordered_map<std::string, BindingRecord> bindings; std::vector<std::string> varNames; std::vector<std::size_t> scopeBounds; bool has(std::string const& varName) { return bindings.find(varName) != bindings.end(); } SMTLib2Expression& operator[](std::string const& varName) { auto it = bindings.find(varName); smtSolverInteractionRequire(it != bindings.end(), "Error in processing let bindings"); smtSolverInteractionRequire(!it->second.empty(), "Error in processing let bindings"); return it->second.back(); } void pushScope() { scopeBounds.push_back(varNames.size()); } void popScope() { smtSolverInteractionRequire(!scopeBounds.empty(), "Error in processing let bindings"); auto bound = scopeBounds.back(); while (varNames.size() > bound) { auto const& varName = varNames.back(); auto it = bindings.find(varName); smtSolverInteractionRequire(it != bindings.end(), "Error in processing let bindings"); auto& record = it->second; record.pop_back(); if (record.empty()) bindings.erase(it); varNames.pop_back(); } scopeBounds.pop_back(); } void addBinding(std::string name, SMTLib2Expression expression) { auto it = bindings.find(name); if (it == bindings.end()) bindings.insert({name, {std::move(expression)}}); else it->second.push_back(std::move(expression)); varNames.push_back(std::move(name)); } }; void inlineLetExpressions(SMTLib2Expression& _expr, LetBindings& _bindings) { if (isAtom(_expr)) { auto const& atom = asAtom(_expr); if (_bindings.has(atom)) _expr = _bindings[atom]; return; } auto& subexprs = asSubExpressions(_expr); smtSolverInteractionRequire(!subexprs.empty(), "Invalid let expression"); auto const& first = subexprs.at(0); if (isAtom(first) && asAtom(first) == "let") { smtSolverInteractionRequire(subexprs.size() == 3, "Invalid let expression"); smtSolverInteractionRequire(!isAtom(subexprs[1]), "Invalid let expression"); auto& bindingExpressions = asSubExpressions(subexprs[1]); // process new bindings std::vector<std::pair<std::string, SMTLib2Expression>> newBindings; for (auto& binding: bindingExpressions) { smtSolverInteractionRequire(!isAtom(binding), "Invalid let expression"); auto& bindingPair = asSubExpressions(binding); smtSolverInteractionRequire(bindingPair.size() == 2, "Invalid let expression"); smtSolverInteractionRequire(isAtom(bindingPair.at(0)), "Invalid let expression"); inlineLetExpressions(bindingPair.at(1), _bindings); newBindings.emplace_back(asAtom(bindingPair.at(0)), bindingPair.at(1)); } _bindings.pushScope(); for (auto&& [name, expr]: newBindings) _bindings.addBinding(std::move(name), std::move(expr)); newBindings.clear(); // get new subexpression inlineLetExpressions(subexprs.at(2), _bindings); // remove the new bindings _bindings.popScope(); // update the expression auto tmp = std::move(subexprs.at(2)); _expr = std::move(tmp); return; } else if (isAtom(first) && (asAtom(first) == "forall" || asAtom(first) == "exists")) { // A little hack to ensure quantified variables are not substituted because of some outer let definition: // We define the current binding of the variable to itself, before we recurse in to subterm smtSolverInteractionRequire(subexprs.size() == 3, "Invalid let expression"); _bindings.pushScope(); for (auto const& sortedVar: asSubExpressions(subexprs.at(1))) { auto const& varNameExpr = asSubExpressions(sortedVar).at(0); _bindings.addBinding(asAtom(varNameExpr), varNameExpr); } inlineLetExpressions(subexprs.at(2), _bindings); _bindings.popScope(); return; } // not a let expression, just process all arguments recursively for (auto& subexpr: subexprs) inlineLetExpressions(subexpr, _bindings); } } void CHCSmtLib2Interface::inlineLetExpressions(SMTLib2Expression& expr) { LetBindings bindings; ::inlineLetExpressions(expr, bindings); }
20,771
C++
.cpp
539
35.41744
146
0.726484
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,279
SMTLib2Parser.cpp
ethereum_solidity/libsmtutil/SMTLib2Parser.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libsmtutil/SMTLib2Parser.h> #include <liblangutil/Common.h> #include <libsolutil/Visitor.h> #include <libsolutil/StringUtils.h> using namespace solidity::langutil; using namespace solidity::smtutil; std::string SMTLib2Expression::toString() const { return std::visit(solidity::util::GenericVisitor{ [](std::string const& _sv) { return _sv; }, [](std::vector<SMTLib2Expression> const& _subExpr) { std::vector<std::string> formatted; for (auto const& item: _subExpr) formatted.emplace_back(item.toString()); return "(" + solidity::util::joinHumanReadable(formatted, " ") + ")"; } }, data); } SMTLib2Expression SMTLib2Parser::parseExpression() { skipWhitespace(); if (token() == '(') { advance(); skipWhitespace(); std::vector<SMTLib2Expression> subExpressions; while (token() != 0 && token() != ')') { subExpressions.emplace_back(parseExpression()); skipWhitespace(); } if (token() != ')') throw ParsingException{}; // Simulate whitespace because we do not want to read the next token since it might block. m_token = ' '; return {std::move(subExpressions)}; } else return {parseToken()}; } std::string SMTLib2Parser::parseToken() { std::string result; skipWhitespace(); bool isPipe = token() == '|'; if (isPipe) advance(); while (token() != 0) { char c = token(); if (isPipe && c == '|') { advance(); break; } else if (!isPipe && (isWhiteSpace(c) || c == '(' || c == ')')) break; result.push_back(c); advance(); } return result; } void SMTLib2Parser::advance() { if (!m_input.good()) throw ParsingException{}; m_token = static_cast<char>(m_input.get()); if (token() == ';') while (token() != '\n' && token() != 0) m_token = static_cast<char>(m_input.get()); } void SMTLib2Parser::skipWhitespace() { while (isWhiteSpace(token())) advance(); }
2,553
C++
.cpp
83
28.168675
92
0.697883
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,281
Disassemble.cpp
ethereum_solidity/libevmasm/Disassemble.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libevmasm/Disassemble.h> #include <libsolutil/Common.h> #include <libsolutil/CommonIO.h> #include <functional> using namespace solidity; using namespace solidity::util; using namespace solidity::evmasm; void solidity::evmasm::eachInstruction( bytes const& _mem, langutil::EVMVersion _evmVersion, std::function<void(Instruction,u256 const&)> const& _onInstruction ) { for (auto it = _mem.begin(); it < _mem.end(); ++it) { Instruction const instr{*it}; int additional = 0; if (isValidInstruction(instr)) additional = instructionInfo(instr, _evmVersion).additional; u256 data{}; // fill the data with the additional data bytes from the instruction stream while (additional > 0 && std::next(it) < _mem.end()) { data <<= 8; data |= *++it; --additional; } // pad the remaining number of additional octets with zeros data <<= 8 * additional; _onInstruction(instr, data); } } std::string solidity::evmasm::disassemble(bytes const& _mem, langutil::EVMVersion _evmVersion, std::string const& _delimiter) { std::stringstream ret; eachInstruction(_mem, _evmVersion, [&](Instruction _instr, u256 const& _data) { if (!isValidInstruction(_instr)) ret << "0x" << std::uppercase << std::hex << static_cast<int>(_instr) << _delimiter; else { InstructionInfo info = instructionInfo(_instr, _evmVersion); ret << info.name; if (info.additional) ret << " 0x" << std::uppercase << std::hex << _data; ret << _delimiter; } }); return ret.str(); }
2,198
C++
.cpp
63
32.380952
125
0.729972
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
3,283
Inliner.cpp
ethereum_solidity/libevmasm/Inliner.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 /** * @file Inliner.cpp * Inlines small code snippets by replacing JUMP with a copy of the code jumped to. */ #include <libevmasm/Inliner.h> #include <libevmasm/AssemblyItem.h> #include <libevmasm/GasMeter.h> #include <libevmasm/KnownState.h> #include <libevmasm/SemanticInformation.h> #include <libsolutil/CommonData.h> #include <range/v3/numeric/accumulate.hpp> #include <range/v3/view/drop_last.hpp> #include <range/v3/view/enumerate.hpp> #include <range/v3/view/slice.hpp> #include <range/v3/view/transform.hpp> #include <optional> #include <limits> using namespace solidity; using namespace solidity::evmasm; namespace { /// @returns an estimation of the runtime gas cost of the AssemblyItems in @a _itemRange. template<typename RangeType> u256 executionCost(RangeType const& _itemRange, langutil::EVMVersion _evmVersion) { GasMeter gasMeter{std::make_shared<KnownState>(), _evmVersion}; auto gasConsumption = ranges::accumulate(_itemRange | ranges::views::transform( [&gasMeter](auto const& _item) { return gasMeter.estimateMax(_item, false); } ), GasMeter::GasConsumption()); if (gasConsumption.isInfinite) return std::numeric_limits<u256>::max(); else return gasConsumption.value; } /// @returns an estimation of the code size in bytes needed for the AssemblyItems in @a _itemRange. template<typename RangeType> uint64_t codeSize(RangeType const& _itemRange, langutil::EVMVersion _evmVersion) { return ranges::accumulate(_itemRange | ranges::views::transform( [&](auto const& _item) { return _item.bytesRequired(2, _evmVersion, Precision::Approximate); } ), 0u); } /// @returns the tag id, if @a _item is a PushTag or Tag into the current subassembly, std::nullopt otherwise. std::optional<size_t> getLocalTag(AssemblyItem const& _item) { if (_item.type() != PushTag && _item.type() != Tag) return std::nullopt; auto [subId, tag] = _item.splitForeignPushTag(); if (subId != std::numeric_limits<size_t>::max()) return std::nullopt; return tag; } } bool Inliner::isInlineCandidate(size_t _tag, ranges::span<AssemblyItem const> _items) const { assertThrow(_items.size() > 0, OptimizerException, ""); if (_items.back().type() != Operation) return false; if ( _items.back() != Instruction::JUMP && !SemanticInformation::terminatesControlFlow(_items.back().instruction()) ) return false; // Never inline tags that reference themselves. for (AssemblyItem const& item: _items) if (item.type() == PushTag) if (getLocalTag(item) == _tag) return false; return true; } std::map<size_t, Inliner::InlinableBlock> Inliner::determineInlinableBlocks(AssemblyItems const& _items) const { std::map<size_t, ranges::span<AssemblyItem const>> inlinableBlockItems; std::map<size_t, uint64_t> numPushTags; std::optional<size_t> lastTag; for (auto&& [index, item]: _items | ranges::views::enumerate) { // The number of PushTags approximates the number of calls to a block. if (item.type() == PushTag) if (std::optional<size_t> tag = getLocalTag(item)) ++numPushTags[*tag]; // We can only inline blocks with straight control flow that end in a jump. // Using breaksCSEAnalysisBlock will hopefully allow the return jump to be optimized after inlining. if (lastTag && SemanticInformation::breaksCSEAnalysisBlock(item, false)) { ranges::span<AssemblyItem const> block = _items | ranges::views::slice(*lastTag + 1, index + 1); if (std::optional<size_t> tag = getLocalTag(_items[*lastTag])) if (isInlineCandidate(*tag, block)) inlinableBlockItems[*tag] = block; lastTag.reset(); } if (item.type() == Tag) { assertThrow(getLocalTag(item), OptimizerException, ""); lastTag = index; } } // Store the number of PushTags alongside the assembly items and discard tags that are never pushed. std::map<size_t, InlinableBlock> result; for (auto&& [tag, items]: inlinableBlockItems) if (uint64_t const* numPushes = util::valueOrNullptr(numPushTags, tag)) result.emplace(tag, InlinableBlock{items, *numPushes}); return result; } bool Inliner::shouldInlineFullFunctionBody(size_t _tag, ranges::span<AssemblyItem const> _block, uint64_t _pushTagCount) const { // Accumulate size of the inline candidate block in bytes (without the return jump). uint64_t functionBodySize = codeSize(ranges::views::drop_last(_block, 1), m_evmVersion); // Use the number of push tags as approximation of the average number of calls to the function per run. uint64_t numberOfCalls = _pushTagCount; // Also use the number of push tags as approximation of the number of call sites to the function. uint64_t numberOfCallSites = _pushTagCount; static AssemblyItems const uninlinedCallSitePattern = { AssemblyItem{PushTag}, AssemblyItem{PushTag}, AssemblyItem{Instruction::JUMP}, AssemblyItem{Tag} }; static AssemblyItems const uninlinedFunctionPattern = { AssemblyItem{Tag}, // Actual function body of size functionBodySize. Handled separately below. AssemblyItem{Instruction::JUMP} }; // Both the call site and jump site pattern is executed for each call. // Since the function body has to be executed equally often both with and without inlining, // it can be ignored. bigint uninlinedExecutionCost = numberOfCalls * ( executionCost(uninlinedCallSitePattern, m_evmVersion) + executionCost(uninlinedFunctionPattern, m_evmVersion) ); // Each call site deposits the call site pattern, whereas the jump site pattern and the function itself are deposited once. bigint uninlinedDepositCost = GasMeter::dataGas( numberOfCallSites * codeSize(uninlinedCallSitePattern, m_evmVersion) + codeSize(uninlinedFunctionPattern, m_evmVersion) + functionBodySize, m_isCreation, m_evmVersion ); // When inlining the execution cost beyond the actual function execution is zero, // but for each call site a copy of the function is deposited. bigint inlinedDepositCost = GasMeter::dataGas( numberOfCallSites * functionBodySize, m_isCreation, m_evmVersion ); // If the block is referenced from outside the current subassembly, the original function cannot be removed. // Note that the function also cannot always be removed, if it is not referenced from outside, but in that case // the heuristics is optimistic. if (m_tagsReferencedFromOutside.count(_tag)) inlinedDepositCost += GasMeter::dataGas( codeSize(uninlinedFunctionPattern, m_evmVersion) + functionBodySize, m_isCreation, m_evmVersion ); // If the estimated runtime cost over the lifetime of the contract plus the deposit cost in the uninlined case // exceed the inlined deposit costs, it is beneficial to inline. if (bigint(m_runs) * uninlinedExecutionCost + uninlinedDepositCost > inlinedDepositCost) return true; return false; } std::optional<AssemblyItem> Inliner::shouldInline(size_t _tag, AssemblyItem const& _jump, InlinableBlock const& _block) const { assertThrow(_jump == Instruction::JUMP, OptimizerException, ""); AssemblyItem blockExit = _block.items.back(); if ( _jump.getJumpType() == AssemblyItem::JumpType::IntoFunction && blockExit == Instruction::JUMP && blockExit.getJumpType() == AssemblyItem::JumpType::OutOfFunction && shouldInlineFullFunctionBody(_tag, _block.items, _block.pushTagCount) ) { blockExit.setJumpType(AssemblyItem::JumpType::Ordinary); return blockExit; } // Inline small blocks, if the jump to it is ordinary or the blockExit is a terminating instruction. if ( _jump.getJumpType() == AssemblyItem::JumpType::Ordinary || SemanticInformation::terminatesControlFlow(blockExit.instruction()) ) { static AssemblyItems const jumpPattern = { AssemblyItem{PushTag}, AssemblyItem{Instruction::JUMP}, }; if ( GasMeter::dataGas(codeSize(_block.items, m_evmVersion), m_isCreation, m_evmVersion) <= GasMeter::dataGas(codeSize(jumpPattern, m_evmVersion), m_isCreation, m_evmVersion) ) return blockExit; } return std::nullopt; } void Inliner::optimise() { std::map<size_t, InlinableBlock> inlinableBlocks = determineInlinableBlocks(m_items); if (inlinableBlocks.empty()) return; AssemblyItems newItems; for (auto it = m_items.begin(); it != m_items.end(); ++it) { AssemblyItem const& item = *it; if (next(it) != m_items.end()) { AssemblyItem const& nextItem = *next(it); if (item.type() == PushTag && nextItem == Instruction::JUMP) { if (std::optional<size_t> tag = getLocalTag(item)) if (auto* inlinableBlock = util::valueOrNullptr(inlinableBlocks, *tag)) if (auto exitItem = shouldInline(*tag, nextItem, *inlinableBlock)) { newItems += inlinableBlock->items | ranges::views::drop_last(1); newItems.emplace_back(std::move(*exitItem)); // We are removing one push tag to the block we inline. --inlinableBlock->pushTagCount; // We might increase the number of push tags to other blocks. for (AssemblyItem const& inlinedItem: inlinableBlock->items) if (inlinedItem.type() == PushTag) if (std::optional<size_t> duplicatedTag = getLocalTag(inlinedItem)) if (auto* block = util::valueOrNullptr(inlinableBlocks, *duplicatedTag)) ++block->pushTagCount; // Skip the original jump to the inlined tag and continue. ++it; continue; } } } newItems.emplace_back(item); } m_items = std::move(newItems); }
10,015
C++
.cpp
244
38.188525
126
0.75018
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
3,287
EVMAssemblyStack.cpp
ethereum_solidity/libevmasm/EVMAssemblyStack.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libevmasm/EVMAssemblyStack.h> #include <libsolutil/JSON.h> #include <liblangutil/Exceptions.h> #include <libsolidity/codegen/CompilerContext.h> #include <range/v3/view/enumerate.hpp> #include <range/v3/view/transform.hpp> #include <tuple> using namespace solidity::util; using namespace solidity::langutil; using namespace solidity::frontend; namespace solidity::evmasm { void EVMAssemblyStack::parseAndAnalyze(std::string const& _sourceName, std::string const& _source) { Json assemblyJson; solRequire(jsonParseStrict(_source, assemblyJson), AssemblyImportException, "Could not parse JSON file."); analyze(_sourceName, assemblyJson); } void EVMAssemblyStack::analyze(std::string const& _sourceName, Json const& _assemblyJson) { solAssert(!m_evmAssembly); m_name = _sourceName; std::tie(m_evmAssembly, m_sourceList) = evmasm::Assembly::fromJSON(_assemblyJson, {}, 0, m_eofVersion); solRequire(m_evmAssembly != nullptr, AssemblyImportException, "Could not create evm assembly object."); } void EVMAssemblyStack::assemble() { solAssert(m_evmAssembly); solAssert(m_evmAssembly->isCreation()); solAssert(!m_evmRuntimeAssembly); m_object = m_evmAssembly->assemble(); // TODO: Check for EOF solAssert(m_evmAssembly->codeSections().size() == 1); m_sourceMapping = AssemblyItem::computeSourceMapping(m_evmAssembly->codeSections().front().items, sourceIndices()); if (m_evmAssembly->numSubs() > 0) { m_evmRuntimeAssembly = std::make_shared<evmasm::Assembly>(m_evmAssembly->sub(0)); solAssert(m_evmRuntimeAssembly && !m_evmRuntimeAssembly->isCreation()); // TODO: Check for EOF solAssert(m_evmRuntimeAssembly->codeSections().size() == 1); m_runtimeSourceMapping = AssemblyItem::computeSourceMapping(m_evmRuntimeAssembly->codeSections().front().items, sourceIndices()); m_runtimeObject = m_evmRuntimeAssembly->assemble(); } } LinkerObject const& EVMAssemblyStack::object(std::string const& _contractName) const { solAssert(_contractName == m_name); return m_object; } LinkerObject const& EVMAssemblyStack::runtimeObject(std::string const& _contractName) const { solAssert(_contractName == m_name); return m_runtimeObject; } std::map<std::string, unsigned> EVMAssemblyStack::sourceIndices() const { solAssert(m_evmAssembly); return m_sourceList | ranges::views::enumerate | ranges::views::transform([](auto const& _source) { return std::make_pair(_source.second, _source.first); }) | ranges::to<std::map<std::string, unsigned>>; } std::string const* EVMAssemblyStack::sourceMapping(std::string const& _contractName) const { solAssert(_contractName == m_name); return &m_sourceMapping; } std::string const* EVMAssemblyStack::runtimeSourceMapping(std::string const& _contractName) const { solAssert(_contractName == m_name); return &m_runtimeSourceMapping; } Json EVMAssemblyStack::assemblyJSON(std::string const& _contractName) const { solAssert(_contractName == m_name); solAssert(m_evmAssembly); return m_evmAssembly->assemblyJSON(sourceIndices()); } std::string EVMAssemblyStack::assemblyString(std::string const& _contractName, StringMap const& _sourceCodes) const { solAssert(_contractName == m_name); solAssert(m_evmAssembly); return m_evmAssembly->assemblyString(m_debugInfoSelection, _sourceCodes); } std::string const EVMAssemblyStack::filesystemFriendlyName(std::string const& _contractName) const { solAssert(_contractName == m_name); return m_name; } std::vector<std::string> EVMAssemblyStack::sourceNames() const { return m_sourceList; } } // namespace solidity::evmasm
4,239
C++
.cpp
108
37.435185
131
0.782376
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,288
PeepholeOptimiser.cpp
ethereum_solidity/libevmasm/PeepholeOptimiser.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 /** * @file PeepholeOptimiser.cpp * Performs local optimising code changes to assembly. */ #include <libevmasm/PeepholeOptimiser.h> #include <libevmasm/AssemblyItem.h> #include <libevmasm/SemanticInformation.h> using namespace solidity; using namespace solidity::evmasm; // TODO: Extend this to use the tools from ExpressionClasses.cpp namespace { struct OptimiserState { AssemblyItems const& items; size_t i; std::back_insert_iterator<AssemblyItems> out; langutil::EVMVersion evmVersion = langutil::EVMVersion(); }; template<typename FunctionType> struct FunctionParameterCount; template<typename R, typename... Args> struct FunctionParameterCount<R(Args...)> { static constexpr auto value = sizeof...(Args); }; template <class Method> struct SimplePeepholeOptimizerMethod { template <size_t... Indices> static bool applyRule( AssemblyItems::const_iterator _in, std::back_insert_iterator<AssemblyItems> _out, std::index_sequence<Indices...> ) { return Method::applySimple(_in[Indices]..., _out); } static bool apply(OptimiserState& _state) { static constexpr size_t WindowSize = FunctionParameterCount<decltype(Method::applySimple)>::value - 1; if ( _state.i + WindowSize <= _state.items.size() && applyRule(_state.items.begin() + static_cast<ptrdiff_t>(_state.i), _state.out, std::make_index_sequence<WindowSize>{}) ) { _state.i += WindowSize; return true; } else return false; } }; struct Identity: SimplePeepholeOptimizerMethod<Identity> { static bool applySimple( AssemblyItem const& _item, std::back_insert_iterator<AssemblyItems> _out ) { *_out = _item; return true; } }; struct PushPop: SimplePeepholeOptimizerMethod<PushPop> { static bool applySimple( AssemblyItem const& _push, AssemblyItem const& _pop, std::back_insert_iterator<AssemblyItems> ) { auto t = _push.type(); return _pop == Instruction::POP && ( SemanticInformation::isDupInstruction(_push) || t == Push || t == PushTag || t == PushSub || t == PushSubSize || t == PushProgramSize || t == PushData || t == PushLibraryAddress ); } }; struct OpPop: SimplePeepholeOptimizerMethod<OpPop> { static bool applySimple( AssemblyItem const& _op, AssemblyItem const& _pop, std::back_insert_iterator<AssemblyItems> _out ) { if (_pop == Instruction::POP && _op.type() == Operation) { Instruction instr = _op.instruction(); if (instructionInfo(instr, langutil::EVMVersion()).ret == 1 && !instructionInfo(instr, langutil::EVMVersion()).sideEffects) { for (int j = 0; j < instructionInfo(instr, langutil::EVMVersion()).args; j++) *_out = {Instruction::POP, _op.debugData()}; return true; } } return false; } }; struct OpStop: SimplePeepholeOptimizerMethod<OpStop> { static bool applySimple( AssemblyItem const& _op, AssemblyItem const& _stop, std::back_insert_iterator<AssemblyItems> _out ) { if (_stop == Instruction::STOP) { if (_op.type() == Operation) { Instruction instr = _op.instruction(); if (!instructionInfo(instr, langutil::EVMVersion()).sideEffects) { *_out = {Instruction::STOP, _op.debugData()}; return true; } } else if (_op.type() == Push) { *_out = {Instruction::STOP, _op.debugData()}; return true; } } return false; } }; struct OpReturnRevert: SimplePeepholeOptimizerMethod<OpReturnRevert> { static bool applySimple( AssemblyItem const& _op, AssemblyItem const& _push, AssemblyItem const& _pushOrDup, AssemblyItem const& _returnRevert, std::back_insert_iterator<AssemblyItems> _out ) { if ( (_returnRevert == Instruction::RETURN || _returnRevert == Instruction::REVERT) && _push.type() == Push && (_pushOrDup.type() == Push || _pushOrDup == dupInstruction(1)) ) if ( (_op.type() == Operation && !instructionInfo(_op.instruction(), langutil::EVMVersion()).sideEffects) || _op.type() == Push ) { *_out = _push; *_out = _pushOrDup; *_out = _returnRevert; return true; } return false; } }; struct DoubleSwap: SimplePeepholeOptimizerMethod<DoubleSwap> { static size_t applySimple( AssemblyItem const& _s1, AssemblyItem const& _s2, std::back_insert_iterator<AssemblyItems> ) { return _s1 == _s2 && SemanticInformation::isSwapInstruction(_s1); } }; struct DoublePush { static bool apply(OptimiserState& _state) { size_t windowSize = 2; if (_state.i + windowSize > _state.items.size()) return false; auto push1 = _state.items.begin() + static_cast<ptrdiff_t>(_state.i); auto push2 = _state.items.begin() + static_cast<ptrdiff_t>(_state.i + 1); assertThrow(push1 != _state.items.end() && push2 != _state.items.end(), OptimizerException, ""); if ( push1->type() == Push && push2->type() == Push && push1->data() == push2->data() && (!_state.evmVersion.hasPush0() || push1->data() != 0) ) { *_state.out = *push1; *_state.out = {Instruction::DUP1, push2->debugData()}; _state.i += windowSize; return true; } else return false; } }; struct CommutativeSwap: SimplePeepholeOptimizerMethod<CommutativeSwap> { static bool applySimple( AssemblyItem const& _swap, AssemblyItem const& _op, std::back_insert_iterator<AssemblyItems> _out ) { // Remove SWAP1 if following instruction is commutative if ( _swap == Instruction::SWAP1 && SemanticInformation::isCommutativeOperation(_op) ) { *_out = _op; return true; } else return false; } }; struct SwapComparison: SimplePeepholeOptimizerMethod<SwapComparison> { static bool applySimple( AssemblyItem const& _swap, AssemblyItem const& _op, std::back_insert_iterator<AssemblyItems> _out ) { static std::map<Instruction, Instruction> const swappableOps{ { Instruction::LT, Instruction::GT }, { Instruction::GT, Instruction::LT }, { Instruction::SLT, Instruction::SGT }, { Instruction::SGT, Instruction::SLT } }; if ( _swap == Instruction::SWAP1 && _op.type() == Operation && swappableOps.count(_op.instruction()) ) { *_out = swappableOps.at(_op.instruction()); return true; } else return false; } }; /// Remove swapN after dupN struct DupSwap: SimplePeepholeOptimizerMethod<DupSwap> { static size_t applySimple( AssemblyItem const& _dupN, AssemblyItem const& _swapN, std::back_insert_iterator<AssemblyItems> _out ) { if ( SemanticInformation::isDupInstruction(_dupN) && SemanticInformation::isSwapInstruction(_swapN) && getDupNumber(_dupN.instruction()) == getSwapNumber(_swapN.instruction()) ) { *_out = _dupN; return true; } else return false; } }; struct IsZeroIsZeroJumpI: SimplePeepholeOptimizerMethod<IsZeroIsZeroJumpI> { static size_t applySimple( AssemblyItem const& _iszero1, AssemblyItem const& _iszero2, AssemblyItem const& _pushTag, AssemblyItem const& _jumpi, std::back_insert_iterator<AssemblyItems> _out ) { if ( _iszero1 == Instruction::ISZERO && _iszero2 == Instruction::ISZERO && _pushTag.type() == PushTag && _jumpi == Instruction::JUMPI ) { *_out = _pushTag; *_out = _jumpi; return true; } else return false; } }; struct EqIsZeroJumpI: SimplePeepholeOptimizerMethod<EqIsZeroJumpI> { static size_t applySimple( AssemblyItem const& _eq, AssemblyItem const& _iszero, AssemblyItem const& _pushTag, AssemblyItem const& _jumpi, std::back_insert_iterator<AssemblyItems> _out ) { if ( _eq == Instruction::EQ && _iszero == Instruction::ISZERO && _pushTag.type() == PushTag && _jumpi == Instruction::JUMPI ) { *_out = AssemblyItem(Instruction::SUB, _eq.debugData()); *_out = _pushTag; *_out = _jumpi; return true; } else return false; } }; // push_tag_1 jumpi push_tag_2 jump tag_1: -> iszero push_tag_2 jumpi tag_1: struct DoubleJump: SimplePeepholeOptimizerMethod<DoubleJump> { static size_t applySimple( AssemblyItem const& _pushTag1, AssemblyItem const& _jumpi, AssemblyItem const& _pushTag2, AssemblyItem const& _jump, AssemblyItem const& _tag1, std::back_insert_iterator<AssemblyItems> _out ) { if ( _pushTag1.type() == PushTag && _jumpi == Instruction::JUMPI && _pushTag2.type() == PushTag && _jump == Instruction::JUMP && _tag1.type() == Tag && _pushTag1.data() == _tag1.data() ) { *_out = AssemblyItem(Instruction::ISZERO, _jumpi.debugData()); *_out = _pushTag2; *_out = _jumpi; *_out = _tag1; return true; } else return false; } }; struct JumpToNext: SimplePeepholeOptimizerMethod<JumpToNext> { static size_t applySimple( AssemblyItem const& _pushTag, AssemblyItem const& _jump, AssemblyItem const& _tag, std::back_insert_iterator<AssemblyItems> _out ) { if ( _pushTag.type() == PushTag && (_jump == Instruction::JUMP || _jump == Instruction::JUMPI) && _tag.type() == Tag && _pushTag.data() == _tag.data() ) { if (_jump == Instruction::JUMPI) *_out = AssemblyItem(Instruction::POP, _jump.debugData()); *_out = _tag; return true; } else return false; } }; struct TagConjunctions: SimplePeepholeOptimizerMethod<TagConjunctions> { static bool applySimple( AssemblyItem const& _pushTag, AssemblyItem const& _pushConstant, AssemblyItem const& _and, std::back_insert_iterator<AssemblyItems> _out ) { if (_and != Instruction::AND) return false; if ( _pushTag.type() == PushTag && _pushConstant.type() == Push && (_pushConstant.data() & u256(0xFFFFFFFF)) == u256(0xFFFFFFFF) ) { *_out = _pushTag; return true; } else if ( // tag and constant are swapped _pushConstant.type() == PushTag && _pushTag.type() == Push && (_pushTag.data() & u256(0xFFFFFFFF)) == u256(0xFFFFFFFF) ) { *_out = _pushConstant; return true; } else return false; } }; struct TruthyAnd: SimplePeepholeOptimizerMethod<TruthyAnd> { static bool applySimple( AssemblyItem const& _push, AssemblyItem const& _not, AssemblyItem const& _and, std::back_insert_iterator<AssemblyItems> ) { return ( _push.type() == Push && _push.data() == 0 && _not == Instruction::NOT && _and == Instruction::AND ); } }; /// Removes everything after a JUMP (or similar) until the next JUMPDEST. struct UnreachableCode { static bool apply(OptimiserState& _state) { auto it = _state.items.begin() + static_cast<ptrdiff_t>(_state.i); auto end = _state.items.end(); if (it == end) return false; if ( it[0] != Instruction::JUMP && it[0] != Instruction::RETURN && it[0] != Instruction::STOP && it[0] != Instruction::INVALID && it[0] != Instruction::SELFDESTRUCT && it[0] != Instruction::REVERT ) return false; ptrdiff_t i = 1; while (it + i != end && it[i].type() != Tag) i++; if (i > 1) { *_state.out = it[0]; _state.i += static_cast<size_t>(i); return true; } else return false; } }; struct DeduplicateNextTagSize3 : SimplePeepholeOptimizerMethod<DeduplicateNextTagSize3> { static bool applySimple( AssemblyItem const& _precedingItem, AssemblyItem const& _itemA, AssemblyItem const& _itemB, AssemblyItem const& _breakingItem, AssemblyItem const& _tag, AssemblyItem const& _itemC, AssemblyItem const& _itemD, AssemblyItem const& _breakingItem2, std::back_insert_iterator<AssemblyItems> _out ) { if ( _precedingItem.type() != Tag && _itemA == _itemC && _itemB == _itemD && _breakingItem == _breakingItem2 && _tag.type() == Tag && SemanticInformation::terminatesControlFlow(_breakingItem) ) { *_out = _precedingItem; *_out = _tag; *_out = _itemC; *_out = _itemD; *_out = _breakingItem2; return true; } return false; } }; struct DeduplicateNextTagSize2 : SimplePeepholeOptimizerMethod<DeduplicateNextTagSize2> { static bool applySimple( AssemblyItem const& _precedingItem, AssemblyItem const& _itemA, AssemblyItem const& _breakingItem, AssemblyItem const& _tag, AssemblyItem const& _itemC, AssemblyItem const& _breakingItem2, std::back_insert_iterator<AssemblyItems> _out ) { if ( _precedingItem.type() != Tag && _itemA == _itemC && _breakingItem == _breakingItem2 && _tag.type() == Tag && SemanticInformation::terminatesControlFlow(_breakingItem) ) { *_out = _precedingItem; *_out = _tag; *_out = _itemC; *_out = _breakingItem2; return true; } return false; } }; struct DeduplicateNextTagSize1 : SimplePeepholeOptimizerMethod<DeduplicateNextTagSize1> { static bool applySimple( AssemblyItem const& _precedingItem, AssemblyItem const& _breakingItem, AssemblyItem const& _tag, AssemblyItem const& _breakingItem2, std::back_insert_iterator<AssemblyItems> _out ) { if ( _precedingItem.type() != Tag && _breakingItem == _breakingItem2 && _tag.type() == Tag && SemanticInformation::terminatesControlFlow(_breakingItem) ) { *_out = _precedingItem; *_out = _tag; *_out = _breakingItem2; return true; } return false; } }; void applyMethods(OptimiserState&) { assertThrow(false, OptimizerException, "Peephole optimizer failed to apply identity."); } template <typename Method, typename... OtherMethods> void applyMethods(OptimiserState& _state, Method, OtherMethods... _other) { if (!Method::apply(_state)) applyMethods(_state, _other...); } size_t numberOfPops(AssemblyItems const& _items) { return static_cast<size_t>(std::count(_items.begin(), _items.end(), Instruction::POP)); } } bool PeepholeOptimiser::optimise() { // Avoid referencing immutables too early by using approx. counting in bytesRequired() auto const approx = evmasm::Precision::Approximate; OptimiserState state {m_items, 0, back_inserter(m_optimisedItems), m_evmVersion}; while (state.i < m_items.size()) applyMethods( state, PushPop(), OpPop(), OpStop(), OpReturnRevert(), DoublePush(), DoubleSwap(), CommutativeSwap(), SwapComparison(), DupSwap(), IsZeroIsZeroJumpI(), EqIsZeroJumpI(), DoubleJump(), JumpToNext(), UnreachableCode(), DeduplicateNextTagSize3(), DeduplicateNextTagSize2(), DeduplicateNextTagSize1(), TagConjunctions(), TruthyAnd(), Identity() ); if (m_optimisedItems.size() < m_items.size() || ( m_optimisedItems.size() == m_items.size() && ( evmasm::bytesRequired(m_optimisedItems, 3, m_evmVersion, approx) < evmasm::bytesRequired(m_items, 3, m_evmVersion, approx) || numberOfPops(m_optimisedItems) > numberOfPops(m_items) ) )) { m_items = std::move(m_optimisedItems); return true; } else return false; }
15,210
C++
.cpp
593
22.777403
128
0.700885
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
3,292
Assembly.cpp
ethereum_solidity/libevmasm/Assembly.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 /** @file Assembly.cpp * @author Gav Wood <i@gavwood.com> * @date 2014 */ #include <libevmasm/Assembly.h> #include <libevmasm/CommonSubexpressionEliminator.h> #include <libevmasm/ControlFlowGraph.h> #include <libevmasm/PeepholeOptimiser.h> #include <libevmasm/Inliner.h> #include <libevmasm/JumpdestRemover.h> #include <libevmasm/BlockDeduplicator.h> #include <libevmasm/ConstantOptimiser.h> #include <liblangutil/CharStream.h> #include <liblangutil/Exceptions.h> #include <libsolutil/JSON.h> #include <libsolutil/StringUtils.h> #include <fmt/format.h> #include <range/v3/algorithm/any_of.hpp> #include <range/v3/view/drop_exactly.hpp> #include <range/v3/view/enumerate.hpp> #include <range/v3/view/map.hpp> #include <fstream> #include <limits> #include <iterator> using namespace solidity; using namespace solidity::evmasm; using namespace solidity::langutil; using namespace solidity::util; std::map<std::string, std::shared_ptr<std::string const>> Assembly::s_sharedSourceNames; AssemblyItem const& Assembly::append(AssemblyItem _i) { assertThrow(m_deposit >= 0, AssemblyException, "Stack underflow."); m_deposit += static_cast<int>(_i.deposit()); solAssert(m_currentCodeSection < m_codeSections.size()); auto& currentItems = m_codeSections.at(m_currentCodeSection).items; currentItems.emplace_back(std::move(_i)); if (!currentItems.back().location().isValid() && m_currentSourceLocation.isValid()) currentItems.back().setLocation(m_currentSourceLocation); currentItems.back().m_modifierDepth = m_currentModifierDepth; return currentItems.back(); } unsigned Assembly::codeSize(unsigned subTagSize) const { for (unsigned tagSize = subTagSize; true; ++tagSize) { size_t ret = 1; for (auto const& i: m_data) ret += i.second.size(); for (auto const& codeSection: m_codeSections) for (AssemblyItem const& i: codeSection.items) ret += i.bytesRequired(tagSize, m_evmVersion, Precision::Precise); if (numberEncodingSize(ret) <= tagSize) return static_cast<unsigned>(ret); } } void Assembly::importAssemblyItemsFromJSON(Json const& _code, std::vector<std::string> const& _sourceList) { // Assembly constructor creates first code section with proper type and empty `items` solAssert(m_codeSections.size() == 1); solAssert(m_codeSections[0].items.empty()); // TODO: Add support for EOF and more than one code sections. solUnimplementedAssert(!m_eofVersion.has_value(), "Assembly output for EOF is not yet implemented."); solRequire(_code.is_array(), AssemblyImportException, "Supplied JSON is not an array."); for (auto jsonItemIter = std::begin(_code); jsonItemIter != std::end(_code); ++jsonItemIter) { AssemblyItem const& newItem = m_codeSections[0].items.emplace_back(createAssemblyItemFromJSON(*jsonItemIter, _sourceList)); if (newItem == Instruction::JUMPDEST) solThrow(AssemblyImportException, "JUMPDEST instruction without a tag"); else if (newItem.type() == AssemblyItemType::Tag) { ++jsonItemIter; if (jsonItemIter != std::end(_code) && createAssemblyItemFromJSON(*jsonItemIter, _sourceList) != Instruction::JUMPDEST) solThrow(AssemblyImportException, "JUMPDEST expected after tag."); } } } AssemblyItem Assembly::createAssemblyItemFromJSON(Json const& _json, std::vector<std::string> const& _sourceList) { solRequire(_json.is_object(), AssemblyImportException, "Supplied JSON is not an object."); static std::set<std::string> const validMembers{"name", "begin", "end", "source", "value", "modifierDepth", "jumpType"}; for (auto const& [member, _]: _json.items()) solRequire( validMembers.count(member), AssemblyImportException, fmt::format( "Unknown member '{}'. Valid members are: {}.", member, solidity::util::joinHumanReadable(validMembers, ", ") ) ); solRequire(isOfType<std::string>(_json["name"]), AssemblyImportException, "Member 'name' missing or not of type string."); solRequire(isOfTypeIfExists<int>(_json, "begin"), AssemblyImportException, "Optional member 'begin' not of type int."); solRequire(isOfTypeIfExists<int>(_json, "end"), AssemblyImportException, "Optional member 'end' not of type int."); solRequire(isOfTypeIfExists<int>(_json, "source"), AssemblyImportException, "Optional member 'source' not of type int."); solRequire(isOfTypeIfExists<std::string>(_json, "value"), AssemblyImportException, "Optional member 'value' not of type string."); solRequire(isOfTypeIfExists<int>(_json, "modifierDepth"), AssemblyImportException, "Optional member 'modifierDepth' not of type int."); solRequire(isOfTypeIfExists<std::string>(_json, "jumpType"), AssemblyImportException, "Optional member 'jumpType' not of type string."); std::string name = get<std::string>(_json["name"]); solRequire(!name.empty(), AssemblyImportException, "Member 'name' is empty."); SourceLocation location; if (_json.contains("begin")) location.start = get<int>(_json["begin"]); if (_json.contains("end")) location.end = get<int>(_json["end"]); int srcIndex = getOrDefault<int>(_json, "source", -1); size_t modifierDepth = static_cast<size_t>(getOrDefault<int>(_json, "modifierDepth", 0)); std::string value = getOrDefault<std::string>(_json, "value", ""); std::string jumpType = getOrDefault<std::string>(_json, "jumpType", ""); auto updateUsedTags = [&](u256 const& data) { m_usedTags = std::max(m_usedTags, static_cast<unsigned>(data) + 1); return data; }; auto storeImmutableHash = [&](std::string const& _immutableName) -> h256 { h256 hash(util::keccak256(_immutableName)); solAssert(m_immutables.count(hash) == 0 || m_immutables[hash] == _immutableName); m_immutables[hash] = _immutableName; return hash; }; auto storeLibraryHash = [&](std::string const& _libraryName) -> h256 { h256 hash(util::keccak256(_libraryName)); solAssert(m_libraries.count(hash) == 0 || m_libraries[hash] == _libraryName); m_libraries[hash] = _libraryName; return hash; }; auto requireValueDefinedForInstruction = [&](std::string const& _name, std::string const& _value) { solRequire( !_value.empty(), AssemblyImportException, "Member 'value' is missing for instruction '" + _name + "', but the instruction needs a value." ); }; auto requireValueUndefinedForInstruction = [&](std::string const& _name, std::string const& _value) { solRequire( _value.empty(), AssemblyImportException, "Member 'value' defined for instruction '" + _name + "', but the instruction does not need a value." ); }; solRequire(srcIndex >= -1 && srcIndex < static_cast<int>(_sourceList.size()), AssemblyImportException, "Source index out of bounds."); if (srcIndex != -1) location.sourceName = sharedSourceName(_sourceList[static_cast<size_t>(srcIndex)]); AssemblyItem result(0); if (c_instructions.count(name)) { AssemblyItem item{c_instructions.at(name), langutil::DebugData::create(location)}; if (!jumpType.empty()) { if (item.instruction() == Instruction::JUMP || item.instruction() == Instruction::JUMPI) { std::optional<AssemblyItem::JumpType> parsedJumpType = AssemblyItem::parseJumpType(jumpType); if (!parsedJumpType.has_value()) solThrow(AssemblyImportException, "Invalid jump type."); item.setJumpType(parsedJumpType.value()); } else solThrow( AssemblyImportException, "Member 'jumpType' set on instruction different from JUMP or JUMPI (was set on instruction '" + name + "')" ); } requireValueUndefinedForInstruction(name, value); result = item; } else { solRequire( jumpType.empty(), AssemblyImportException, "Member 'jumpType' set on instruction different from JUMP or JUMPI (was set on instruction '" + name + "')" ); if (name == "PUSH") { requireValueDefinedForInstruction(name, value); result = {AssemblyItemType::Push, u256("0x" + value)}; } else if (name == "PUSH [ErrorTag]") { requireValueUndefinedForInstruction(name, value); result = {AssemblyItemType::PushTag, 0}; } else if (name == "PUSH [tag]") { requireValueDefinedForInstruction(name, value); result = {AssemblyItemType::PushTag, updateUsedTags(u256(value))}; } else if (name == "PUSH [$]") { requireValueDefinedForInstruction(name, value); result = {AssemblyItemType::PushSub, u256("0x" + value)}; } else if (name == "PUSH #[$]") { requireValueDefinedForInstruction(name, value); result = {AssemblyItemType::PushSubSize, u256("0x" + value)}; } else if (name == "PUSHSIZE") { requireValueUndefinedForInstruction(name, value); result = {AssemblyItemType::PushProgramSize, 0}; } else if (name == "PUSHLIB") { requireValueDefinedForInstruction(name, value); result = {AssemblyItemType::PushLibraryAddress, storeLibraryHash(value)}; } else if (name == "PUSHDEPLOYADDRESS") { requireValueUndefinedForInstruction(name, value); result = {AssemblyItemType::PushDeployTimeAddress, 0}; } else if (name == "PUSHIMMUTABLE") { requireValueDefinedForInstruction(name, value); result = {AssemblyItemType::PushImmutable, storeImmutableHash(value)}; } else if (name == "ASSIGNIMMUTABLE") { requireValueDefinedForInstruction(name, value); result = {AssemblyItemType::AssignImmutable, storeImmutableHash(value)}; } else if (name == "tag") { requireValueDefinedForInstruction(name, value); result = {AssemblyItemType::Tag, updateUsedTags(u256(value))}; } else if (name == "PUSH data") { requireValueDefinedForInstruction(name, value); result = {AssemblyItemType::PushData, u256("0x" + value)}; } else if (name == "VERBATIM") { requireValueDefinedForInstruction(name, value); AssemblyItem item(fromHex(value), 0, 0); result = item; } else solThrow(InvalidOpcode, "Invalid opcode: " + name); } result.setLocation(location); result.m_modifierDepth = modifierDepth; return result; } namespace { std::string locationFromSources(StringMap const& _sourceCodes, SourceLocation const& _location) { if (!_location.hasText() || _sourceCodes.empty()) return {}; auto it = _sourceCodes.find(*_location.sourceName); if (it == _sourceCodes.end()) return {}; return CharStream::singleLineSnippet(it->second, _location); } class Functionalizer { public: Functionalizer (std::ostream& _out, std::string const& _prefix, StringMap const& _sourceCodes, Assembly const& _assembly): m_out(_out), m_prefix(_prefix), m_sourceCodes(_sourceCodes), m_assembly(_assembly) {} void feed(AssemblyItem const& _item, DebugInfoSelection const& _debugInfoSelection) { if (_item.location().isValid() && _item.location() != m_location) { flush(); m_location = _item.location(); printLocation(_debugInfoSelection); } std::string expression = _item.toAssemblyText(m_assembly); if (!( _item.canBeFunctional() && _item.returnValues() <= 1 && _item.arguments() <= m_pending.size() )) { flush(); m_out << m_prefix << (_item.type() == Tag ? "" : " ") << expression << std::endl; return; } if (_item.arguments() > 0) { expression += "("; for (size_t i = 0; i < _item.arguments(); ++i) { expression += m_pending.back(); m_pending.pop_back(); if (i + 1 < _item.arguments()) expression += ", "; } expression += ")"; } m_pending.push_back(expression); if (_item.returnValues() != 1) flush(); } void flush() { for (std::string const& expression: m_pending) m_out << m_prefix << " " << expression << std::endl; m_pending.clear(); } void printLocation(DebugInfoSelection const& _debugInfoSelection) { if (!m_location.isValid() || (!_debugInfoSelection.location && !_debugInfoSelection.snippet)) return; m_out << m_prefix << " /*"; if (_debugInfoSelection.location) { if (m_location.sourceName) m_out << " " + escapeAndQuoteString(*m_location.sourceName); if (m_location.hasText()) m_out << ":" << std::to_string(m_location.start) + ":" + std::to_string(m_location.end); } if (_debugInfoSelection.snippet) { if (_debugInfoSelection.location) m_out << " "; m_out << locationFromSources(m_sourceCodes, m_location); } m_out << " */" << std::endl; } private: strings m_pending; SourceLocation m_location; std::ostream& m_out; std::string const& m_prefix; StringMap const& m_sourceCodes; Assembly const& m_assembly; }; } void Assembly::assemblyStream( std::ostream& _out, DebugInfoSelection const& _debugInfoSelection, std::string const& _prefix, StringMap const& _sourceCodes ) const { Functionalizer f(_out, _prefix, _sourceCodes, *this); for (auto const& i: m_codeSections.front().items) f.feed(i, _debugInfoSelection); f.flush(); // Implementing this requires introduction of CALLF, RETF and JUMPF if (m_codeSections.size() > 1) solUnimplemented("Add support for more code sections"); if (!m_data.empty() || !m_subs.empty()) { _out << _prefix << "stop" << std::endl; for (auto const& i: m_data) if (u256(i.first) >= m_subs.size()) _out << _prefix << "data_" << toHex(u256(i.first)) << " " << util::toHex(i.second) << std::endl; for (size_t i = 0; i < m_subs.size(); ++i) { _out << std::endl << _prefix << "sub_" << i << ": assembly {\n"; m_subs[i]->assemblyStream(_out, _debugInfoSelection, _prefix + " ", _sourceCodes); _out << _prefix << "}" << std::endl; } } if (m_auxiliaryData.size() > 0) _out << std::endl << _prefix << "auxdata: 0x" << util::toHex(m_auxiliaryData) << std::endl; } std::string Assembly::assemblyString( DebugInfoSelection const& _debugInfoSelection, StringMap const& _sourceCodes ) const { std::ostringstream tmp; assemblyStream(tmp, _debugInfoSelection, "", _sourceCodes); return tmp.str(); } Json Assembly::assemblyJSON(std::map<std::string, unsigned> const& _sourceIndices, bool _includeSourceList) const { Json root; root[".code"] = Json::array(); Json& code = root[".code"]; // TODO: support EOF solUnimplementedAssert(!m_eofVersion.has_value(), "Assembly output for EOF is not yet implemented."); solAssert(m_codeSections.size() == 1); for (AssemblyItem const& item: m_codeSections.front().items) { int sourceIndex = -1; if (item.location().sourceName) { auto iter = _sourceIndices.find(*item.location().sourceName); if (iter != _sourceIndices.end()) sourceIndex = static_cast<int>(iter->second); } auto [name, data] = item.nameAndData(m_evmVersion); Json jsonItem; jsonItem["name"] = name; jsonItem["begin"] = item.location().start; jsonItem["end"] = item.location().end; if (item.m_modifierDepth != 0) jsonItem["modifierDepth"] = static_cast<int>(item.m_modifierDepth); std::string jumpType = item.getJumpTypeAsString(); if (!jumpType.empty()) jsonItem["jumpType"] = jumpType; if (name == "PUSHLIB") data = m_libraries.at(h256(data)); else if (name == "PUSHIMMUTABLE" || name == "ASSIGNIMMUTABLE") data = m_immutables.at(h256(data)); if (!data.empty()) jsonItem["value"] = data; jsonItem["source"] = sourceIndex; code.emplace_back(std::move(jsonItem)); if (item.type() == AssemblyItemType::Tag) { Json jumpdest; jumpdest["name"] = "JUMPDEST"; jumpdest["begin"] = item.location().start; jumpdest["end"] = item.location().end; jumpdest["source"] = sourceIndex; if (item.m_modifierDepth != 0) jumpdest["modifierDepth"] = static_cast<int>(item.m_modifierDepth); code.emplace_back(std::move(jumpdest)); } } if (_includeSourceList) { root["sourceList"] = Json::array(); Json& jsonSourceList = root["sourceList"]; unsigned maxSourceIndex = 0; for (auto const& [sourceName, sourceIndex]: _sourceIndices) { maxSourceIndex = std::max(sourceIndex, maxSourceIndex); jsonSourceList[sourceIndex] = sourceName; } solAssert(maxSourceIndex + 1 >= _sourceIndices.size()); solRequire( _sourceIndices.size() == 0 || _sourceIndices.size() == maxSourceIndex + 1, AssemblyImportException, "The 'sourceList' array contains invalid 'null' item." ); } if (!m_data.empty() || !m_subs.empty()) { root[".data"] = Json::object(); Json& data = root[".data"]; for (auto const& i: m_data) if (u256(i.first) >= m_subs.size()) data[util::toHex(toBigEndian((u256)i.first), util::HexPrefix::DontAdd, util::HexCase::Upper)] = util::toHex(i.second); for (size_t i = 0; i < m_subs.size(); ++i) { std::stringstream hexStr; hexStr << std::hex << i; data[hexStr.str()] = m_subs[i]->assemblyJSON(_sourceIndices, /*_includeSourceList = */false); } } if (!m_auxiliaryData.empty()) root[".auxdata"] = util::toHex(m_auxiliaryData); return root; } std::pair<std::shared_ptr<Assembly>, std::vector<std::string>> Assembly::fromJSON( Json const& _json, std::vector<std::string> const& _sourceList, size_t _level, std::optional<uint8_t> _eofVersion ) { solRequire(_json.is_object(), AssemblyImportException, "Supplied JSON is not an object."); static std::set<std::string> const validMembers{".code", ".data", ".auxdata", "sourceList"}; for (auto const& [attribute, _]: _json.items()) solRequire(validMembers.count(attribute), AssemblyImportException, "Unknown attribute '" + attribute + "'."); if (_level == 0) { if (_json.contains("sourceList")) { solRequire(_json["sourceList"].is_array(), AssemblyImportException, "Optional member 'sourceList' is not an array."); for (Json const& sourceName: _json["sourceList"]) { solRequire(!sourceName.is_null(), AssemblyImportException, "The 'sourceList' array contains invalid 'null' item."); solRequire( sourceName.is_string(), AssemblyImportException, "The 'sourceList' array contains an item that is not a string." ); } } } else solRequire( !_json.contains("sourceList"), AssemblyImportException, "Member 'sourceList' may only be present in the root JSON object." ); auto result = std::make_shared<Assembly>(EVMVersion{}, _level == 0 /* _creation */, _eofVersion, "" /* _name */); std::vector<std::string> parsedSourceList; if (_json.contains("sourceList")) { solAssert(_level == 0); solAssert(_sourceList.empty()); for (Json const& sourceName: _json["sourceList"]) { solRequire( std::find(parsedSourceList.begin(), parsedSourceList.end(), sourceName.get<std::string>()) == parsedSourceList.end(), AssemblyImportException, "Items in 'sourceList' array are not unique." ); parsedSourceList.emplace_back(sourceName.get<std::string>()); } } solRequire(_json.contains(".code"), AssemblyImportException, "Member '.code' is missing."); solRequire(_json[".code"].is_array(), AssemblyImportException, "Member '.code' is not an array."); for (Json const& codeItem: _json[".code"]) solRequire(codeItem.is_object(), AssemblyImportException, "The '.code' array contains an item that is not an object."); result->importAssemblyItemsFromJSON(_json[".code"], _level == 0 ? parsedSourceList : _sourceList); if (_json.contains(".auxdata")) { solRequire(_json[".auxdata"].is_string(), AssemblyImportException, "Optional member '.auxdata' is not a string."); result->m_auxiliaryData = fromHex(_json[".auxdata"].get<std::string>()); solRequire(!result->m_auxiliaryData.empty(), AssemblyImportException, "Optional member '.auxdata' is not a valid hexadecimal string."); } if (_json.contains(".data")) { solRequire(_json[".data"].is_object(), AssemblyImportException, "Optional member '.data' is not an object."); Json const& data = _json[".data"]; std::map<size_t, std::shared_ptr<Assembly>> subAssemblies; for (auto const& [key, value] : data.items()) { if (value.is_string()) { solRequire( value.get<std::string>().empty() || !fromHex(value.get<std::string>()).empty(), AssemblyImportException, "The value for key '" + key + "' inside '.data' is not a valid hexadecimal string." ); result->m_data[h256(fromHex(key))] = fromHex(value.get<std::string>()); } else if (value.is_object()) { size_t index{}; try { // Using signed variant because stoul() still accepts negative numbers and // just lets them wrap around. int parsedDataItemID = std::stoi(key, nullptr, 16); solRequire(parsedDataItemID >= 0, AssemblyImportException, "The key '" + key + "' inside '.data' is out of the supported integer range."); index = static_cast<size_t>(parsedDataItemID); } catch (std::invalid_argument const&) { solThrow(AssemblyImportException, "The key '" + key + "' inside '.data' is not an integer."); } catch (std::out_of_range const&) { solThrow(AssemblyImportException, "The key '" + key + "' inside '.data' is out of the supported integer range."); } auto [subAssembly, emptySourceList] = Assembly::fromJSON(value, _level == 0 ? parsedSourceList : _sourceList, _level + 1, _eofVersion); solAssert(subAssembly); solAssert(emptySourceList.empty()); solAssert(subAssemblies.count(index) == 0); subAssemblies[index] = subAssembly; } else solThrow(AssemblyImportException, "The value of key '" + key + "' inside '.data' is neither a hex string nor an object."); } if (!subAssemblies.empty()) solRequire( ranges::max(subAssemblies | ranges::views::keys) == subAssemblies.size() - 1, AssemblyImportException, fmt::format( "Invalid subassembly indices in '.data'. Not all numbers between 0 and {} are present.", subAssemblies.size() - 1 ) ); result->m_subs = subAssemblies | ranges::views::values | ranges::to<std::vector>; } if (_level == 0) result->encodeAllPossibleSubPathsInAssemblyTree(); return std::make_pair(result, _level == 0 ? parsedSourceList : std::vector<std::string>{}); } void Assembly::encodeAllPossibleSubPathsInAssemblyTree(std::vector<size_t> _pathFromRoot, std::vector<Assembly*> _assembliesOnPath) { _assembliesOnPath.push_back(this); for (_pathFromRoot.push_back(0); _pathFromRoot.back() < m_subs.size(); ++_pathFromRoot.back()) { for (size_t distanceFromRoot = 0; distanceFromRoot < _assembliesOnPath.size(); ++distanceFromRoot) _assembliesOnPath[distanceFromRoot]->encodeSubPath( _pathFromRoot | ranges::views::drop_exactly(distanceFromRoot) | ranges::to<std::vector> ); m_subs[_pathFromRoot.back()]->encodeAllPossibleSubPathsInAssemblyTree(_pathFromRoot, _assembliesOnPath); } } std::shared_ptr<std::string const> Assembly::sharedSourceName(std::string const& _name) const { if (s_sharedSourceNames.find(_name) == s_sharedSourceNames.end()) s_sharedSourceNames[_name] = std::make_shared<std::string>(_name); return s_sharedSourceNames[_name]; } AssemblyItem Assembly::namedTag(std::string const& _name, size_t _params, size_t _returns, std::optional<uint64_t> _sourceID) { assertThrow(!_name.empty(), AssemblyException, "Empty named tag."); if (m_namedTags.count(_name)) { assertThrow(m_namedTags.at(_name).params == _params, AssemblyException, ""); assertThrow(m_namedTags.at(_name).returns == _returns, AssemblyException, ""); assertThrow(m_namedTags.at(_name).sourceID == _sourceID, AssemblyException, ""); } else m_namedTags[_name] = {static_cast<size_t>(newTag().data()), _sourceID, _params, _returns}; return AssemblyItem{Tag, m_namedTags.at(_name).id}; } AssemblyItem Assembly::newPushLibraryAddress(std::string const& _identifier) { h256 h(util::keccak256(_identifier)); m_libraries[h] = _identifier; return AssemblyItem{PushLibraryAddress, h}; } AssemblyItem Assembly::newPushImmutable(std::string const& _identifier) { h256 h(util::keccak256(_identifier)); m_immutables[h] = _identifier; return AssemblyItem{PushImmutable, h}; } AssemblyItem Assembly::newImmutableAssignment(std::string const& _identifier) { h256 h(util::keccak256(_identifier)); m_immutables[h] = _identifier; return AssemblyItem{AssignImmutable, h}; } AssemblyItem Assembly::newAuxDataLoadN(size_t _offset) { return AssemblyItem{AuxDataLoadN, _offset}; } Assembly& Assembly::optimise(OptimiserSettings const& _settings) { optimiseInternal(_settings, {}); return *this; } std::map<u256, u256> const& Assembly::optimiseInternal( OptimiserSettings const& _settings, std::set<size_t> _tagsReferencedFromOutside ) { if (m_tagReplacements) return *m_tagReplacements; // Run optimisation for sub-assemblies. // TODO: verify and double-check this for EOF. for (size_t subId = 0; subId < m_subs.size(); ++subId) { OptimiserSettings settings = _settings; Assembly& sub = *m_subs[subId]; std::set<size_t> referencedTags; for (auto& codeSection: m_codeSections) referencedTags += JumpdestRemover::referencedTags(codeSection.items, subId); std::map<u256, u256> const& subTagReplacements = sub.optimiseInternal( settings, referencedTags ); // Apply the replacements (can be empty). for (auto& codeSection: m_codeSections) BlockDeduplicator::applyTagReplacement(codeSection.items, subTagReplacements, subId); } std::map<u256, u256> tagReplacements; // Iterate until no new optimisation possibilities are found. for (unsigned count = 1; count > 0;) { count = 0; // TODO: verify this for EOF. if (_settings.runInliner && !m_eofVersion.has_value()) { solAssert(m_codeSections.size() == 1); Inliner{ m_codeSections.front().items, _tagsReferencedFromOutside, _settings.expectedExecutionsPerDeployment, isCreation(), _settings.evmVersion} .optimise(); } // TODO: verify this for EOF. if (_settings.runJumpdestRemover && !m_eofVersion.has_value()) { for (auto& codeSection: m_codeSections) { JumpdestRemover jumpdestOpt{codeSection.items}; if (jumpdestOpt.optimise(_tagsReferencedFromOutside)) count++; } } // TODO: verify this for EOF. if (_settings.runPeephole && !m_eofVersion.has_value()) { for (auto& codeSection: m_codeSections) { PeepholeOptimiser peepOpt{codeSection.items, m_evmVersion}; while (peepOpt.optimise()) { count++; assertThrow(count < 64000, OptimizerException, "Peephole optimizer seems to be stuck."); } } } // This only modifies PushTags, we have to run again to actually remove code. // TODO: implement for EOF. if (_settings.runDeduplicate && !m_eofVersion.has_value()) for (auto& section: m_codeSections) { BlockDeduplicator deduplicator{section.items}; if (deduplicator.deduplicate()) { for (auto const& replacement: deduplicator.replacedTags()) { assertThrow( replacement.first <= std::numeric_limits<size_t>::max() && replacement.second <= std::numeric_limits<size_t>::max(), OptimizerException, "Invalid tag replacement." ); assertThrow( !tagReplacements.count(replacement.first), OptimizerException, "Replacement already known." ); tagReplacements[replacement.first] = replacement.second; if (_tagsReferencedFromOutside.erase(static_cast<size_t>(replacement.first))) _tagsReferencedFromOutside.insert(static_cast<size_t>(replacement.second)); } count++; } } // TODO: investigate for EOF if (_settings.runCSE && !m_eofVersion.has_value()) { // Control flow graph optimization has been here before but is disabled because it // assumes we only jump to tags that are pushed. This is not the case anymore with // function types that can be stored in storage. AssemblyItems optimisedItems; solAssert(m_codeSections.size() == 1); auto& items = m_codeSections.front().items; bool usesMSize = ranges::any_of(items, [](AssemblyItem const& _i) { return _i == AssemblyItem{Instruction::MSIZE} || _i.type() == VerbatimBytecode; }); auto iter = items.begin(); while (iter != items.end()) { KnownState emptyState; CommonSubexpressionEliminator eliminator{emptyState}; auto orig = iter; iter = eliminator.feedItems(iter, items.end(), usesMSize); bool shouldReplace = false; AssemblyItems optimisedChunk; try { optimisedChunk = eliminator.getOptimizedItems(); shouldReplace = (optimisedChunk.size() < static_cast<size_t>(iter - orig)); } catch (StackTooDeepException const&) { // This might happen if the opcode reconstruction is not as efficient // as the hand-crafted code. } catch (ItemNotAvailableException const&) { // This might happen if e.g. associativity and commutativity rules // reorganise the expression tree, but not all leaves are available. } if (shouldReplace) { count++; optimisedItems += optimisedChunk; } else copy(orig, iter, back_inserter(optimisedItems)); } if (optimisedItems.size() < items.size()) { items = std::move(optimisedItems); count++; } } } // TODO: investigate for EOF if (_settings.runConstantOptimiser && !m_eofVersion.has_value()) ConstantOptimisationMethod::optimiseConstants( isCreation(), isCreation() ? 1 : _settings.expectedExecutionsPerDeployment, _settings.evmVersion, *this ); m_tagReplacements = std::move(tagReplacements); return *m_tagReplacements; } namespace { template<typename ValueT> void setBigEndian(bytes& _dest, size_t _offset, size_t _size, ValueT _value) { assertThrow(numberEncodingSize(_value) <= _size, AssemblyException, ""); toBigEndian(_value, bytesRef(_dest.data() + _offset, _size)); } template<typename ValueT> void appendBigEndian(bytes& _dest, size_t _size, ValueT _value) { _dest.resize(_dest.size() + _size); setBigEndian(_dest, _dest.size() - _size, _size, _value); } template<typename ValueT> void setBigEndianUint16(bytes& _dest, size_t _offset, ValueT _value) { setBigEndian(_dest, _offset, 2, _value); } template<typename ValueT> void appendBigEndianUint16(bytes& _dest, ValueT _value) { static_assert(!std::numeric_limits<ValueT>::is_signed, "only unsigned types or bigint supported"); assertThrow(_value <= 0xFFFF, AssemblyException, ""); appendBigEndian(_dest, 2, static_cast<size_t>(_value)); } } std::tuple<bytes, std::vector<size_t>, size_t> Assembly::createEOFHeader(std::set<uint16_t> const& _referencedSubIds) const { bytes retBytecode; std::vector<size_t> codeSectionSizePositions; size_t dataSectionSizePosition; retBytecode.push_back(0xef); retBytecode.push_back(0x00); retBytecode.push_back(0x01); // version 1 retBytecode.push_back(0x01); // kind=type appendBigEndianUint16(retBytecode, m_codeSections.size() * 4u); // length of type section retBytecode.push_back(0x02); // kind=code appendBigEndianUint16(retBytecode, m_codeSections.size()); // placeholder for number of code sections for (auto const& codeSection: m_codeSections) { (void) codeSection; codeSectionSizePositions.emplace_back(retBytecode.size()); appendBigEndianUint16(retBytecode, 0u); // placeholder for length of code } if (!_referencedSubIds.empty()) { retBytecode.push_back(0x03); appendBigEndianUint16(retBytecode, _referencedSubIds.size()); for (auto subId: _referencedSubIds) appendBigEndianUint16(retBytecode, m_subs[subId]->assemble().bytecode.size()); } retBytecode.push_back(0x04); // kind=data dataSectionSizePosition = retBytecode.size(); appendBigEndianUint16(retBytecode, 0u); // length of data retBytecode.push_back(0x00); // terminator for (auto const& codeSection: m_codeSections) { retBytecode.push_back(codeSection.inputs); retBytecode.push_back(codeSection.outputs); // TODO: Add stack height calculation appendBigEndianUint16(retBytecode, 0xFFFFu); } return {retBytecode, codeSectionSizePositions, dataSectionSizePosition}; } LinkerObject const& Assembly::assemble() const { solRequire(!m_invalid, AssemblyException, "Attempted to assemble invalid Assembly object."); // Return the already assembled object, if present. if (!m_assembledObject.bytecode.empty()) return m_assembledObject; // Otherwise ensure the object is actually clear. solRequire(m_assembledObject.linkReferences.empty(), AssemblyException, "Unexpected link references."); bool const eof = m_eofVersion.has_value(); solRequire(!eof || m_eofVersion == 1, AssemblyException, "Invalid EOF version."); if (!eof) return assembleLegacy(); else return assembleEOF(); } [[nodiscard]] bytes Assembly::assembleOperation(AssemblyItem const& _item) const { // solidity::evmasm::Instructions underlying type is uint8_t // TODO: Change to std::to_underlying since C++23 return {static_cast<uint8_t>(_item.instruction())}; } [[nodiscard]] bytes Assembly::assemblePush(AssemblyItem const& _item) const { bytes ret; unsigned pushValueSize = numberEncodingSize(_item.data()); if (pushValueSize == 0 && !m_evmVersion.hasPush0()) pushValueSize = 1; // solidity::evmasm::Instructions underlying type is uint8_t // TODO: Change to std::to_underlying since C++23 ret.push_back(static_cast<uint8_t>(pushInstruction(pushValueSize))); if (pushValueSize > 0) appendBigEndian(ret, pushValueSize, _item.data()); return ret; } [[nodiscard]] std::pair<bytes, Assembly::LinkRef> Assembly::assemblePushLibraryAddress(AssemblyItem const& _item, size_t _pos) const { return { // solidity::evmasm::Instructions underlying type is uint8_t // TODO: Change to std::to_underlying since C++23 bytes(1, static_cast<uint8_t>(Instruction::PUSH20)) + bytes(20), {_pos + 1, m_libraries.at(_item.data())} }; } [[nodiscard]] bytes Assembly::assembleVerbatimBytecode(AssemblyItem const& item) const { return item.verbatimData(); } [[nodiscard]] bytes Assembly::assemblePushDeployTimeAddress() const { // solidity::evmasm::Instructions underlying type is uint8_t // TODO: Change to std::to_underlying since C++23 return bytes(1, static_cast<uint8_t>(Instruction::PUSH20)) + bytes(20); } [[nodiscard]] bytes Assembly::assembleTag(AssemblyItem const& _item, size_t _pos, bool _addJumpDest) const { solRequire(_item.data() != 0, AssemblyException, "Invalid tag position."); solRequire(_item.splitForeignPushTag().first == std::numeric_limits<size_t>::max(), AssemblyException, "Foreign tag."); solRequire(_pos < 0xffffffffL, AssemblyException, "Tag too large."); size_t tagId = static_cast<size_t>(_item.data()); solRequire(m_tagPositionsInBytecode[tagId] == std::numeric_limits<size_t>::max(), AssemblyException, "Duplicate tag position."); m_tagPositionsInBytecode[tagId] = _pos; // solidity::evmasm::Instructions underlying type is uint8_t // TODO: Change to std::to_underlying since C++23 return _addJumpDest ? bytes(1, static_cast<uint8_t>(Instruction::JUMPDEST)) : bytes(); } LinkerObject const& Assembly::assembleLegacy() const { solAssert(!m_eofVersion.has_value()); solAssert(!m_invalid); // Return the already assembled object, if present. if (!m_assembledObject.bytecode.empty()) return m_assembledObject; // Otherwise ensure the object is actually clear. solAssert(m_assembledObject.linkReferences.empty()); LinkerObject& ret = m_assembledObject; size_t subTagSize = 1; std::map<u256, LinkerObject::ImmutableRefs> immutableReferencesBySub; for (auto const& sub: m_subs) { auto const& linkerObject = sub->assemble(); if (!linkerObject.immutableReferences.empty()) { assertThrow( immutableReferencesBySub.empty(), AssemblyException, "More than one sub-assembly references immutables." ); immutableReferencesBySub = linkerObject.immutableReferences; } for (size_t tagPos: sub->m_tagPositionsInBytecode) if (tagPos != std::numeric_limits<size_t>::max() && numberEncodingSize(tagPos) > subTagSize) subTagSize = numberEncodingSize(tagPos); } bool setsImmutables = false; bool pushesImmutables = false; assertThrow(m_codeSections.size() == 1, AssemblyException, "Expected exactly one code section in non-EOF code."); AssemblyItems const& items = m_codeSections.front().items; for (auto const& item: items) if (item.type() == AssignImmutable) { item.setImmutableOccurrences(immutableReferencesBySub[item.data()].second.size()); setsImmutables = true; } else if (item.type() == PushImmutable) pushesImmutables = true; if (setsImmutables || pushesImmutables) assertThrow( setsImmutables != pushesImmutables, AssemblyException, "Cannot push and assign immutables in the same assembly subroutine." ); unsigned bytesRequiredForCode = codeSize(static_cast<unsigned>(subTagSize)); m_tagPositionsInBytecode = std::vector<size_t>(m_usedTags, std::numeric_limits<size_t>::max()); unsigned bytesPerTag = numberEncodingSize(bytesRequiredForCode); // Adjust bytesPerTag for references to sub assemblies. for (AssemblyItem const& item: items) if (item.type() == PushTag) { auto [subId, tagId] = item.splitForeignPushTag(); if (subId == std::numeric_limits<size_t>::max()) continue; assertThrow(subId < m_subs.size(), AssemblyException, "Invalid sub id"); auto subTagPosition = m_subs[subId]->m_tagPositionsInBytecode.at(tagId); assertThrow(subTagPosition != std::numeric_limits<size_t>::max(), AssemblyException, "Reference to tag without position."); bytesPerTag = std::max(bytesPerTag, numberEncodingSize(subTagPosition)); } unsigned bytesRequiredIncludingData = bytesRequiredForCode + 1 + static_cast<unsigned>(m_auxiliaryData.size()); for (auto const& sub: m_subs) bytesRequiredIncludingData += static_cast<unsigned>(sub->assemble().bytecode.size()); unsigned bytesPerDataRef = numberEncodingSize(bytesRequiredIncludingData); ret.bytecode.reserve(bytesRequiredIncludingData); TagRefs tagRefs; DataRefs dataRefs; SubAssemblyRefs subRefs; ProgramSizeRefs sizeRefs; uint8_t tagPush = static_cast<uint8_t>(pushInstruction(bytesPerTag)); uint8_t dataRefPush = static_cast<uint8_t>(pushInstruction(bytesPerDataRef)); for (AssemblyItem const& item: items) { // store position of the invalid jump destination if (item.type() != Tag && m_tagPositionsInBytecode[0] == std::numeric_limits<size_t>::max()) m_tagPositionsInBytecode[0] = ret.bytecode.size(); switch (item.type()) { case Operation: ret.bytecode += assembleOperation(item); break; case Push: ret.bytecode += assemblePush(item); break; case PushTag: { ret.bytecode.push_back(tagPush); tagRefs[ret.bytecode.size()] = item.splitForeignPushTag(); ret.bytecode.resize(ret.bytecode.size() + bytesPerTag); break; } case PushData: ret.bytecode.push_back(dataRefPush); dataRefs.insert(std::make_pair(h256(item.data()), ret.bytecode.size())); ret.bytecode.resize(ret.bytecode.size() + bytesPerDataRef); break; case PushSub: assertThrow(item.data() <= std::numeric_limits<size_t>::max(), AssemblyException, ""); ret.bytecode.push_back(dataRefPush); subRefs.insert(std::make_pair(static_cast<size_t>(item.data()), ret.bytecode.size())); ret.bytecode.resize(ret.bytecode.size() + bytesPerDataRef); break; case PushSubSize: { assertThrow(item.data() <= std::numeric_limits<size_t>::max(), AssemblyException, ""); auto s = subAssemblyById(static_cast<size_t>(item.data()))->assemble().bytecode.size(); item.setPushedValue(u256(s)); unsigned b = std::max<unsigned>(1, numberEncodingSize(s)); ret.bytecode.push_back(static_cast<uint8_t>(pushInstruction(b))); ret.bytecode.resize(ret.bytecode.size() + b); bytesRef byr(&ret.bytecode.back() + 1 - b, b); toBigEndian(s, byr); break; } case PushProgramSize: { ret.bytecode.push_back(dataRefPush); sizeRefs.push_back(static_cast<unsigned>(ret.bytecode.size())); ret.bytecode.resize(ret.bytecode.size() + bytesPerDataRef); break; } case PushLibraryAddress: { auto const [bytecode, linkRef] = assemblePushLibraryAddress(item, ret.bytecode.size()); ret.bytecode += bytecode; ret.linkReferences.insert(linkRef); break; } case PushImmutable: ret.bytecode.push_back(static_cast<uint8_t>(Instruction::PUSH32)); // Maps keccak back to the "identifier" std::string of that immutable. ret.immutableReferences[item.data()].first = m_immutables.at(item.data()); // Record the bytecode offset of the PUSH32 argument. ret.immutableReferences[item.data()].second.emplace_back(ret.bytecode.size()); // Advance bytecode by 32 bytes (default initialized). ret.bytecode.resize(ret.bytecode.size() + 32); break; case VerbatimBytecode: ret.bytecode += assembleVerbatimBytecode(item); break; case AssignImmutable: { // Expect 2 elements on stack (source, dest_base) auto const& offsets = immutableReferencesBySub[item.data()].second; for (size_t i = 0; i < offsets.size(); ++i) { if (i != offsets.size() - 1) { ret.bytecode.push_back(uint8_t(Instruction::DUP2)); ret.bytecode.push_back(uint8_t(Instruction::DUP2)); } // TODO: should we make use of the constant optimizer methods for pushing the offsets? bytes offsetBytes = toCompactBigEndian(u256(offsets[i])); ret.bytecode.push_back(static_cast<uint8_t>(pushInstruction(static_cast<unsigned>(offsetBytes.size())))); ret.bytecode += offsetBytes; ret.bytecode.push_back(uint8_t(Instruction::ADD)); ret.bytecode.push_back(uint8_t(Instruction::MSTORE)); } if (offsets.empty()) { ret.bytecode.push_back(uint8_t(Instruction::POP)); ret.bytecode.push_back(uint8_t(Instruction::POP)); } immutableReferencesBySub.erase(item.data()); break; } case PushDeployTimeAddress: ret.bytecode += assemblePushDeployTimeAddress(); break; case Tag: ret.bytecode += assembleTag(item, ret.bytecode.size(), true); break; default: assertThrow(false, InvalidOpcode, "Unexpected opcode while assembling."); } } if (!immutableReferencesBySub.empty()) throw langutil::Error( 1284_error, langutil::Error::Type::CodeGenerationError, "Some immutables were read from but never assigned, possibly because of optimization." ); if (!m_subs.empty() || !m_data.empty() || !m_auxiliaryData.empty()) // Append an INVALID here to help tests find miscompilation. ret.bytecode.push_back(static_cast<uint8_t>(Instruction::INVALID)); std::map<LinkerObject, size_t> subAssemblyOffsets; for (auto const& [subIdPath, bytecodeOffset]: subRefs) { LinkerObject subObject = subAssemblyById(subIdPath)->assemble(); bytesRef r(ret.bytecode.data() + bytecodeOffset, bytesPerDataRef); // In order for de-duplication to kick in, not only must the bytecode be identical, but // link and immutables references as well. if (size_t* subAssemblyOffset = util::valueOrNullptr(subAssemblyOffsets, subObject)) toBigEndian(*subAssemblyOffset, r); else { toBigEndian(ret.bytecode.size(), r); subAssemblyOffsets[subObject] = ret.bytecode.size(); ret.bytecode += subObject.bytecode; } for (auto const& ref: subObject.linkReferences) ret.linkReferences[ref.first + subAssemblyOffsets[subObject]] = ref.second; } for (auto const& i: tagRefs) { size_t subId; size_t tagId; std::tie(subId, tagId) = i.second; assertThrow(subId == std::numeric_limits<size_t>::max() || subId < m_subs.size(), AssemblyException, "Invalid sub id"); std::vector<size_t> const& tagPositions = subId == std::numeric_limits<size_t>::max() ? m_tagPositionsInBytecode : m_subs[subId]->m_tagPositionsInBytecode; assertThrow(tagId < tagPositions.size(), AssemblyException, "Reference to non-existing tag."); size_t pos = tagPositions[tagId]; assertThrow(pos != std::numeric_limits<size_t>::max(), AssemblyException, "Reference to tag without position."); assertThrow(numberEncodingSize(pos) <= bytesPerTag, AssemblyException, "Tag too large for reserved space."); bytesRef r(ret.bytecode.data() + i.first, bytesPerTag); toBigEndian(pos, r); } for (auto const& [name, tagInfo]: m_namedTags) { size_t position = m_tagPositionsInBytecode.at(tagInfo.id); std::optional<size_t> tagIndex; for (auto&& [index, item]: items | ranges::views::enumerate) if (item.type() == Tag && static_cast<size_t>(item.data()) == tagInfo.id) { tagIndex = index; break; } ret.functionDebugData[name] = { position == std::numeric_limits<size_t>::max() ? std::nullopt : std::optional<size_t>{position}, tagIndex, tagInfo.sourceID, tagInfo.params, tagInfo.returns }; } for (auto const& dataItem: m_data) { auto references = dataRefs.equal_range(dataItem.first); if (references.first == references.second) continue; for (auto ref = references.first; ref != references.second; ++ref) { bytesRef r(ret.bytecode.data() + ref->second, bytesPerDataRef); toBigEndian(ret.bytecode.size(), r); } ret.bytecode += dataItem.second; } ret.bytecode += m_auxiliaryData; for (unsigned pos: sizeRefs) { bytesRef r(ret.bytecode.data() + pos, bytesPerDataRef); toBigEndian(ret.bytecode.size(), r); } return ret; } std::map<uint16_t, uint16_t> Assembly::findReferencedContainers() const { std::set<uint16_t> referencedSubcontainersIds; solAssert(m_subs.size() <= 0x100); // According to EOF spec for (auto&& codeSection: m_codeSections) for (AssemblyItem const& item: codeSection.items) if (item.type() == EOFCreate || item.type() == ReturnContract) { solAssert(item.data() <= m_subs.size(), "Invalid subcontainer index."); auto const containerId = static_cast<ContainerID>(item.data()); referencedSubcontainersIds.insert(containerId); } std::map<uint16_t, uint16_t> replacements; uint8_t nUnreferenced = 0; for (uint8_t i = 0; i < static_cast<uint16_t>(m_subs.size()); ++i) { if (referencedSubcontainersIds.count(i) > 0) replacements[i] = static_cast<uint16_t>(i - nUnreferenced); else nUnreferenced++; } return replacements; } std::optional<uint16_t> Assembly::findMaxAuxDataLoadNOffset() const { std::optional<unsigned> maxOffset = std::nullopt; for (auto&& codeSection: m_codeSections) for (AssemblyItem const& item: codeSection.items) if (item.type() == AuxDataLoadN) { solAssert(item.data() <= std::numeric_limits<uint16_t>::max(), "Invalid auxdataloadn index value."); auto const offset = static_cast<unsigned>(item.data()); if (!maxOffset.has_value() || offset > maxOffset.value()) maxOffset = offset; } return maxOffset; } LinkerObject const& Assembly::assembleEOF() const { solAssert(m_eofVersion.has_value() && m_eofVersion == 1); LinkerObject& ret = m_assembledObject; auto const subIdsReplacements = findReferencedContainers(); auto const referencedSubIds = keys(subIdsReplacements); solRequire(!m_codeSections.empty(), AssemblyException, "Expected at least one code section."); solRequire( m_codeSections.front().inputs == 0 && m_codeSections.front().outputs == 0x80, AssemblyException, "Expected the first code section to have zero inputs and be non-returning." ); auto const maxAuxDataLoadNOffset = findMaxAuxDataLoadNOffset(); // Insert EOF1 header. auto [headerBytecode, codeSectionSizePositions, dataSectionSizePosition] = createEOFHeader(referencedSubIds); ret.bytecode = headerBytecode; m_tagPositionsInBytecode = std::vector<size_t>(m_usedTags, std::numeric_limits<size_t>::max()); std::map<size_t, uint16_t> dataSectionRef; for (auto&& [codeSectionIndex, codeSection]: m_codeSections | ranges::views::enumerate) { auto const sectionStart = ret.bytecode.size(); for (AssemblyItem const& item: codeSection.items) { // store position of the invalid jump destination if (item.type() != Tag && m_tagPositionsInBytecode[0] == std::numeric_limits<size_t>::max()) m_tagPositionsInBytecode[0] = ret.bytecode.size(); switch (item.type()) { case Operation: solAssert( item.instruction() != Instruction::DATALOADN && item.instruction() != Instruction::RETURNCONTRACT && item.instruction() != Instruction::EOFCREATE ); solAssert(!(item.instruction() >= Instruction::PUSH0 && item.instruction() <= Instruction::PUSH32)); ret.bytecode += assembleOperation(item); break; case Push: ret.bytecode += assemblePush(item); break; case PushLibraryAddress: { auto const [pushLibraryAddressBytecode, linkRef] = assemblePushLibraryAddress(item, ret.bytecode.size()); ret.bytecode += pushLibraryAddressBytecode; ret.linkReferences.insert(linkRef); break; } case EOFCreate: { ret.bytecode.push_back(static_cast<uint8_t>(Instruction::EOFCREATE)); ret.bytecode.push_back(static_cast<uint8_t>(item.data())); break; } case ReturnContract: { ret.bytecode.push_back(static_cast<uint8_t>(Instruction::RETURNCONTRACT)); ret.bytecode.push_back(static_cast<uint8_t>(item.data())); break; } case VerbatimBytecode: ret.bytecode += assembleVerbatimBytecode(item); break; case PushDeployTimeAddress: ret.bytecode += assemblePushDeployTimeAddress(); break; case Tag: ret.bytecode += assembleTag(item, ret.bytecode.size(), false); break; case AuxDataLoadN: { // In findMaxAuxDataLoadNOffset we already verified that unsigned data value fits 2 bytes solAssert(item.data() <= std::numeric_limits<uint16_t>::max(), "Invalid auxdataloadn position."); ret.bytecode.push_back(uint8_t(Instruction::DATALOADN)); dataSectionRef[ret.bytecode.size()] = static_cast<uint16_t>(item.data()); appendBigEndianUint16(ret.bytecode, item.data()); break; } default: solThrow(InvalidOpcode, "Unexpected opcode while assembling."); } } setBigEndianUint16(ret.bytecode, codeSectionSizePositions[codeSectionIndex], ret.bytecode.size() - sectionStart); } for (auto i: referencedSubIds) ret.bytecode += m_subs[i]->assemble().bytecode; // TODO: Fill functionDebugData for EOF. It probably should be handled for new code section in the loop above. solRequire(m_namedTags.empty(), AssemblyException, "Named tags must be empty in EOF context."); auto const dataStart = ret.bytecode.size(); for (auto const& dataItem: m_data) ret.bytecode += dataItem.second; ret.bytecode += m_auxiliaryData; auto const preDeployDataSectionSize = ret.bytecode.size() - dataStart; // DATALOADN loads 32 bytes from EOF data section zero padded if reading out of data bounds. // In our case we do not allow DATALOADN with offsets which reads out of data bounds. auto const staticAuxDataSize = maxAuxDataLoadNOffset.has_value() ? (*maxAuxDataLoadNOffset + 32u) : 0u; solRequire(preDeployDataSectionSize + staticAuxDataSize < std::numeric_limits<uint16_t>::max(), AssemblyException, "Invalid DATALOADN offset."); // If some data was already added to data section we need to update data section refs accordingly if (preDeployDataSectionSize > 0) for (auto [refPosition, staticAuxDataOffset] : dataSectionRef) { // staticAuxDataOffset + preDeployDataSectionSize value is already verified to fit 2 bytes because // staticAuxDataOffset < staticAuxDataSize setBigEndianUint16(ret.bytecode, refPosition, staticAuxDataOffset + preDeployDataSectionSize); } auto const preDeployAndStaticAuxDataSize = preDeployDataSectionSize + staticAuxDataSize; setBigEndianUint16(ret.bytecode, dataSectionSizePosition, preDeployAndStaticAuxDataSize); return ret; } std::vector<size_t> Assembly::decodeSubPath(size_t _subObjectId) const { if (_subObjectId < m_subs.size()) return {_subObjectId}; auto subIdPathIt = find_if( m_subPaths.begin(), m_subPaths.end(), [_subObjectId](auto const& subId) { return subId.second == _subObjectId; } ); assertThrow(subIdPathIt != m_subPaths.end(), AssemblyException, ""); return subIdPathIt->first; } size_t Assembly::encodeSubPath(std::vector<size_t> const& _subPath) { assertThrow(!_subPath.empty(), AssemblyException, ""); if (_subPath.size() == 1) { assertThrow(_subPath[0] < m_subs.size(), AssemblyException, ""); return _subPath[0]; } if (m_subPaths.find(_subPath) == m_subPaths.end()) { size_t objectId = std::numeric_limits<size_t>::max() - m_subPaths.size(); assertThrow(objectId >= m_subs.size(), AssemblyException, ""); m_subPaths[_subPath] = objectId; } return m_subPaths[_subPath]; } Assembly const* Assembly::subAssemblyById(size_t _subId) const { std::vector<size_t> subIds = decodeSubPath(_subId); Assembly const* currentAssembly = this; for (size_t currentSubId: subIds) { currentAssembly = currentAssembly->m_subs.at(currentSubId).get(); assertThrow(currentAssembly, AssemblyException, ""); } assertThrow(currentAssembly != this, AssemblyException, ""); return currentAssembly; } Assembly::OptimiserSettings Assembly::OptimiserSettings::translateSettings(frontend::OptimiserSettings const& _settings, langutil::EVMVersion const& _evmVersion) { // Constructing it this way so that we notice changes in the fields. evmasm::Assembly::OptimiserSettings asmSettings{false, false, false, false, false, false, _evmVersion, 0}; asmSettings.runInliner = _settings.runInliner; asmSettings.runJumpdestRemover = _settings.runJumpdestRemover; asmSettings.runPeephole = _settings.runPeephole; asmSettings.runDeduplicate = _settings.runDeduplicate; asmSettings.runCSE = _settings.runCSE; asmSettings.runConstantOptimiser = _settings.runConstantOptimiser; asmSettings.expectedExecutionsPerDeployment = _settings.expectedExecutionsPerDeployment; asmSettings.evmVersion = _evmVersion; return asmSettings; }
54,064
C++
.cpp
1,389
35.770338
161
0.720909
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,295
AssemblyItem.cpp
ethereum_solidity/libevmasm/AssemblyItem.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 #include <libevmasm/AssemblyItem.h> #include <libevmasm/Assembly.h> #include <libsolutil/CommonData.h> #include <libsolutil/CommonIO.h> #include <libsolutil/Numeric.h> #include <libsolutil/StringUtils.h> #include <libsolutil/FixedHash.h> #include <liblangutil/SourceLocation.h> #include <fstream> #include <limits> using namespace std::literals; using namespace solidity; using namespace solidity::evmasm; using namespace solidity::langutil; static_assert(sizeof(size_t) <= 8, "size_t must be at most 64-bits wide"); namespace { std::string toStringInHex(u256 _value) { std::stringstream hexStr; hexStr << std::uppercase << std::hex << _value; return hexStr.str(); } } AssemblyItem AssemblyItem::toSubAssemblyTag(size_t _subId) const { assertThrow(data() < (u256(1) << 64), util::Exception, "Tag already has subassembly set."); assertThrow(m_type == PushTag || m_type == Tag, util::Exception, ""); auto tag = static_cast<size_t>(u256(data()) & 0xffffffffffffffffULL); AssemblyItem r = *this; r.m_type = PushTag; r.setPushTagSubIdAndTag(_subId, tag); return r; } std::pair<size_t, size_t> AssemblyItem::splitForeignPushTag() const { assertThrow(m_type == PushTag || m_type == Tag, util::Exception, ""); u256 combined = u256(data()); size_t subId = static_cast<size_t>((combined >> 64) - 1); size_t tag = static_cast<size_t>(combined & 0xffffffffffffffffULL); return std::make_pair(subId, tag); } std::pair<std::string, std::string> AssemblyItem::nameAndData(langutil::EVMVersion _evmVersion) const { switch (type()) { case Operation: case EOFCreate: case ReturnContract: return {instructionInfo(instruction(), _evmVersion).name, m_data != nullptr ? toStringInHex(*m_data) : ""}; case Push: return {"PUSH", toStringInHex(data())}; case PushTag: if (data() == 0) return {"PUSH [ErrorTag]", ""}; else return {"PUSH [tag]", util::toString(data())}; case PushSub: return {"PUSH [$]", toString(util::h256(data()))}; case PushSubSize: return {"PUSH #[$]", toString(util::h256(data()))}; case PushProgramSize: return {"PUSHSIZE", ""}; case PushLibraryAddress: return {"PUSHLIB", toString(util::h256(data()))}; case PushDeployTimeAddress: return {"PUSHDEPLOYADDRESS", ""}; case PushImmutable: return {"PUSHIMMUTABLE", toString(util::h256(data()))}; case AssignImmutable: return {"ASSIGNIMMUTABLE", toString(util::h256(data()))}; case Tag: return {"tag", util::toString(data())}; case PushData: return {"PUSH data", toStringInHex(data())}; case VerbatimBytecode: return {"VERBATIM", util::toHex(verbatimData())}; case AuxDataLoadN: return {"AUXDATALOADN", util::toString(data())}; case UndefinedItem: solAssert(false); } util::unreachable(); } void AssemblyItem::setPushTagSubIdAndTag(size_t _subId, size_t _tag) { assertThrow(m_type == PushTag || m_type == Tag, util::Exception, ""); u256 data = _tag; if (_subId != std::numeric_limits<size_t>::max()) data |= (u256(_subId) + 1) << 64; setData(data); } size_t AssemblyItem::bytesRequired(size_t _addressLength, langutil::EVMVersion _evmVersion, Precision _precision) const { switch (m_type) { case Operation: case Tag: // 1 byte for the JUMPDEST return 1; case Push: return 1 + std::max<size_t>((_evmVersion.hasPush0() ? 0 : 1), numberEncodingSize(data())); case PushSubSize: case PushProgramSize: return 1 + 4; // worst case: a 16MB program case PushTag: case PushData: case PushSub: return 1 + _addressLength; case PushLibraryAddress: case PushDeployTimeAddress: return 1 + 20; case PushImmutable: return 1 + 32; case AssignImmutable: { unsigned long immutableOccurrences = 0; // Skip exact immutables count if no precise count was requested if (_precision == Precision::Approximate) immutableOccurrences = 1; // Assume one immut. ref. else { solAssert(m_immutableOccurrences, "No immutable references. `bytesRequired()` called before assembly()?"); immutableOccurrences = m_immutableOccurrences.value(); } if (immutableOccurrences != 0) // (DUP DUP PUSH <n> ADD MSTORE)* (PUSH <n> ADD MSTORE) return (immutableOccurrences - 1) * (5 + 32) + (3 + 32); else // POP POP return 2; } case VerbatimBytecode: return std::get<2>(*m_verbatimBytecode).size(); case AuxDataLoadN: return 1 + 2; case EOFCreate: return 2; case ReturnContract: return 2; case UndefinedItem: solAssert(false); } util::unreachable(); } size_t AssemblyItem::arguments() const { if (hasInstruction()) // The latest EVMVersion is used here, since the InstructionInfo is assumed to be // the same across all EVM versions except for the instruction name. return static_cast<size_t>(instructionInfo(instruction(), EVMVersion()).args); else if (type() == VerbatimBytecode) return std::get<0>(*m_verbatimBytecode); else if (type() == AssignImmutable) return 2; else return 0; } size_t AssemblyItem::returnValues() const { switch (m_type) { case Operation: case EOFCreate: case ReturnContract: // The latest EVMVersion is used here, since the InstructionInfo is assumed to be // the same across all EVM versions except for the instruction name. return static_cast<size_t>(instructionInfo(instruction(), EVMVersion()).ret); case Push: case PushTag: case PushData: case PushSub: case PushSubSize: case PushProgramSize: case PushLibraryAddress: case PushImmutable: case PushDeployTimeAddress: return 1; case Tag: return 0; case VerbatimBytecode: return std::get<1>(*m_verbatimBytecode); case AuxDataLoadN: return 1; case AssignImmutable: case UndefinedItem: break; } return 0; } bool AssemblyItem::canBeFunctional() const { if (m_jumpType != JumpType::Ordinary) return false; switch (m_type) { case Operation: case EOFCreate: case ReturnContract: return !isDupInstruction(instruction()) && !isSwapInstruction(instruction()); case Push: case PushTag: case PushData: case PushSub: case PushSubSize: case PushProgramSize: case PushLibraryAddress: case PushDeployTimeAddress: case PushImmutable: case AuxDataLoadN: return true; case Tag: return false; case AssignImmutable: case VerbatimBytecode: case UndefinedItem: break; } return false; } std::string AssemblyItem::getJumpTypeAsString() const { switch (m_jumpType) { case JumpType::IntoFunction: return "[in]"; case JumpType::OutOfFunction: return "[out]"; case JumpType::Ordinary: default: return ""; } } std::optional<AssemblyItem::JumpType> AssemblyItem::parseJumpType(std::string const& _jumpType) { if (_jumpType == "[in]") return JumpType::IntoFunction; else if (_jumpType == "[out]") return JumpType::OutOfFunction; else if (_jumpType.empty()) return JumpType::Ordinary; return std::nullopt; } std::string AssemblyItem::toAssemblyText(Assembly const& _assembly) const { std::string text; switch (type()) { case Operation: { assertThrow(isValidInstruction(instruction()), AssemblyException, "Invalid instruction."); text = util::toLower(instructionInfo(instruction(), _assembly.evmVersion()).name); break; } case Push: text = toHex(toCompactBigEndian(data(), 1), util::HexPrefix::Add); break; case PushTag: { size_t sub{0}; size_t tag{0}; std::tie(sub, tag) = splitForeignPushTag(); if (sub == std::numeric_limits<size_t>::max()) text = std::string("tag_") + std::to_string(tag); else text = std::string("tag_") + std::to_string(sub) + "_" + std::to_string(tag); break; } case Tag: assertThrow(data() < 0x10000, AssemblyException, "Declaration of sub-assembly tag."); text = std::string("tag_") + std::to_string(static_cast<size_t>(data())) + ":"; break; case PushData: text = std::string("data_") + toHex(data()); break; case PushSub: case PushSubSize: { std::vector<std::string> subPathComponents; for (size_t subPathComponentId: _assembly.decodeSubPath(static_cast<size_t>(data()))) subPathComponents.emplace_back("sub_" + std::to_string(subPathComponentId)); text = (type() == PushSub ? "dataOffset"s : "dataSize"s) + "(" + solidity::util::joinHumanReadable(subPathComponents, ".") + ")"; break; } case PushProgramSize: text = std::string("bytecodeSize"); break; case PushLibraryAddress: text = std::string("linkerSymbol(\"") + toHex(data()) + std::string("\")"); break; case PushDeployTimeAddress: text = std::string("deployTimeAddress()"); break; case PushImmutable: text = std::string("immutable(\"") + "0x" + util::toHex(toCompactBigEndian(data(), 1)) + "\")"; break; case AssignImmutable: text = std::string("assignImmutable(\"") + "0x" + util::toHex(toCompactBigEndian(data(), 1)) + "\")"; break; case UndefinedItem: assertThrow(false, AssemblyException, "Invalid assembly item."); break; case VerbatimBytecode: text = std::string("verbatimbytecode_") + util::toHex(std::get<2>(*m_verbatimBytecode)); break; case AuxDataLoadN: assertThrow(data() <= std::numeric_limits<size_t>::max(), AssemblyException, "Invalid auxdataloadn argument."); text = "auxdataloadn{" + std::to_string(static_cast<size_t>(data())) + "}"; break; case EOFCreate: text = "eofcreate{" + std::to_string(static_cast<size_t>(data())) + "}"; break; case ReturnContract: text = "returcontract{" + std::to_string(static_cast<size_t>(data())) + "}"; break; } if (m_jumpType == JumpType::IntoFunction || m_jumpType == JumpType::OutOfFunction) { text += "\t//"; if (m_jumpType == JumpType::IntoFunction) text += " in"; else text += " out"; } return text; } // Note: This method is exclusively used for debugging. std::ostream& solidity::evmasm::operator<<(std::ostream& _out, AssemblyItem const& _item) { switch (_item.type()) { case Operation: case EOFCreate: case ReturnContract: _out << " " << instructionInfo(_item.instruction(), EVMVersion()).name; if (_item.instruction() == Instruction::JUMP || _item.instruction() == Instruction::JUMPI) _out << "\t" << _item.getJumpTypeAsString(); break; case Push: _out << " PUSH " << std::hex << _item.data() << std::dec; break; case PushTag: { size_t subId = _item.splitForeignPushTag().first; if (subId == std::numeric_limits<size_t>::max()) _out << " PushTag " << _item.splitForeignPushTag().second; else _out << " PushTag " << subId << ":" << _item.splitForeignPushTag().second; break; } case Tag: _out << " Tag " << _item.data(); break; case PushData: _out << " PushData " << std::hex << static_cast<unsigned>(_item.data()) << std::dec; break; case PushSub: _out << " PushSub " << std::hex << static_cast<size_t>(_item.data()) << std::dec; break; case PushSubSize: _out << " PushSubSize " << std::hex << static_cast<size_t>(_item.data()) << std::dec; break; case PushProgramSize: _out << " PushProgramSize"; break; case PushLibraryAddress: { std::string hash(util::h256((_item.data())).hex()); _out << " PushLibraryAddress " << hash.substr(0, 8) + "..." + hash.substr(hash.length() - 8); break; } case PushDeployTimeAddress: _out << " PushDeployTimeAddress"; break; case PushImmutable: _out << " PushImmutable"; break; case AssignImmutable: _out << " AssignImmutable"; break; case VerbatimBytecode: _out << " Verbatim " << util::toHex(_item.verbatimData()); break; case AuxDataLoadN: _out << " AuxDataLoadN " << util::toString(_item.data()); break; case UndefinedItem: _out << " ???"; break; } return _out; } size_t AssemblyItem::opcodeCount() const noexcept { switch (m_type) { case AssemblyItemType::AssignImmutable: // Append empty items if this AssignImmutable was referenced more than once. // For n immutable occurrences the first (n - 1) occurrences will // generate 5 opcodes and the last will generate 3 opcodes, // because it is reusing the 2 top-most elements on the stack. solAssert(m_immutableOccurrences, ""); if (m_immutableOccurrences.value() != 0) return (*m_immutableOccurrences - 1) * 5 + 3; else return 2; // two POP's default: return 1; } } std::string AssemblyItem::computeSourceMapping( AssemblyItems const& _items, std::map<std::string, unsigned> const& _sourceIndicesMap ) { std::string ret; int prevStart = -1; int prevLength = -1; int prevSourceIndex = -1; int prevModifierDepth = -1; char prevJump = 0; for (auto const& item: _items) { if (!ret.empty()) ret += ";"; SourceLocation const& location = item.location(); int length = location.start != -1 && location.end != -1 ? location.end - location.start : -1; int sourceIndex = (location.sourceName && _sourceIndicesMap.count(*location.sourceName)) ? static_cast<int>(_sourceIndicesMap.at(*location.sourceName)) : -1; char jump = '-'; // TODO: Uncomment when EOF functions introduced. if (item.getJumpType() == evmasm::AssemblyItem::JumpType::IntoFunction /*|| item.type() == CallF || item.type() == JumpF*/) jump = 'i'; else if (item.getJumpType() == evmasm::AssemblyItem::JumpType::OutOfFunction /*|| item.type() == RetF*/) jump = 'o'; int modifierDepth = static_cast<int>(item.m_modifierDepth); unsigned components = 5; if (modifierDepth == prevModifierDepth) { components--; if (jump == prevJump) { components--; if (sourceIndex == prevSourceIndex) { components--; if (length == prevLength) { components--; if (location.start == prevStart) components--; } } } } if (components-- > 0) { if (location.start != prevStart) ret += std::to_string(location.start); if (components-- > 0) { ret += ':'; if (length != prevLength) ret += std::to_string(length); if (components-- > 0) { ret += ':'; if (sourceIndex != prevSourceIndex) ret += std::to_string(sourceIndex); if (components-- > 0) { ret += ':'; if (jump != prevJump) ret += jump; if (components-- > 0) { ret += ':'; if (modifierDepth != prevModifierDepth) ret += std::to_string(modifierDepth); } } } } } if (item.opcodeCount() > 1) ret += std::string(item.opcodeCount() - 1, ';'); prevStart = location.start; prevLength = length; prevSourceIndex = sourceIndex; prevJump = jump; prevModifierDepth = modifierDepth; } return ret; }
15,002
C++
.cpp
515
26.405825
125
0.696982
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
3,297
SemanticInformation.cpp
ethereum_solidity/libevmasm/SemanticInformation.cpp
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 /** * @file SemanticInformation.cpp * @author Christian <c@ethdev.com> * @date 2015 * Helper to provide semantic information about assembly items. */ #include <libevmasm/SemanticInformation.h> #include <libevmasm/AssemblyItem.h> using namespace solidity; using namespace solidity::evmasm; std::vector<SemanticInformation::Operation> SemanticInformation::readWriteOperations(Instruction _instruction) { switch (_instruction) { case Instruction::SSTORE: case Instruction::SLOAD: { assertThrow(memory(_instruction) == Effect::None, OptimizerException, ""); assertThrow(storage(_instruction) != Effect::None, OptimizerException, ""); assertThrow(transientStorage(_instruction) == Effect::None, OptimizerException, ""); Operation op; op.effect = storage(_instruction); op.location = Location::Storage; op.startParameter = 0; // We know that exactly one slot is affected. op.lengthConstant = 1; return {op}; } case Instruction::MSTORE: case Instruction::MSTORE8: case Instruction::MLOAD: { assertThrow(memory(_instruction) != Effect::None, OptimizerException, ""); assertThrow(storage(_instruction) == Effect::None, OptimizerException, ""); assertThrow(transientStorage(_instruction) == Effect::None, OptimizerException, ""); Operation op; op.effect = memory(_instruction); op.location = Location::Memory; op.startParameter = 0; if (_instruction == Instruction::MSTORE || _instruction == Instruction::MLOAD) op.lengthConstant = 32; else if (_instruction == Instruction::MSTORE8) op.lengthConstant = 1; return {op}; } case Instruction::TSTORE: case Instruction::TLOAD: { assertThrow(memory(_instruction) == Effect::None, OptimizerException, ""); assertThrow(storage(_instruction) == Effect::None, OptimizerException, ""); assertThrow(transientStorage(_instruction) != Effect::None, OptimizerException, ""); Operation op; op.effect = transientStorage(_instruction); op.location = Location::TransientStorage; op.startParameter = 0; op.lengthConstant = 1; return {op}; } case Instruction::REVERT: case Instruction::RETURN: case Instruction::KECCAK256: case Instruction::LOG0: case Instruction::LOG1: case Instruction::LOG2: case Instruction::LOG3: case Instruction::LOG4: { assertThrow(storage(_instruction) == Effect::None, OptimizerException, ""); assertThrow(memory(_instruction) == Effect::Read, OptimizerException, ""); assertThrow(transientStorage(_instruction) == Effect::None, OptimizerException, ""); Operation op; op.effect = memory(_instruction); op.location = Location::Memory; op.startParameter = 0; op.lengthParameter = 1; return {op}; } case Instruction::EXTCODECOPY: { assertThrow(memory(_instruction) == Effect::Write, OptimizerException, ""); assertThrow(storage(_instruction) == Effect::None, OptimizerException, ""); assertThrow(transientStorage(_instruction) == Effect::None, OptimizerException, ""); Operation op; op.effect = memory(_instruction); op.location = Location::Memory; op.startParameter = 1; op.lengthParameter = 3; return {op}; } case Instruction::CODECOPY: case Instruction::CALLDATACOPY: case Instruction::RETURNDATACOPY: { assertThrow(memory(_instruction) == Effect::Write, OptimizerException, ""); assertThrow(storage(_instruction) == Effect::None, OptimizerException, ""); assertThrow(transientStorage(_instruction) == Effect::None, OptimizerException, ""); Operation op; op.effect = memory(_instruction); op.location = Location::Memory; op.startParameter = 0; op.lengthParameter = 2; return {op}; } case Instruction::MCOPY: { assertThrow(memory(_instruction) != Effect::None, OptimizerException, ""); assertThrow(storage(_instruction) == Effect::None, OptimizerException, ""); assertThrow(transientStorage(_instruction) == Effect::None, OptimizerException, ""); Operation readOperation; readOperation.effect = Read; readOperation.location = Location::Memory; readOperation.startParameter = 1; readOperation.lengthParameter = 2; Operation writeOperation; writeOperation.effect = Write; writeOperation.location = Location::Memory; writeOperation.startParameter = 0; writeOperation.lengthParameter = 2; return {readOperation, writeOperation}; } case Instruction::STATICCALL: case Instruction::CALL: case Instruction::CALLCODE: case Instruction::DELEGATECALL: { size_t paramCount = static_cast<size_t>(instructionInfo(_instruction, langutil::EVMVersion()).args); std::vector<Operation> operations{ Operation{Location::Memory, Effect::Read, paramCount - 4, paramCount - 3, {}}, Operation{Location::Storage, Effect::Read, {}, {}, {}}, Operation{Location::TransientStorage, Effect::Read, {}, {}, {}} }; if (_instruction != Instruction::STATICCALL) { operations.emplace_back(Operation{Location::Storage, Effect::Write, {}, {}, {}}); operations.emplace_back(Operation{Location::TransientStorage, Effect::Write, {}, {}, {}}); } operations.emplace_back(Operation{ Location::Memory, Effect::Write, paramCount - 2, // Length is in paramCount - 1, but it is only a max length, // there is no guarantee that the full area is written to. {}, {} }); return operations; } case Instruction::CREATE: case Instruction::CREATE2: return std::vector<Operation>{ Operation{ Location::Memory, Effect::Read, 1, 2, {} }, Operation{Location::Storage, Effect::Read, {}, {}, {}}, Operation{Location::Storage, Effect::Write, {}, {}, {}}, Operation{Location::TransientStorage, Effect::Read, {}, {}, {}}, Operation{Location::TransientStorage, Effect::Write, {}, {}, {}} }; case Instruction::EOFCREATE: return std::vector<Operation>{ Operation{ Location::Memory, Effect::Read, 2, 3, {} }, Operation{Location::Storage, Effect::Read, {}, {}, {}}, Operation{Location::Storage, Effect::Write, {}, {}, {}}, Operation{Location::TransientStorage, Effect::Read, {}, {}, {}}, Operation{Location::TransientStorage, Effect::Write, {}, {}, {}} }; case Instruction::RETURNCONTRACT: return std::vector<Operation>{ Operation{ Location::Memory, Effect::Read, 0, 1, {} }, Operation{Location::Storage, Effect::Read, {}, {}, {}}, Operation{Location::Storage, Effect::Write, {}, {}, {}}, Operation{Location::TransientStorage, Effect::Read, {}, {}, {}}, Operation{Location::TransientStorage, Effect::Write, {}, {}, {}} }; case Instruction::MSIZE: // This is just to satisfy the assert below. return std::vector<Operation>{}; default: assertThrow(storage(_instruction) == None && memory(_instruction) == None && transientStorage(_instruction) == None, AssemblyException, ""); } return {}; } bool SemanticInformation::breaksCSEAnalysisBlock(AssemblyItem const& _item, bool _msizeImportant) { switch (_item.type()) { default: case UndefinedItem: case Tag: case PushDeployTimeAddress: case AssignImmutable: case VerbatimBytecode: return true; case Push: case PushTag: case PushSub: case PushSubSize: case PushProgramSize: case PushData: case PushLibraryAddress: case PushImmutable: return false; case evmasm::Operation: { if (isSwapInstruction(_item) || isDupInstruction(_item)) return false; if (_item.instruction() == Instruction::GAS || _item.instruction() == Instruction::PC) return true; // GAS and PC assume a specific order of opcodes if (_item.instruction() == Instruction::MSIZE) return true; // msize is modified already by memory access, avoid that for now InstructionInfo info = instructionInfo(_item.instruction(), langutil::EVMVersion()); if (_item.instruction() == Instruction::SSTORE) return false; if (_item.instruction() == Instruction::MSTORE) return false; if (!_msizeImportant && ( _item.instruction() == Instruction::MLOAD || _item.instruction() == Instruction::KECCAK256 )) return false; //@todo: We do not handle the following memory instructions for now: // calldatacopy, codecopy, extcodecopy, mcopy, mstore8, // msize (note that msize also depends on memory read access) // the second requirement will be lifted once it is implemented return info.sideEffects || info.args > 2; } } } bool SemanticInformation::isCommutativeOperation(AssemblyItem const& _item) { if (_item.type() != evmasm::Operation) return false; switch (_item.instruction()) { case Instruction::ADD: case Instruction::MUL: case Instruction::EQ: case Instruction::AND: case Instruction::OR: case Instruction::XOR: return true; default: return false; } } bool SemanticInformation::isDupInstruction(AssemblyItem const& _item) { if (_item.type() != evmasm::Operation) return false; return evmasm::isDupInstruction(_item.instruction()); } bool SemanticInformation::isSwapInstruction(AssemblyItem const& _item) { if (_item.type() != evmasm::Operation) return false; return evmasm::isSwapInstruction(_item.instruction()); } bool SemanticInformation::isJumpInstruction(AssemblyItem const& _item) { return _item == Instruction::JUMP || _item == Instruction::JUMPI; } bool SemanticInformation::altersControlFlow(AssemblyItem const& _item) { if (!_item.hasInstruction()) return false; switch (_item.instruction()) { // note that CALL, CALLCODE and CREATE do not really alter the control flow, because we // continue on the next instruction case Instruction::JUMP: case Instruction::JUMPI: case Instruction::RETURN: case Instruction::SELFDESTRUCT: case Instruction::STOP: case Instruction::INVALID: case Instruction::REVERT: case Instruction::RETURNCONTRACT: return true; default: return false; } } bool SemanticInformation::terminatesControlFlow(AssemblyItem const& _item) { if (!_item.hasInstruction()) return false; return terminatesControlFlow(_item.instruction()); } bool SemanticInformation::terminatesControlFlow(Instruction _instruction) { switch (_instruction) { case Instruction::RETURN: case Instruction::SELFDESTRUCT: case Instruction::STOP: case Instruction::INVALID: case Instruction::REVERT: case Instruction::RETURNCONTRACT: return true; default: return false; } } bool SemanticInformation::reverts(Instruction _instruction) { switch (_instruction) { case Instruction::INVALID: case Instruction::REVERT: return true; default: return false; } } bool SemanticInformation::isDeterministic(AssemblyItem const& _item) { assertThrow(_item.type() != VerbatimBytecode, AssemblyException, ""); if (!_item.hasInstruction()) return true; switch (_item.instruction()) { case Instruction::CALL: case Instruction::CALLCODE: case Instruction::DELEGATECALL: case Instruction::STATICCALL: case Instruction::CREATE: case Instruction::CREATE2: case Instruction::GAS: case Instruction::PC: case Instruction::MSIZE: // depends on previous writes and reads, not only on content case Instruction::BALANCE: // depends on previous calls case Instruction::SELFBALANCE: // depends on previous calls case Instruction::EXTCODESIZE: case Instruction::EXTCODEHASH: case Instruction::RETURNDATACOPY: // depends on previous calls case Instruction::RETURNDATASIZE: case Instruction::EOFCREATE: return false; default: return true; } } bool SemanticInformation::movable(Instruction _instruction) { // These are not really functional. if (isDupInstruction(_instruction) || isSwapInstruction(_instruction)) return false; InstructionInfo info = instructionInfo(_instruction, langutil::EVMVersion()); if (info.sideEffects) return false; switch (_instruction) { case Instruction::KECCAK256: case Instruction::BALANCE: case Instruction::SELFBALANCE: case Instruction::EXTCODESIZE: case Instruction::EXTCODEHASH: case Instruction::RETURNDATASIZE: case Instruction::SLOAD: case Instruction::TLOAD: case Instruction::PC: case Instruction::MSIZE: case Instruction::GAS: return false; default: return true; } return true; } bool SemanticInformation::canBeRemoved(Instruction _instruction) { // These are not really functional. assertThrow(!isDupInstruction(_instruction) && !isSwapInstruction(_instruction), AssemblyException, ""); return !instructionInfo(_instruction, langutil::EVMVersion()).sideEffects; } bool SemanticInformation::canBeRemovedIfNoMSize(Instruction _instruction) { if (_instruction == Instruction::KECCAK256 || _instruction == Instruction::MLOAD) return true; else return canBeRemoved(_instruction); } SemanticInformation::Effect SemanticInformation::memory(Instruction _instruction) { switch (_instruction) { case Instruction::CALLDATACOPY: case Instruction::CODECOPY: case Instruction::EXTCODECOPY: case Instruction::RETURNDATACOPY: case Instruction::MCOPY: case Instruction::MSTORE: case Instruction::MSTORE8: case Instruction::CALL: case Instruction::CALLCODE: case Instruction::DELEGATECALL: case Instruction::STATICCALL: return SemanticInformation::Write; case Instruction::CREATE: case Instruction::CREATE2: case Instruction::KECCAK256: case Instruction::MLOAD: case Instruction::MSIZE: case Instruction::RETURN: case Instruction::REVERT: case Instruction::LOG0: case Instruction::LOG1: case Instruction::LOG2: case Instruction::LOG3: case Instruction::LOG4: case Instruction::EOFCREATE: case Instruction::RETURNCONTRACT: return SemanticInformation::Read; default: return SemanticInformation::None; } } bool SemanticInformation::movableApartFromEffects(Instruction _instruction) { switch (_instruction) { case Instruction::EXTCODEHASH: case Instruction::EXTCODESIZE: case Instruction::RETURNDATASIZE: case Instruction::BALANCE: case Instruction::SELFBALANCE: case Instruction::SLOAD: case Instruction::TLOAD: case Instruction::KECCAK256: case Instruction::MLOAD: return true; default: return movable(_instruction); } } SemanticInformation::Effect SemanticInformation::storage(Instruction _instruction) { switch (_instruction) { case Instruction::CALL: case Instruction::CALLCODE: case Instruction::DELEGATECALL: case Instruction::CREATE: case Instruction::CREATE2: case Instruction::SSTORE: case Instruction::EOFCREATE: case Instruction::RETURNCONTRACT: return SemanticInformation::Write; case Instruction::SLOAD: case Instruction::STATICCALL: return SemanticInformation::Read; default: return SemanticInformation::None; } } SemanticInformation::Effect SemanticInformation::transientStorage(Instruction _instruction) { switch (_instruction) { case Instruction::CALL: case Instruction::CALLCODE: case Instruction::DELEGATECALL: case Instruction::CREATE: case Instruction::CREATE2: case Instruction::TSTORE: case Instruction::EOFCREATE: case Instruction::RETURNCONTRACT: return SemanticInformation::Write; case Instruction::TLOAD: case Instruction::STATICCALL: return SemanticInformation::Read; default: return SemanticInformation::None; } } SemanticInformation::Effect SemanticInformation::otherState(Instruction _instruction) { switch (_instruction) { case Instruction::CALL: case Instruction::CALLCODE: case Instruction::DELEGATECALL: case Instruction::CREATE: case Instruction::CREATE2: case Instruction::EOFCREATE: case Instruction::RETURNCONTRACT: case Instruction::SELFDESTRUCT: case Instruction::STATICCALL: // because it can affect returndatasize // Strictly speaking, log0, .., log4 writes to the state, but the EVM cannot read it, so they // are just marked as having 'other side effects.' return SemanticInformation::Write; case Instruction::EXTCODESIZE: case Instruction::EXTCODEHASH: case Instruction::RETURNDATASIZE: case Instruction::BALANCE: case Instruction::SELFBALANCE: case Instruction::RETURNDATACOPY: case Instruction::EXTCODECOPY: // PC and GAS are specifically excluded here. Instructions such as CALLER, CALLVALUE, // ADDRESS are excluded because they cannot change during execution. return SemanticInformation::Read; default: return SemanticInformation::None; } } bool SemanticInformation::invalidInPureFunctions(Instruction _instruction) { switch (_instruction) { case Instruction::ADDRESS: case Instruction::SELFBALANCE: case Instruction::BALANCE: case Instruction::ORIGIN: case Instruction::CALLER: case Instruction::CALLVALUE: case Instruction::CHAINID: case Instruction::BASEFEE: case Instruction::BLOBBASEFEE: case Instruction::GAS: case Instruction::GASPRICE: case Instruction::EXTCODESIZE: case Instruction::EXTCODECOPY: case Instruction::EXTCODEHASH: case Instruction::BLOCKHASH: case Instruction::BLOBHASH: case Instruction::COINBASE: case Instruction::TIMESTAMP: case Instruction::NUMBER: case Instruction::PREVRANDAO: case Instruction::GASLIMIT: case Instruction::STATICCALL: case Instruction::SLOAD: case Instruction::TLOAD: return true; default: break; } return invalidInViewFunctions(_instruction); } bool SemanticInformation::invalidInViewFunctions(Instruction _instruction) { switch (_instruction) { case Instruction::SSTORE: case Instruction::TSTORE: case Instruction::JUMP: case Instruction::JUMPI: case Instruction::LOG0: case Instruction::LOG1: case Instruction::LOG2: case Instruction::LOG3: case Instruction::LOG4: case Instruction::CREATE: case Instruction::CALL: case Instruction::CALLCODE: case Instruction::DELEGATECALL: // According to EOF spec https://eips.ethereum.org/EIPS/eip-7620#eofcreate case Instruction::EOFCREATE: // According to EOF spec https://eips.ethereum.org/EIPS/eip-7620#returncontract case Instruction::RETURNCONTRACT: case Instruction::CREATE2: case Instruction::SELFDESTRUCT: return true; default: break; } return false; }
18,365
C++
.cpp
598
28.292642
142
0.766687
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,300
CommandLineInterface.h
ethereum_solidity/solc/CommandLineInterface.h
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 /** * @author Lefteris <lefteris@ethdev.com> * @date 2014 * Solidity command line interface. */ #pragma once #include <solc/CommandLineParser.h> #include <libevmasm/AbstractAssemblyStack.h> #include <libevmasm/EVMAssemblyStack.h> #include <libsolidity/interface/CompilerStack.h> #include <libsolidity/interface/DebugSettings.h> #include <libsolidity/interface/FileReader.h> #include <libsolidity/interface/SMTSolverCommand.h> #include <libsolidity/interface/UniversalCallback.h> #include <libyul/YulStack.h> #include <iostream> #include <memory> #include <string> namespace solidity::frontend { class CommandLineInterface { public: explicit CommandLineInterface( std::istream& _sin, std::ostream& _sout, std::ostream& _serr, CommandLineOptions const& _options = CommandLineOptions{} ): m_sin(_sin), m_sout(_sout), m_serr(_serr), m_options(_options) {} /// Parses command-line arguments, executes the requested operation and handles validation and /// execution errors. /// @returns false if it catches a @p CommandLineValidationError or if the application is /// expected to exit with a non-zero exit code despite there being no error. bool run(int _argc, char const* const* _argv); /// Parses command line arguments and stores the result in @p m_options. /// @throws CommandLineValidationError if command-line arguments are invalid. /// @returns false if the application is expected to exit with a non-zero exit code despite /// there being no error. bool parseArguments(int _argc, char const* const* _argv); /// Reads the content of all input files and initializes the file reader. /// @throws CommandLineValidationError if it fails to read the input files (invalid paths, /// non-existent files, not enough or too many input files, etc.). void readInputFiles(); /// Executes the requested operation (compilation, assembling, standard JSON, etc.) and prints /// results to the terminal. /// @throws CommandLineExecutionError if execution fails due to errors in the input files. /// @throws CommandLineOutputError if creating output files or writing to them fails. void processInput(); CommandLineOptions const& options() const { return m_options; } FileReader const& fileReader() const { return m_fileReader; } std::optional<std::string> const& standardJsonInput() const { return m_standardJsonInput; } private: void printVersion(); void printLicense(); void compile(); void assembleFromEVMAssemblyJSON(); void serveLSP(); void link(); void writeLinkedFiles(); /// @returns the ``// <identifier> -> name`` hint for library placeholders. static std::string libraryPlaceholderHint(std::string const& _libraryName); /// @returns the full object with library placeholder hints in hex. static std::string objectWithLinkRefsHex(evmasm::LinkerObject const& _obj); void assembleYul(yul::YulStack::Language _language, yul::YulStack::Machine _targetMachine); void outputCompilationResults(); void handleCombinedJSON(); void handleAst(); void handleEVMAssembly(std::string const& _contract); void handleBinary(std::string const& _contract); void handleOpcode(std::string const& _contract); void handleIR(std::string const& _contract); void handleIRAst(std::string const& _contract); void handleIROptimized(std::string const& _contract); void handleIROptimizedAst(std::string const& _contract); void handleYulCFGExport(std::string const& _contract); void handleBytecode(std::string const& _contract); void handleSignatureHashes(std::string const& _contract); void handleMetadata(std::string const& _contract); void handleABI(std::string const& _contract); void handleNatspec(bool _natspecDev, std::string const& _contract); void handleGasEstimation(std::string const& _contract); void handleStorageLayout(std::string const& _contract); void handleTransientStorageLayout(std::string const& _contract); /// Tries to read @ m_sourceCodes as a JSONs holding ASTs /// such that they can be imported into the compiler (importASTs()) /// (produced by --combined-json ast <file.sol> /// or standard-json output std::map<std::string, Json> parseAstFromInput(); /// Create a file in the given directory /// @arg _fileName the name of the file /// @arg _data to be written void createFile(std::string const& _fileName, std::string const& _data); /// Create a json file in the given directory /// @arg _fileName the name of the file (the extension will be replaced with .json) /// @arg _json json string to be written void createJson(std::string const& _fileName, std::string const& _json); /// Returns the stream that should receive normal output. Sets m_hasOutput to true if the /// stream has ever been used unless @arg _markAsUsed is set to false. std::ostream& sout(bool _markAsUsed = true); /// Returns the stream that should receive error output. Sets m_hasOutput to true if the /// stream has ever been used unless @arg _markAsUsed is set to false. std::ostream& serr(bool _markAsUsed = true); void report(langutil::Error::Severity _severity, std::string _message); std::istream& m_sin; std::ostream& m_sout; std::ostream& m_serr; bool m_hasOutput = false; FileReader m_fileReader; SMTSolverCommand m_solverCommand; UniversalCallback m_universalCallback{&m_fileReader, m_solverCommand}; std::optional<std::string> m_standardJsonInput; std::unique_ptr<frontend::CompilerStack> m_compiler; std::unique_ptr<evmasm::EVMAssemblyStack> m_evmAssemblyStack; evmasm::AbstractAssemblyStack* m_assemblyStack = nullptr; CommandLineOptions m_options; }; }
6,245
C++
.h
136
43.860294
95
0.772189
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,301
Exceptions.h
ethereum_solidity/solc/Exceptions.h
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 /** * Exceptions used by the command-line interface. */ #pragma once #include <liblangutil/Exceptions.h> namespace solidity::frontend { struct CommandLineError: virtual util::Exception {}; struct CommandLineExecutionError: virtual CommandLineError {}; struct CommandLineValidationError: virtual CommandLineError {}; struct CommandLineOutputError: virtual CommandLineError {}; }
1,070
C++
.h
26
39.346154
69
0.803089
ethereum/solidity
23,062
5,715
501
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false