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,488
NameDisplacer.h
ethereum_solidity/libyul/optimiser/NameDisplacer.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 /** * Optimiser component that renames identifiers to free up certain names. */ #pragma once #include <libyul/optimiser/ASTWalker.h> #include <libyul/optimiser/NameDispenser.h> #include <set> #include <map> namespace solidity::yul { struct Dialect; /** * Optimiser component that renames identifiers to free up certain names. * * Only replaces names that have been defined inside the code. If the code uses * names to be freed but does not define them, they remain unchanged. * * Prerequisites: Disambiguator */ class NameDisplacer: public ASTModifier { public: explicit NameDisplacer( NameDispenser& _dispenser, std::set<YulName> const& _namesToFree ): m_nameDispenser(_dispenser), m_namesToFree(_namesToFree) { for (YulName n: _namesToFree) m_nameDispenser.markUsed(n); } using ASTModifier::operator(); void operator()(Identifier& _identifier) override; void operator()(VariableDeclaration& _varDecl) override; void operator()(FunctionDefinition& _function) override; void operator()(FunctionCall& _funCall) override; void operator()(Block& _block) override; std::map<YulName, YulName> const& translations() const { return m_translations; } protected: /// Check if the newly introduced identifier @a _name has to be replaced. void checkAndReplaceNew(YulName& _name); /// Replace the identifier @a _name if it is in the translation map. void checkAndReplace(YulName& _name) const; NameDispenser& m_nameDispenser; std::set<YulName> const& m_namesToFree; std::map<YulName, YulName> m_translations; }; }
2,237
C++
.h
63
33.492063
82
0.777881
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,489
UnusedAssignEliminator.h
ethereum_solidity/libyul/optimiser/UnusedAssignEliminator.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 /** * Optimiser component that removes assignments to variables that are not used * until they go out of scope or are re-assigned. */ #pragma once #include <libyul/ASTForward.h> #include <libyul/optimiser/ASTWalker.h> #include <libyul/optimiser/OptimiserStep.h> #include <libyul/optimiser/UnusedStoreBase.h> #include <libyul/optimiser/Semantics.h> #include <map> #include <vector> namespace solidity::yul { struct Dialect; /** * Optimiser component that removes assignments to variables that are not used * until they go out of scope or are re-assigned. This component * respects the control-flow and takes it into account for removal. * * Example: * * { * let a * a := 1 * a := 2 * b := 2 * if calldataload(0) * { * b := mload(a) * } * a := b * } * * In the example, "a := 1" can be removed because the value from this assignment * is not used in any control-flow branch (it is replaced right away). * The assignment "a := 2" is also overwritten by "a := b" at the end, * but there is a control-flow path (through the condition body) which uses * the value from "a := 2" and thus, this assignment cannot be removed. * * Detailed rules: * * The AST is traversed twice: in an information gathering step and in the * actual removal step. During information gathering, assignment statements * can be marked as "potentially unused" or as "used". * * When an assignment is visited, it is stored in the "set of all stores" and * added to the branch-dependent "active" sets for the assigned variables. This active * set for a variable contains all statements where that variable was last assigned to, i.e. * where a read from that variable could read from. * Furthermore, all other active sets for the assigned variables are cleared. * * When a reference to a variable is visited, the active assignments to that variable * in the current branch are marked as "used". This mark is permanent. * Also, the active set for this variable in the current branch is cleared. * * At points where control-flow splits, we maintain a copy of the active set * (all other data structures are shared across branches). * * At control-flow joins, we combine the sets of active stores for each variable. * * In the example above, the active set right after the assignment "b := mload(a)" (but before * the control-flow join) is "b := mload(a)"; the assignment "b := 2" was removed. * After the control-flow join it will contain both "b := mload(a)" and "b := 2", coming from * the two branches. * * For for-loops, the condition, body and post-part are visited twice, taking * the joining control-flow at the condition into account. * In other words, we create three control flow paths: Zero runs of the loop, * one run and two runs and then combine them at the end. * Running at most twice is enough because this takes into account all possible control-flow connections. * * Since this algorithm has exponential runtime in the nesting depth of for loops, * a shortcut is taken at a certain nesting level: We only use the zero- and * once-run of the for loop and change any assignment that was newly introduced * in the for loop from to "used". * * For switch statements that have a "default"-case, there is no control-flow * part that skips the switch. * * At ``leave`` statements, all return variables are set to "used" and the set of active statements * is cleared. * * If a function or builtin is called that does not continue, the set of active statements is * cleared for all variables. * * In the second traversal, all assignments that are not marked as "used" are removed. * * This step is usually run right after the SSA transform to complete * the generation of the pseudo-SSA. * * Prerequisite: Disambiguator, ForLoopInitRewriter. */ class UnusedAssignEliminator: public UnusedStoreBase<YulName> { public: static constexpr char const* name{"UnusedAssignEliminator"}; static void run(OptimiserStepContext&, Block& _ast); explicit UnusedAssignEliminator( Dialect const& _dialect, std::map<YulName, ControlFlowSideEffects> _controlFlowSideEffects ): UnusedStoreBase(_dialect), m_controlFlowSideEffects(_controlFlowSideEffects) {} void operator()(Identifier const& _identifier) override; void operator()(Assignment const& _assignment) override; void operator()(FunctionDefinition const&) override; void operator()(FunctionCall const& _functionCall) override; void operator()(Leave const&) override; void operator()(Block const& _block) override; using UnusedStoreBase::visit; void visit(Statement const& _statement) override; private: void shortcutNestedLoop(ActiveStores const& _beforeLoop) override; void finalizeFunctionDefinition(FunctionDefinition const& _functionDefinition) override; void markUsed(YulName _variable); std::set<YulName> m_returnVariables; std::map<YulName, ControlFlowSideEffects> m_controlFlowSideEffects; }; }
5,638
C++
.h
135
39.785185
105
0.762026
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,490
UnusedFunctionParameterPruner.h
ethereum_solidity/libyul/optimiser/UnusedFunctionParameterPruner.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 #pragma once #include <libyul/optimiser/OptimiserStep.h> namespace solidity::yul { /** * UnusedFunctionParameterPruner: Optimiser step that removes unused parameters in a function. * * If a parameter is unused, like `c` and `y` in, `function f(a,b,c) -> x, y { x := div(a,b) }` * * We remove the parameter and create a new "linking" function as follows: * * `function f(a,b) -> x { x := div(a,b) }` * `function f2(a,b,c) -> x, y { x := f(a,b) }` * * and replace all references to `f` by `f2`. * The inliner should be run afterwards to make sure that all references to `f2` are replaced by * `f`. * * Prerequisites: Disambiguator, FunctionHoister, LiteralRematerialiser * * The step LiteralRematerialiser is not required for correctness. It helps deal with cases such as: * `function f(x) -> y { revert(y, y} }` where the literal `y` will be replaced by its value `0`, * allowing us to rewrite the function. */ struct UnusedFunctionParameterPruner { static constexpr char const* name{"UnusedFunctionParameterPruner"}; static void run(OptimiserStepContext& _context, Block& _ast); }; }
1,795
C++
.h
44
38.886364
100
0.744119
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,491
StackLimitEvader.h
ethereum_solidity/libyul/optimiser/StackLimitEvader.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/>. */ /** * Optimisation stage that assigns memory offsets to variables that would become unreachable if * assigned a stack slot as usual and replaces references and assignments to them by mload and mstore calls. */ #pragma once #include <libyul/optimiser/OptimiserStep.h> #include <libyul/backends/evm/StackLayoutGenerator.h> namespace solidity::yul { class Object; /** * Optimisation stage that assigns memory offsets to variables that would become unreachable if * assigned a stack slot as usual. * * Uses CompilabilityChecker to determine which variables in which functions are unreachable. * * Only variables outside of functions contained in cycles in the call graph are considered. Thereby it is possible * to assign globally fixed memory offsets to the variable. If a variable in a function contained in a cycle in the * call graph is reported as unreachable, the process is aborted. * * Offsets are assigned to the variables, s.t. on every path through the call graph each variable gets a unique offset * in memory. However, distinct paths through the call graph can use the same memory offsets for their variables. * * The current arguments to the ``memoryguard`` calls are used as base memory offset and then replaced by the offset past * the last memory offset used for a variable on any path through the call graph. * * Finally, the StackToMemoryMover is called to actually move the variables to their offsets in memory. * * Prerequisite: Disambiguator */ class StackLimitEvader { public: /// @a _unreachableVariables can be determined by the CompilabilityChecker. /// Can only be run on the EVM dialect with objects. /// Abort and do nothing, if no ``memoryguard`` call or several ``memoryguard`` calls /// with non-matching arguments are found, or if any of the @a _unreachableVariables /// are contained in a recursive function. static void run( OptimiserStepContext& _context, Block& _astRoot, std::map<YulName, std::vector<YulName>> const& _unreachableVariables ); /// @a _stackTooDeepErrors can be determined by the StackLayoutGenerator. /// Can only be run on the EVM dialect with objects. /// Abort and do nothing, if no ``memoryguard`` call or several ``memoryguard`` calls /// with non-matching arguments are found, or if any of the @a _stackTooDeepErrors /// are contained in a recursive function. static void run( OptimiserStepContext& _context, Block& _astRoot, std::map<YulName, std::vector<StackLayoutGenerator::StackTooDeep>> const& _stackTooDeepErrors ); /// Determines stack too deep errors using the appropriate code generation backend. /// Can only be run on the EVM dialect with objects. /// Abort and do nothing, if no ``memoryguard`` call or several ``memoryguard`` calls /// with non-matching arguments are found, or if any of the unreachable variables /// are contained in a recursive function. static Block run( OptimiserStepContext& _context, Object const& _object ); }; }
3,621
C++
.h
77
45
121
0.778784
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,492
NameCollector.h
ethereum_solidity/libyul/optimiser/NameCollector.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 /** * Specific AST walkers that collect facts about identifiers and definitions. */ #pragma once #include <libyul/optimiser/ASTWalker.h> #include <libyul/YulName.h> #include <map> #include <set> namespace solidity::yul { /** * Specific AST walker that collects all defined names. */ class NameCollector: public ASTWalker { public: enum CollectWhat { VariablesAndFunctions, OnlyVariables, OnlyFunctions }; explicit NameCollector( Block const& _block, CollectWhat _collectWhat = VariablesAndFunctions ): m_collectWhat(_collectWhat) { (*this)(_block); } explicit NameCollector( FunctionDefinition const& _functionDefinition, CollectWhat _collectWhat = VariablesAndFunctions ): m_collectWhat(_collectWhat) { (*this)(_functionDefinition); } using ASTWalker::operator (); void operator()(VariableDeclaration const& _varDecl) override; void operator()(FunctionDefinition const& _funDef) override; std::set<YulName> names() const { return m_names; } private: std::set<YulName> m_names; CollectWhat m_collectWhat = VariablesAndFunctions; }; /** * Specific AST walker that counts all references to all declarations. */ class ReferencesCounter: public ASTWalker { public: using ASTWalker::operator (); void operator()(Identifier const& _identifier) override; void operator()(FunctionCall const& _funCall) override; static std::map<YulName, size_t> countReferences(Block const& _block); static std::map<YulName, size_t> countReferences(FunctionDefinition const& _function); static std::map<YulName, size_t> countReferences(Expression const& _expression); private: std::map<YulName, size_t> m_references; }; /** * Specific AST walker that counts all references to all variable declarations. */ class VariableReferencesCounter: public ASTWalker { public: using ASTWalker::operator (); void operator()(Identifier const& _identifier) override; static std::map<YulName, size_t> countReferences(Block const& _block); static std::map<YulName, size_t> countReferences(FunctionDefinition const& _function); static std::map<YulName, size_t> countReferences(Expression const& _expression); static std::map<YulName, size_t> countReferences(Statement const& _statement); private: std::map<YulName, size_t> m_references; }; /** * Collects all names from a given continue statement on onwards. * * It makes only sense to be invoked from within a body of an outer for loop, that is, * it will only collect all names from the beginning of the first continue statement * of the outer-most ForLoop. */ class AssignmentsSinceContinue: public ASTWalker { public: using ASTWalker::operator(); void operator()(ForLoop const& _forLoop) override; void operator()(Continue const&) override; void operator()(Assignment const& _assignment) override; void operator()(FunctionDefinition const& _funDef) override; std::set<YulName> const& names() const { return m_names; } bool empty() const noexcept { return m_names.empty(); } private: size_t m_forLoopDepth = 0; bool m_continueFound = false; std::set<YulName> m_names; }; /// @returns the names of all variables that are assigned to inside @a _code. /// (ignores variable declarations) std::set<YulName> assignedVariableNames(Block const& _code); /// @returns all function definitions anywhere in the AST. /// Requires disambiguated source. std::map<YulName, FunctionDefinition const*> allFunctionDefinitions(Block const& _block); }
4,118
C++
.h
114
34.210526
89
0.778392
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,495
EqualStoreEliminator.h
ethereum_solidity/libyul/optimiser/EqualStoreEliminator.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 /** * Optimisation stage that removes mstore and sstore operations if they store the same * value that is already known to be in that slot. */ #pragma once #include <libyul/optimiser/DataFlowAnalyzer.h> #include <libyul/optimiser/OptimiserStep.h> namespace solidity::yul { /** * Optimisation stage that removes mstore and sstore operations if they store the same * value that is already known to be in that slot. * * Works best if the code is in SSA form - without literal arguments. * * Prerequisite: Disambiguator, ForLoopInitRewriter. */ class EqualStoreEliminator: public DataFlowAnalyzer { public: static constexpr char const* name{"EqualStoreEliminator"}; static void run(OptimiserStepContext const&, Block& _ast); private: EqualStoreEliminator( Dialect const& _dialect, std::map<YulName, SideEffects> _functionSideEffects ): DataFlowAnalyzer(_dialect, MemoryAndStorage::Analyze, std::move(_functionSideEffects)) {} protected: using ASTModifier::visit; void visit(Statement& _statement) override; std::set<Statement const*> m_pendingRemovals; }; }
1,771
C++
.h
49
34.204082
88
0.790766
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,496
SemanticTokensBuilder.h
ethereum_solidity/libsolidity/lsp/SemanticTokensBuilder.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 #include <libsolidity/ast/AST.h> #include <libsolidity/ast/ASTVisitor.h> #include <libsolutil/JSON.h> #include <fmt/format.h> namespace solidity::langutil { class CharStream; struct SourceLocation; } namespace solidity::lsp { // See: https://microsoft.github.io/language-server-protocol/specifications/specification-3-17/#semanticTokenTypes enum class SemanticTokenType { Class, Comment, Enum, EnumMember, Event, Function, Interface, Keyword, Macro, Method, Modifier, Number, Operator, Parameter, Property, String, Struct, Type, TypeParameter, Variable, // Unused below: // Namespace, // Regexp, }; enum class SemanticTokenModifiers { None = 0, // Member integer values must be bit-values as // they can be OR'd together. Abstract = 0x0001, Declaration = 0x0002, Definition = 0x0004, Deprecated = 0x0008, Documentation = 0x0010, Modification = 0x0020, Readonly = 0x0040, // Unused below: // Static, // Async, // DefaultLibrary, }; constexpr SemanticTokenModifiers operator|(SemanticTokenModifiers a, SemanticTokenModifiers b) noexcept { return static_cast<SemanticTokenModifiers>(static_cast<int>(a) | static_cast<int>(b)); } class SemanticTokensBuilder: public frontend::ASTConstVisitor { public: Json build(frontend::SourceUnit const& _sourceUnit, langutil::CharStream const& _charStream); void reset(langutil::CharStream const* _charStream); void encode( langutil::SourceLocation const& _sourceLocation, SemanticTokenType _tokenType, SemanticTokenModifiers _modifiers = SemanticTokenModifiers::None ); bool visit(frontend::ContractDefinition const&) override; bool visit(frontend::ElementaryTypeName const&) override; bool visit(frontend::ElementaryTypeNameExpression const&) override; bool visit(frontend::EnumDefinition const&) override; bool visit(frontend::EnumValue const&) override; bool visit(frontend::ErrorDefinition const&) override; bool visit(frontend::FunctionDefinition const&) override; bool visit(frontend::ModifierDefinition const&) override; void endVisit(frontend::Literal const&) override; void endVisit(frontend::StructuredDocumentation const&) override; void endVisit(frontend::Identifier const&) override; void endVisit(frontend::IdentifierPath const&) override; bool visit(frontend::MemberAccess const&) override; void endVisit(frontend::PragmaDirective const&) override; bool visit(frontend::UserDefinedTypeName const&) override; bool visit(frontend::VariableDeclaration const&) override; private: Json m_encodedTokens; langutil::CharStream const* m_charStream; int m_lastLine; int m_lastStartChar; }; } // end namespace
3,360
C++
.h
106
29.792453
114
0.789929
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,497
Utils.h
ethereum_solidity/libsolidity/lsp/Utils.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 #pragma once #include <liblangutil/SourceLocation.h> #include <libsolidity/ast/ASTForward.h> #include <libsolutil/JSON.h> #include <optional> #include <vector> #if !defined(NDEBUG) #include <fstream> #define lspDebug(message) (std::ofstream("/tmp/solc.log", std::ios::app) << (message) << std::endl) #else #define lspDebug(message) do {} while (0) #endif namespace solidity::langutil { class CharStreamProvider; } namespace solidity::lsp { class FileRepository; std::optional<langutil::LineColumn> parseLineColumn(Json const& _lineColumn); Json toJson(langutil::LineColumn const& _pos); Json toJsonRange(langutil::LineColumn const& _start, langutil::LineColumn const& _end); /// @returns the source location given a source unit name and an LSP Range object, /// or nullopt on failure. std::optional<langutil::SourceLocation> parsePosition( FileRepository const& _fileRepository, std::string const& _sourceUnitName, Json const& _position ); /// @returns the source location given a source unit name and an LSP Range object, /// or nullopt on failure. std::optional<langutil::SourceLocation> parseRange( FileRepository const& _fileRepository, std::string const& _sourceUnitName, Json const& _range ); /// Strips the file:// URI prefix off the given path, if present, /// also taking special care of Windows-drive-letter paths. /// /// So file:///path/to/some/file.txt returns /path/to/some/file.txt, as well as, /// file:///C:/file.txt will return C:/file.txt (forward-slash is okay on Windows). std::string stripFileUriSchemePrefix(std::string const& _path); /// Extracts the resolved declaration of the given expression AST node. /// /// This may for example be the type declaration of an identifier, /// or the type declaration of a structured member identifier. /// /// @returns the resolved type declaration if found, or nullptr otherwise. frontend::Declaration const* referencedDeclaration(frontend::Expression const* _expression); /// @returns the location of the declaration's name, if present, or the location of the complete /// declaration otherwise. If the input declaration is nullptr, std::nullopt is returned instead. std::optional<langutil::SourceLocation> declarationLocation(frontend::Declaration const* _declaration); }
2,944
C++
.h
67
42.402985
103
0.779916
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,498
HandlerBase.h
ethereum_solidity/libsolidity/lsp/HandlerBase.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 #pragma once #include <libsolidity/lsp/FileRepository.h> #include <libsolidity/lsp/LanguageServer.h> #include <liblangutil/SourceLocation.h> #include <liblangutil/CharStreamProvider.h> #include <optional> namespace solidity::lsp { class Transport; /** * Helper base class for implementing handlers. */ class HandlerBase { public: explicit HandlerBase(LanguageServer& _server): m_server{_server} {} Json toRange(langutil::SourceLocation const& _location) const; Json toJson(langutil::SourceLocation const& _location) const; /// @returns source unit name and the line column position as extracted /// from the JSON-RPC parameters. std::pair<std::string, langutil::LineColumn> extractSourceUnitNameAndLineColumn(Json const& _params) const; langutil::CharStreamProvider const& charStreamProvider() const noexcept { return m_server.compilerStack(); } FileRepository& fileRepository() const noexcept { return m_server.fileRepository(); } Transport& client() const noexcept { return m_server.client(); } protected: LanguageServer& m_server; }; }
1,747
C++
.h
42
39.714286
109
0.793613
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,499
Transport.h
ethereum_solidity/libsolidity/lsp/Transport.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 #pragma once #include <libsolutil/Exceptions.h> #include <libsolutil/JSON.h> #include <functional> #include <iosfwd> #include <map> #include <optional> #include <string> #include <string_view> #include <variant> namespace solidity::lsp { using MessageID = Json; enum class TraceValue { Off, Messages, Verbose }; enum class ErrorCode { // Defined by JSON RPC ParseError = -32700, MethodNotFound = -32601, InvalidParams = -32602, InternalError = -32603, // Defined by the protocol. ServerNotInitialized = -32002, RequestFailed = -32803 }; /** * Error exception used to bail out on errors in the LSP function-call handlers. */ class RequestError: public util::Exception { public: explicit RequestError(ErrorCode _code): m_code{_code} { } ErrorCode code() const noexcept { return m_code; } private: ErrorCode m_code; }; /** * Ensures precondition check is valid. * This is supposed to be a recoverable error, that means, if the condition fails to be valid, * an exception is being raised to be thrown out of the current request handlers * of the current LSP's client RPC call and this will cause the current request to fail * with the given error code - but subsequent calls shall be able to continue. */ #define lspRequire(condition, errorCode, errorMessage) \ if (!(condition)) \ { \ BOOST_THROW_EXCEPTION( \ RequestError(errorCode) << \ util::errinfo_comment(errorMessage) \ ); \ } /** * Transport layer API * * The transport layer API is abstracted to make LSP more testable as well as * this way it could be possible to support other transports (HTTP for example) easily. */ class Transport { public: virtual ~Transport() = default; std::optional<Json> receive(); void notify(std::string _method, Json _params); void reply(MessageID _id, Json _result); void error(MessageID _id, ErrorCode _code, std::string _message); virtual bool closed() const noexcept = 0; void trace(std::string _message, Json _extra = Json{}); TraceValue traceValue() const noexcept { return m_logTrace; } void setTrace(TraceValue _value) noexcept { m_logTrace = _value; } private: TraceValue m_logTrace = TraceValue::Off; protected: /// Reads from the transport and parses the headers until the beginning /// of the contents. std::optional<std::map<std::string, std::string>> parseHeaders(); /// Consumes exactly @p _byteCount bytes, as needed for consuming /// the message body from the transport line. virtual std::string readBytes(size_t _byteCount) = 0; // Mimics std::getline() on this Transport API. virtual std::string getline() = 0; /// Writes the given payload @p _data to transport. /// This call may or may not buffer. virtual void writeBytes(std::string_view _data) = 0; /// Ensures transport output is flushed. virtual void flushOutput() = 0; /// Sends an arbitrary raw message to the client. /// /// Used by the notify/reply/error function family. virtual void send(Json _message, MessageID _id = Json{}); }; /** * LSP Transport using JSON-RPC over iostreams. */ class IOStreamTransport: public Transport { public: /// Constructs a standard stream transport layer. /// /// @param _in for example std::cin (stdin) /// @param _out for example std::cout (stdout) IOStreamTransport(std::istream& _in, std::ostream& _out); bool closed() const noexcept override; protected: std::string readBytes(size_t _byteCount) override; std::string getline() override; void writeBytes(std::string_view _data) override; void flushOutput() override; private: std::istream& m_input; std::ostream& m_output; }; /** * Standard I/O transport Layer utilizing stdin/stdout for communication. */ class StdioTransport: public Transport { public: StdioTransport(); bool closed() const noexcept override; protected: std::string readBytes(size_t _byteCount) override; std::string getline() override; void writeBytes(std::string_view _data) override; void flushOutput() override; }; }
4,651
C++
.h
148
29.493243
94
0.754307
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,500
FileRepository.h
ethereum_solidity/libsolidity/lsp/FileRepository.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 #pragma once #include <libsolidity/interface/FileReader.h> #include <libsolutil/Result.h> #include <string> #include <map> namespace solidity::lsp { class FileRepository { public: FileRepository(boost::filesystem::path _basePath, std::vector<boost::filesystem::path> _includePaths); std::vector<boost::filesystem::path> const& includePaths() const noexcept { return m_includePaths; } void setIncludePaths(std::vector<boost::filesystem::path> _paths); boost::filesystem::path const& basePath() const { return m_basePath; } /// Translates a compiler-internal source unit name to an LSP client path. std::string sourceUnitNameToUri(std::string const& _sourceUnitName) const; /// Translates an LSP file URI into a compiler-internal source unit name. std::string uriToSourceUnitName(std::string const& _uri) const; /// @returns all sources by their compiler-internal source unit name. StringMap const& sourceUnits() const noexcept { return m_sourceCodes; } /// Changes the source identified by the LSP client path _uri to _text. void setSourceByUri(std::string const& _uri, std::string _text); void setSourceUnits(StringMap _sources); frontend::ReadCallback::Result readFile(std::string const& _kind, std::string const& _sourceUnitName); frontend::ReadCallback::Callback reader() { return [this](std::string const& _kind, std::string const& _path) { return readFile(_kind, _path); }; } util::Result<boost::filesystem::path> tryResolvePath(std::string const& _sourceUnitName) const; private: /// Base path without URI scheme. boost::filesystem::path m_basePath; /// Additional directories used for resolving relative paths in imports. std::vector<boost::filesystem::path> m_includePaths; /// Mapping of source unit names to their URIs as understood by the client. StringMap m_sourceUnitNamesToUri; /// Mapping of source unit names to their file content. StringMap m_sourceCodes; }; }
2,608
C++
.h
54
46.203704
103
0.776638
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,501
DocumentHoverHandler.h
ethereum_solidity/libsolidity/lsp/DocumentHoverHandler.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 #pragma once #include <libsolidity/lsp/HandlerBase.h> namespace solidity::lsp { class DocumentHoverHandler: public HandlerBase { public: using HandlerBase::HandlerBase; void operator()(MessageID, Json const&); }; }
906
C++
.h
25
34.44
69
0.795195
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,502
LanguageServer.h
ethereum_solidity/libsolidity/lsp/LanguageServer.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 #pragma once #include <libsolidity/lsp/Transport.h> #include <libsolidity/lsp/FileRepository.h> #include <libsolidity/interface/CompilerStack.h> #include <libsolidity/interface/FileReader.h> #include <libsolutil/JSON.h> #include <functional> #include <map> #include <optional> #include <string> #include <vector> namespace solidity::lsp { class RenameSymbol; enum class ErrorCode; /** * Enum to mandate what files to take into consideration for source code analysis. */ enum class FileLoadStrategy { /// Takes only those files into consideration that are explicitly opened and those /// that have been directly or indirectly imported. DirectlyOpenedAndOnImported = 0, /// Takes all Solidity (.sol) files within the project root into account. /// Symbolic links will be followed, even if they lead outside of the project directory /// (`--allowed-paths` is currently ignored by the LSP). /// /// This resembles the closest what other LSPs should be doing already. ProjectDirectory = 1, }; /** * Solidity Language Server, managing one LSP client. * This implements a subset of LSP version 3.16 that can be found at: * https://microsoft.github.io/language-server-protocol/specifications/specification-3-16/ */ class LanguageServer { public: /// @param _transport Customizable transport layer. explicit LanguageServer(Transport& _transport); /// Re-compiles the project and updates the diagnostics pushed to the client. void compileAndUpdateDiagnostics(); /// Loops over incoming messages via the transport layer until shutdown condition is met. /// /// The standard shutdown condition is when the maximum number of consecutive failures /// has been exceeded. /// /// @return boolean indicating normal or abnormal termination. bool run(); FileRepository& fileRepository() noexcept { return m_fileRepository; } Transport& client() noexcept { return m_client; } std::tuple<frontend::ASTNode const*, int> astNodeAndOffsetAtSourceLocation(std::string const& _sourceUnitName, langutil::LineColumn const& _filePos); frontend::ASTNode const* astNodeAtSourceLocation(std::string const& _sourceUnitName, langutil::LineColumn const& _filePos); frontend::CompilerStack const& compilerStack() const noexcept { return m_compilerStack; } private: /// Checks if the server is initialized (to be used by messages that need it to be initialized). /// Reports an error and returns false if not. void requireServerInitialized(); void handleInitialize(MessageID _id, Json const& _args); void handleInitialized(MessageID _id, Json const& _args); void handleWorkspaceDidChangeConfiguration(Json const& _args); void setTrace(Json const& _args); void handleTextDocumentDidOpen(Json const& _args); void handleTextDocumentDidChange(Json const& _args); void handleTextDocumentDidClose(Json const& _args); void handleRename(Json const& _args); void handleGotoDefinition(MessageID _id, Json const& _args); void semanticTokensFull(MessageID _id, Json const& _args); /// Invoked when the server user-supplied configuration changes (initiated by the client). void changeConfiguration(Json const&); /// Compile everything until after analysis phase. void compile(); std::vector<boost::filesystem::path> allSolidityFilesFromProject() const; using MessageHandler = std::function<void(MessageID, Json const&)>; Json toRange(langutil::SourceLocation const& _location); Json toJson(langutil::SourceLocation const& _location); // LSP related member fields enum class State { Started, Initialized, ShutdownRequested, ExitRequested, ExitWithoutShutdown }; State m_state = State::Started; Transport& m_client; std::map<std::string, MessageHandler> m_handlers; /// Set of files (names in URI form) known to be open by the client. std::set<std::string> m_openFiles; /// Set of source unit names for which we sent diagnostics to the client in the last iteration. std::set<std::string> m_nonemptyDiagnostics; FileRepository m_fileRepository; FileLoadStrategy m_fileLoadStrategy = FileLoadStrategy::ProjectDirectory; frontend::CompilerStack m_compilerStack; /// User-supplied custom configuration settings (such as EVM version). Json m_settingsObject; }; }
4,881
C++
.h
106
44.066038
150
0.787911
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,503
GotoDefinition.h
ethereum_solidity/libsolidity/lsp/GotoDefinition.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 #include <libsolidity/lsp/HandlerBase.h> namespace solidity::lsp { class GotoDefinition: public HandlerBase { public: explicit GotoDefinition(LanguageServer& _server): HandlerBase(_server) {} void operator()(MessageID, Json const&); }; }
929
C++
.h
24
36.875
74
0.791759
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,504
RenameSymbol.h
ethereum_solidity/libsolidity/lsp/RenameSymbol.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 #include <libsolidity/lsp/HandlerBase.h> #include <libsolidity/ast/AST.h> #include <libsolidity/ast/ASTVisitor.h> namespace solidity::lsp { class RenameSymbol: public HandlerBase { public: explicit RenameSymbol(LanguageServer& _server): HandlerBase(_server) {} void operator()(MessageID, Json const&); protected: // Nested class because otherwise `RenameSymbol` couldn't be easily used // with LanguageServer::m_handlers as `ASTConstVisitor` deletes required // c'tors struct Visitor: public frontend::ASTConstVisitor { explicit Visitor(RenameSymbol& _outer): m_outer(_outer) {} void endVisit(frontend::ImportDirective const& _node) override; void endVisit(frontend::MemberAccess const& _node) override; void endVisit(frontend::Identifier const& _node) override; void endVisit(frontend::IdentifierPath const& _node) override; void endVisit(frontend::FunctionCall const& _node) override; void endVisit(frontend::InlineAssembly const& _node) override; void endVisit(frontend::ContractDefinition const& _node) override { handleGenericDeclaration(_node); } void endVisit(frontend::StructDefinition const& _node) override { handleGenericDeclaration(_node); } void endVisit(frontend::EnumDefinition const& _node) override { handleGenericDeclaration(_node); } void endVisit(frontend::EnumValue const& _node) override { handleGenericDeclaration(_node); } void endVisit(frontend::UserDefinedValueTypeDefinition const& _node) override { handleGenericDeclaration(_node); } void endVisit(frontend::VariableDeclaration const& _node) override { handleGenericDeclaration(_node); } void endVisit(frontend::FunctionDefinition const& _node) override { handleGenericDeclaration(_node); } void endVisit(frontend::ModifierDefinition const& _node) override { handleGenericDeclaration(_node); } void endVisit(frontend::EventDefinition const& _node) override { handleGenericDeclaration(_node); } void endVisit(frontend::ErrorDefinition const& _node) override { handleGenericDeclaration(_node); } bool handleGenericDeclaration(frontend::Declaration const& _declaration) { if ( m_outer.m_symbolName == _declaration.name() && *m_outer.m_declarationToRename == _declaration ) { m_outer.m_locations.emplace_back(_declaration.nameLocation()); return true; } return false; } private: RenameSymbol& m_outer; }; void extractNameAndDeclaration(frontend::ASTNode const& _node, int _cursorBytePosition); void extractNameAndDeclaration(frontend::IdentifierPath const& _identifierPath, int _cursorBytePosition); void extractNameAndDeclaration(frontend::ImportDirective const& _importDirective, int _cursorBytePosition); void extractNameAndDeclaration(frontend::FunctionCall const& _functionCall, int _cursorBytePosition); void extractNameAndDeclaration(frontend::InlineAssembly const& _inlineAssembly, int _cursorBytePosition); // Node to rename frontend::Declaration const* m_declarationToRename = nullptr; // Original name frontend::ASTString m_symbolName = {}; // SourceUnits to search & replace symbol in std::set<frontend::SourceUnit const*, frontend::ASTNode::CompareByID> m_sourceUnits = {}; // Source locations that need to be replaced std::vector<langutil::SourceLocation> m_locations = {}; }; }
4,028
C++
.h
107
34.869159
108
0.779483
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,507
DocStringParser.h
ethereum_solidity/libsolidity/parsing/DocStringParser.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, 2015 * Parses a given docstring into pieces introduced by tags. */ #pragma once #include <libsolidity/ast/ASTAnnotations.h> #include <liblangutil/SourceLocation.h> #include <string> namespace solidity::langutil { class ErrorReporter; } namespace solidity::frontend { class StructuredDocumentation; class DocStringParser { public: /// @param _documentedNode the node whose documentation is parsed. DocStringParser(StructuredDocumentation const& _documentedNode, langutil::ErrorReporter& _errorReporter): m_node(_documentedNode), m_errorReporter(_errorReporter) {} std::multimap<std::string, DocTag> parse(); private: using iter = std::string::const_iterator; iter parseDocTagLine(iter _pos, iter _end, bool _appending); iter parseDocTagParam(iter _pos, iter _end); /// Parses the doc tag named @a _tag, adds it to m_docTags and returns the position /// after the tag. iter parseDocTag(iter _pos, iter _end, std::string const& _tag); /// Creates and inserts a new tag and adjusts m_lastTag. void newTag(std::string const& _tagName); StructuredDocumentation const& m_node; langutil::ErrorReporter& m_errorReporter; /// Mapping tag name -> content. std::multimap<std::string, DocTag> m_docTags; DocTag* m_lastTag = nullptr; }; }
2,006
C++
.h
55
34.545455
106
0.77686
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,508
ArraySlicePredicate.h
ethereum_solidity/libsolidity/formal/ArraySlicePredicate.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 #include <libsolidity/formal/EncodingContext.h> #include <libsolidity/formal/Predicate.h> #include <libsolidity/formal/SymbolicVariables.h> #include <libsmtutil/Sorts.h> #include <vector> namespace solidity::frontend { /** * Contains the set of rules to compute an array slice. * Rules: * 1. end > start => ArraySliceHeader(a, b, start, end, 0) * 2. ArraySliceHeader(a, b, start, end, i) && i >= (end - start) => ArraySlice(a, b, start, end) * 3. ArraySliceHeader(a, b, start, end, i) && i >= 0 && i < (end - start) => ArraySliceLoop(a, b, start, end, i) * 4. ArraySliceLoop(a, b, start, end, i) && b[i] = a[start + i] => ArraySliceHeader(a, b, start, end, i + 1) * * The rule to be used by CHC is ArraySlice(a, b, start, end). */ struct ArraySlicePredicate { /// Contains the predicates and rules created to compute /// array slices for a given sort. struct SliceData { std::vector<Predicate const*> predicates; std::vector<smtutil::Expression> rules; }; /// @returns a flag representing whether the array slice predicates had already been created before for this sort, /// and the corresponding slice data. static std::pair<bool, SliceData const&> create(smtutil::SortPointer _sort, smt::EncodingContext& _context); static void reset() { m_slicePredicates.clear(); } private: /// Maps a unique sort name to its slice data. static std::map<std::string, SliceData> m_slicePredicates; }; }
2,108
C++
.h
49
41.040816
115
0.739003
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,510
BMC.h
ethereum_solidity/libsolidity/formal/BMC.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 /** * Class that implements an SMT-based Bounded Model Checker (BMC). * Traverses the AST such that: * - Loops are unrolled * - Internal function calls are inlined * Creates verification targets for: * - Underflow/Overflow * - Constant conditions * - Assertions */ #pragma once #include <libsolidity/formal/EncodingContext.h> #include <libsolidity/formal/ModelCheckerSettings.h> #include <libsolidity/formal/SMTEncoder.h> #include <libsolidity/interface/ReadFile.h> #include <libsmtutil/BMCSolverInterface.h> #include <liblangutil/UniqueErrorReporter.h> #include <set> #include <string> #include <vector> #include <stack> using solidity::util::h256; namespace solidity::langutil { class ErrorReporter; struct ErrorId; struct SourceLocation; } namespace solidity::frontend { class BMC: public SMTEncoder { public: BMC( smt::EncodingContext& _context, langutil::UniqueErrorReporter& _errorReporter, langutil::UniqueErrorReporter& _unsupportedErrorReporter, langutil::ErrorReporter& _provedSafeReporter, std::map<h256, std::string> const& _smtlib2Responses, ReadCallback::Callback const& _smtCallback, ModelCheckerSettings _settings, langutil::CharStreamProvider const& _charStreamProvider ); void analyze(SourceUnit const& _sources, std::map<ASTNode const*, std::set<VerificationTargetType>, smt::EncodingContext::IdCompare> _solvedTargets); /// This is used if the SMT solver is not directly linked into this binary. /// @returns a list of inputs to the SMT solver that were not part of the argument to /// the constructor. std::vector<std::string> unhandledQueries() { return m_interface->unhandledQueries(); } /// @returns true if _funCall should be inlined, otherwise false. /// @param _scopeContract The contract that contains the current function being analyzed. /// @param _contextContract The most derived contract, currently being analyzed. static bool shouldInlineFunctionCall( FunctionCall const& _funCall, ContractDefinition const* _scopeContract, ContractDefinition const* _contextContract ); private: /// AST visitors. /// Only nodes that lead to verification targets being built /// or checked are visited. //@{ bool visit(ContractDefinition const& _node) override; void endVisit(ContractDefinition const& _node) override; bool visit(FunctionDefinition const& _node) override; void endVisit(FunctionDefinition const& _node) override; bool visit(IfStatement const& _node) override; bool visit(Conditional const& _node) override; bool visit(WhileStatement const& _node) override; bool visit(ForStatement const& _node) override; void endVisit(UnaryOperation const& _node) override; void endVisit(BinaryOperation const& _node) override; void endVisit(FunctionCall const& _node) override; void endVisit(Return const& _node) override; bool visit(TryStatement const& _node) override; bool visit(Break const& _node) override; bool visit(Continue const& _node) override; //@} /// Visitor helpers. //@{ void visitAssert(FunctionCall const& _funCall); void visitRequire(FunctionCall const& _funCall); void visitAddMulMod(FunctionCall const& _funCall) override; void assignment(smt::SymbolicVariable& _symVar, smtutil::Expression const& _value) override; /// Visits the FunctionDefinition of the called function /// if available and inlines the return value. void inlineFunctionCall(FunctionCall const& _funCall); void inlineFunctionCall( FunctionDefinition const* _funDef, Expression const& _callStackExpr, std::optional<Expression const*> _calledExpr, std::vector<Expression const*> const& _arguments ); /// Inlines if the function call is internal or external to `this`. /// Erases knowledge about state variables if external. void internalOrExternalFunctionCall(FunctionCall const& _funCall); /// Creates underflow/overflow verification targets. std::pair<smtutil::Expression, smtutil::Expression> arithmeticOperation( Token _op, smtutil::Expression const& _left, smtutil::Expression const& _right, Type const* _commonType, Expression const& _expression ) override; void reset(); std::pair<std::vector<smtutil::Expression>, std::vector<std::string>> modelExpressions(); //@} /// Verification targets. //@{ struct BMCVerificationTarget: VerificationTarget { Expression const* expression; std::vector<CallStackEntry> callStack; std::pair<std::vector<smtutil::Expression>, std::vector<std::string>> modelExpressions; friend bool operator<(BMCVerificationTarget const& _a, BMCVerificationTarget const& _b) { if (_a.expression->id() == _b.expression->id()) return _a.type < _b.type; else return _a.expression->id() < _b.expression->id(); } }; std::string targetDescription(BMCVerificationTarget const& _target); void checkVerificationTargets(); void checkVerificationTarget(BMCVerificationTarget& _target); void checkConstantCondition(BMCVerificationTarget& _target); void checkUnderflow(BMCVerificationTarget& _target); void checkOverflow(BMCVerificationTarget& _target); void checkDivByZero(BMCVerificationTarget& _target); void checkBalance(BMCVerificationTarget& _target); void checkAssert(BMCVerificationTarget& _target); void addVerificationTarget( VerificationTargetType _type, smtutil::Expression const& _value, Expression const* _expression ); //@} /// Solver related. //@{ /// Check that a condition can be satisfied. void checkCondition( BMCVerificationTarget const& _target, smtutil::Expression _condition, std::vector<CallStackEntry> const& _callStack, std::pair<std::vector<smtutil::Expression>, std::vector<std::string>> const& _modelExpressions, langutil::SourceLocation const& _location, langutil::ErrorId _errorHappens, langutil::ErrorId _errorMightHappen, std::string const& _additionalValueName = "", smtutil::Expression const* _additionalValue = nullptr ); /// Checks that a boolean condition is not constant. Do not warn if the expression /// is a literal constant. void checkBooleanNotConstant( Expression const& _condition, smtutil::Expression const& _constraints, smtutil::Expression const& _value, std::vector<CallStackEntry> const& _callStack ); std::pair<smtutil::CheckResult, std::vector<std::string>> checkSatisfiableAndGenerateModel(std::vector<smtutil::Expression> const& _expressionsToEvaluate); smtutil::CheckResult checkSatisfiable(); //@} smtutil::Expression mergeVariablesFromLoopCheckpoints(); bool isInsideLoop() const; std::unique_ptr<smtutil::BMCSolverInterface> m_interface; /// Flags used for better warning messages. bool m_loopExecutionHappened = false; bool m_externalFunctionCallHappened = false; std::vector<BMCVerificationTarget> m_verificationTargets; /// Targets proved safe by this engine. std::map<ASTNode const*, std::set<BMCVerificationTarget>, smt::EncodingContext::IdCompare> m_safeTargets; /// Targets that were already proven before this engine started. std::map<ASTNode const*, std::set<VerificationTargetType>, smt::EncodingContext::IdCompare> m_solvedTargets; /// Number of verification conditions that could not be proved. size_t m_unprovedAmt = 0; enum class LoopControlKind { Continue, Break }; // Current path conditions and SSA indices for break or continue statement struct LoopControl { LoopControlKind kind; smtutil::Expression pathConditions; VariableIndices variableIndices; }; // Loop control statements for every loop std::stack<std::vector<LoopControl>> m_loopCheckpoints; }; }
8,192
C++
.h
204
37.843137
150
0.785184
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,511
EldaricaCHCSmtLib2Interface.h
ethereum_solidity/libsolidity/formal/EldaricaCHCSmtLib2Interface.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 #pragma once #include <libsmtutil/CHCSmtLib2Interface.h> namespace solidity::frontend::smt { class EldaricaCHCSmtLib2Interface: public smtutil::CHCSmtLib2Interface { public: EldaricaCHCSmtLib2Interface( frontend::ReadCallback::Callback _smtCallback, std::optional<unsigned int> _queryTimeout, bool computeInvariants ); private: std::string querySolver(std::string const& _input) override; bool m_computeInvariants; }; }
1,122
C++
.h
31
34.193548
70
0.803885
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,512
Cvc5SMTLib2Interface.h
ethereum_solidity/libsolidity/formal/Cvc5SMTLib2Interface.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 #pragma once #include <libsmtutil/SMTLib2Interface.h> namespace solidity::frontend::smt { class Cvc5SMTLib2Interface: public smtutil::SMTLib2Interface { public: explicit Cvc5SMTLib2Interface( frontend::ReadCallback::Callback _smtCallback = {}, std::optional<unsigned> _queryTimeout = {} ); private: void setupSmtCallback() override; }; }
1,035
C++
.h
29
33.793103
69
0.793587
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,514
Z3SMTLib2Interface.h
ethereum_solidity/libsolidity/formal/Z3SMTLib2Interface.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 #pragma once #include <libsmtutil/SMTLib2Interface.h> namespace solidity::frontend::smt { class Z3SMTLib2Interface: public smtutil::SMTLib2Interface { public: explicit Z3SMTLib2Interface( frontend::ReadCallback::Callback _smtCallback = {}, std::optional<unsigned> _queryTimeout = {} ); private: void setupSmtCallback() override; std::string querySolver(std::string const& _query) override; }; }
1,093
C++
.h
30
34.533333
69
0.791469
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,515
Z3CHCSmtLib2Interface.h
ethereum_solidity/libsolidity/formal/Z3CHCSmtLib2Interface.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 #pragma once #include <libsmtutil/CHCSmtLib2Interface.h> namespace solidity::frontend::smt { class Z3CHCSmtLib2Interface: public smtutil::CHCSmtLib2Interface { public: Z3CHCSmtLib2Interface( frontend::ReadCallback::Callback _smtCallback, std::optional<unsigned int> _queryTimeout, bool _computeInvariants ); private: void setupSmtCallback(bool _disablePreprocessing); CHCSolverInterface::QueryResult query(smtutil::Expression const& _expr) override; CHCSolverInterface::CexGraph graphFromZ3Answer(std::string const& _proof) const; static CHCSolverInterface::CexGraph graphFromSMTLib2Expression( smtutil::SMTLib2Expression const& _proof, ScopedParser& _context ); bool m_computeInvariants; }; }
1,407
C++
.h
37
35.891892
82
0.810612
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,518
ModelCheckerSettings.h
ethereum_solidity/libsolidity/formal/ModelCheckerSettings.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 #pragma once #include <libsmtutil/SolverInterface.h> #include <optional> #include <set> namespace solidity::frontend { struct ModelCheckerContracts { /// By default all contracts are analyzed. static ModelCheckerContracts Default() { return {}; } /// Parses a string of the form <path>:<contract>,<path>:contract,... /// and returns nullopt if a path or contract name is empty. static std::optional<ModelCheckerContracts> fromString(std::string const& _contracts); /// @returns true if all contracts should be analyzed. bool isDefault() const { return contracts.empty(); } bool has(std::string const& _source) const { return contracts.count(_source); } bool has(std::string const& _source, std::string const& _contract) const { return has(_source) && contracts.at(_source).count(_contract); } bool operator!=(ModelCheckerContracts const& _other) const noexcept { return !(*this == _other); } bool operator==(ModelCheckerContracts const& _other) const noexcept { return contracts == _other.contracts; } /// Represents which contracts should be analyzed by the SMTChecker /// as the most derived. /// The key is the source file. If the map is empty, all sources must be analyzed. /// For each source, contracts[source] represents the contracts in that source /// that should be analyzed. /// If the set of contracts is empty, all contracts in that source should be analyzed. std::map<std::string, std::set<std::string>> contracts; }; struct ModelCheckerEngine { bool bmc = false; bool chc = false; static constexpr ModelCheckerEngine All() { return {true, true}; } static constexpr ModelCheckerEngine BMC() { return {true, false}; } static constexpr ModelCheckerEngine CHC() { return {false, true}; } static constexpr ModelCheckerEngine None() { return {false, false}; } bool none() const { return !any(); } bool any() const { return bmc || chc; } bool all() const { return bmc && chc; } static std::optional<ModelCheckerEngine> fromString(std::string const& _engine) { static std::map<std::string, ModelCheckerEngine> engineMap{ {"all", All()}, {"bmc", BMC()}, {"chc", CHC()}, {"none", None()} }; if (engineMap.count(_engine)) return engineMap.at(_engine); return {}; } bool operator!=(ModelCheckerEngine const& _other) const noexcept { return !(*this == _other); } bool operator==(ModelCheckerEngine const& _other) const noexcept { return bmc == _other.bmc && chc == _other.chc; } }; enum class InvariantType { Contract, Reentrancy }; struct ModelCheckerInvariants { /// Adds the default targets, that is, all except underflow and overflow. static ModelCheckerInvariants Default() { return *fromString("default"); } /// Adds all targets, including underflow and overflow. static ModelCheckerInvariants All() { return *fromString("all"); } static ModelCheckerInvariants None() { return {{}}; } static std::optional<ModelCheckerInvariants> fromString(std::string const& _invs); bool has(InvariantType _inv) const { return invariants.count(_inv); } /// @returns true if the @p _target is valid, /// and false otherwise. bool setFromString(std::string const& _target); static std::map<std::string, InvariantType> const validInvariants; bool operator!=(ModelCheckerInvariants const& _other) const noexcept { return !(*this == _other); } bool operator==(ModelCheckerInvariants const& _other) const noexcept { return invariants == _other.invariants; } std::set<InvariantType> invariants; }; enum class VerificationTargetType { ConstantCondition, Underflow, Overflow, DivByZero, Balance, Assert, PopEmptyArray, OutOfBounds }; struct ModelCheckerTargets { /// Adds the default targets, that is, all except underflow and overflow. static ModelCheckerTargets Default() { return *fromString("default"); } /// Adds all targets, including underflow and overflow. static ModelCheckerTargets All() { return *fromString("all"); } static std::optional<ModelCheckerTargets> fromString(std::string const& _targets); bool has(VerificationTargetType _type) const { return targets.count(_type); } /// @returns true if the @p _target is valid, /// and false otherwise. bool setFromString(std::string const& _target); static std::map<std::string, VerificationTargetType> const targetStrings; static std::map<VerificationTargetType, std::string> const targetTypeToString; bool operator!=(ModelCheckerTargets const& _other) const noexcept { return !(*this == _other); } bool operator==(ModelCheckerTargets const& _other) const noexcept { return targets == _other.targets; } std::set<VerificationTargetType> targets; }; struct ModelCheckerExtCalls { enum class Mode { UNTRUSTED, TRUSTED }; Mode mode = Mode::UNTRUSTED; static std::optional<ModelCheckerExtCalls> fromString(std::string const& _mode); bool isTrusted() const { return mode == Mode::TRUSTED; } }; struct ModelCheckerSettings { std::optional<unsigned> bmcLoopIterations; ModelCheckerContracts contracts = ModelCheckerContracts::Default(); /// Currently division and modulo are replaced by multiplication with slack vars, such that /// a / b <=> a = b * k + m /// where k and m are slack variables. /// This is the default because Spacer prefers that over precise / and mod. /// This option allows disabling this mechanism since other solvers /// might prefer the precise encoding. bool divModNoSlacks = false; ModelCheckerEngine engine = ModelCheckerEngine::None(); ModelCheckerExtCalls externalCalls = {}; ModelCheckerInvariants invariants = ModelCheckerInvariants::Default(); bool printQuery = false; bool showProvedSafe = false; bool showUnproved = false; bool showUnsupported = false; smtutil::SMTSolverChoice solvers = smtutil::SMTSolverChoice::Z3(); ModelCheckerTargets targets = ModelCheckerTargets::Default(); std::optional<unsigned> timeout; // in milliseconds bool operator!=(ModelCheckerSettings const& _other) const noexcept { return !(*this == _other); } bool operator==(ModelCheckerSettings const& _other) const noexcept { return bmcLoopIterations == _other.bmcLoopIterations && contracts == _other.contracts && divModNoSlacks == _other.divModNoSlacks && engine == _other.engine && externalCalls.mode == _other.externalCalls.mode && invariants == _other.invariants && printQuery == _other.printQuery && showProvedSafe == _other.showProvedSafe && showUnproved == _other.showUnproved && showUnsupported == _other.showUnsupported && solvers == _other.solvers && targets == _other.targets && timeout == _other.timeout; } }; }
7,255
C++
.h
158
43.563291
133
0.751099
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,519
CHC.h
ethereum_solidity/libsolidity/formal/CHC.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 /** * Model checker based on Constrained Horn Clauses. * * A Solidity contract's CFG is encoded into a system of Horn clauses where * each block has a predicate and edges are rules. * * The entry block is the constructor which has no in-edges. * The constructor has one out-edge to an artificial block named _Interface_ * which has in/out-edges from/to all public functions. * * Loop invariants for Interface -> Interface' are state invariants. */ #pragma once #include <libsolidity/formal/ModelCheckerSettings.h> #include <libsolidity/formal/Predicate.h> #include <libsolidity/formal/SMTEncoder.h> #include <libsolidity/interface/ReadFile.h> #include <libsmtutil/CHCSolverInterface.h> #include <liblangutil/SourceLocation.h> #include <liblangutil/UniqueErrorReporter.h> #include <boost/algorithm/string/join.hpp> #include <map> #include <optional> #include <set> namespace solidity::frontend { class CHC: public SMTEncoder { public: CHC( smt::EncodingContext& _context, langutil::UniqueErrorReporter& _errorReporter, langutil::UniqueErrorReporter& _unsupportedErrorReporter, langutil::ErrorReporter& _provedSafeReporter, std::map<util::h256, std::string> const& _smtlib2Responses, ReadCallback::Callback const& _smtCallback, ModelCheckerSettings _settings, langutil::CharStreamProvider const& _charStreamProvider ); void analyze(SourceUnit const& _sources); struct CHCVerificationTarget: VerificationTarget { unsigned const errorId; ASTNode const* const errorNode; friend bool operator<(CHCVerificationTarget const& _a, CHCVerificationTarget const& _b) { return _a.errorId < _b.errorId; } }; struct SafeTargetsCompare { bool operator()(CHCVerificationTarget const & _lhs, CHCVerificationTarget const & _rhs) const { if (_lhs.errorNode->id() == _rhs.errorNode->id()) return _lhs.type < _rhs.type; else return _lhs.errorNode->id() == _rhs.errorNode->id(); } }; struct ReportTargetInfo { langutil::ErrorId error; langutil::SourceLocation location; std::string message; }; std::map<ASTNode const*, std::set<CHCVerificationTarget, SafeTargetsCompare>, smt::EncodingContext::IdCompare> const& safeTargets() const { return m_safeTargets; } std::map<ASTNode const*, std::map<VerificationTargetType, ReportTargetInfo>, smt::EncodingContext::IdCompare> const& unsafeTargets() const { return m_unsafeTargets; } /// This is used if the Horn solver is not directly linked into this binary. /// @returns a list of inputs to the Horn solver that were not part of the argument to /// the constructor. std::vector<std::string> unhandledQueries() const; enum class CHCNatspecOption { AbstractFunctionNondet }; private: /// Visitor functions. //@{ bool visit(ContractDefinition const& _node) override; void endVisit(ContractDefinition const& _node) override; bool visit(FunctionDefinition const& _node) override; void endVisit(FunctionDefinition const& _node) override; bool visit(Block const& _block) override; void endVisit(Block const& _block) override; bool visit(IfStatement const& _node) override; bool visit(WhileStatement const&) override; bool visit(ForStatement const&) override; void endVisit(ForStatement const&) override; void endVisit(FunctionCall const& _node) override; void endVisit(BinaryOperation const& _op) override; void endVisit(UnaryOperation const& _op) override; void endVisit(Break const& _node) override; void endVisit(Continue const& _node) override; void endVisit(IndexRangeAccess const& _node) override; void endVisit(Return const& _node) override; bool visit(TryCatchClause const&) override; void endVisit(TryCatchClause const&) override; bool visit(TryStatement const& _node) override; void pushInlineFrame(CallableDeclaration const& _callable) override; void popInlineFrame(CallableDeclaration const& _callable) override; void visitAssert(FunctionCall const& _funCall); void visitPublicGetter(FunctionCall const& _funCall) override; void visitAddMulMod(FunctionCall const& _funCall) override; void visitDeployment(FunctionCall const& _funCall); void internalFunctionCall(FunctionCall const& _funCall); void internalFunctionCall( FunctionDefinition const* _funDef, std::optional<Expression const*> _boundArgumentCall, FunctionType const* _funType, std::vector<Expression const*> const& _arguments, smtutil::Expression _contractAddressValue ); void externalFunctionCall(FunctionCall const& _funCall); void externalFunctionCallToTrustedCode(FunctionCall const& _funCall); void addNondetCalls(ContractDefinition const& _contract); void nondetCall(ContractDefinition const& _contract, VariableDeclaration const& _var); void unknownFunctionCall(FunctionCall const& _funCall); void makeArrayPopVerificationTarget(FunctionCall const& _arrayPop) override; void makeOutOfBoundsVerificationTarget(IndexAccess const& _access) override; /// Creates underflow/overflow verification targets. std::pair<smtutil::Expression, smtutil::Expression> arithmeticOperation( Token _op, smtutil::Expression const& _left, smtutil::Expression const& _right, Type const* _commonType, Expression const& _expression ) override; //@} /// Helpers. //@{ void resetSourceAnalysis(); void resetContractAnalysis(); void eraseKnowledge(); void clearIndices(ContractDefinition const* _contract, FunctionDefinition const* _function = nullptr) override; void setCurrentBlock(Predicate const& _block); std::set<unsigned> transactionVerificationTargetsIds(ASTNode const* _txRoot); bool usesStaticCall(FunctionDefinition const* _funDef, FunctionType const* _funType); bool usesStaticCall(FunctionCall const& _funCall); //@} /// SMT Natspec and abstraction helpers. //@{ /// @returns a CHCNatspecOption enum if _option is a valid SMTChecker Natspec value /// or nullopt otherwise. static std::optional<CHCNatspecOption> natspecOptionFromString(std::string const& _option); /// @returns which SMTChecker options are enabled by @a _function's Natspec via /// `@custom:smtchecker <option>` or nullopt if none is used. std::set<CHCNatspecOption> smtNatspecTags(FunctionDefinition const& _function); /// @returns true if _function is Natspec annotated to be abstracted by /// nondeterministic values. bool abstractAsNondet(FunctionDefinition const& _function); /// @returns true if external calls should be considered trusted. /// If that's the case, their code is used if available at compile time. bool encodeExternalCallsAsTrusted(); //@} /// Sort helpers. //@{ smtutil::SortPointer sort(FunctionDefinition const& _function); smtutil::SortPointer sort(ASTNode const* _block); //@} /// Predicate helpers. //@{ /// @returns a new block of given _sort and _name. Predicate const* createSymbolicBlock(smtutil::SortPointer _sort, std::string const& _name, PredicateType _predType, ASTNode const* _node = nullptr, ContractDefinition const* _contractContext = nullptr); /// Creates summary predicates for all functions of all contracts /// in a given _source. void defineInterfacesAndSummaries(SourceUnit const& _source); /// Creates the rule /// summary_function \land transaction_entry_constraints => external_summary_function /// This is needed to add these transaction entry constraints which include /// potential balance increase by external means, for example. void defineExternalFunctionInterface(FunctionDefinition const& _function, ContractDefinition const& _contract); /// Creates a CHC system that, for a given contract, /// - initializes its state variables (as 0 or given value, if any). /// - "calls" the explicit constructor function of the contract, if any. void defineContractInitializer(ContractDefinition const& _contract, ContractDefinition const& _contractContext); /// Interface predicate over current variables. smtutil::Expression interface(); smtutil::Expression interface(ContractDefinition const& _contract); /// Error predicate over current variables. smtutil::Expression error(); /// Creates a block for the given _node. Predicate const* createBlock(ASTNode const* _node, PredicateType _predType, std::string const& _prefix = ""); /// Creates a call block for the given function _function from contract _contract. /// The contract is needed here because of inheritance. /// There are different types of summaries, where the most common is FunctionSummary, /// but other summaries are also used for internal and external function calls. Predicate const* createSummaryBlock( FunctionDefinition const& _function, ContractDefinition const& _contract, PredicateType _type = PredicateType::FunctionSummary ); /// @returns a block related to @a _contract's constructor. Predicate const* createConstructorBlock(ContractDefinition const& _contract, std::string const& _prefix); /// Creates a new error block to be used by an assertion. /// Also registers the predicate. void createErrorBlock(); void connectBlocks(smtutil::Expression const& _from, smtutil::Expression const& _to, smtutil::Expression const& _constraints = smtutil::Expression(true)); /// @returns The initial constraints that set up the beginning of a function. smtutil::Expression initialConstraints(ContractDefinition const& _contract, FunctionDefinition const* _function = nullptr); /// @returns the symbolic values of the state variables at the beginning /// of the current transaction. std::vector<smtutil::Expression> initialStateVariables(); std::vector<smtutil::Expression> stateVariablesAtIndex(unsigned _index); std::vector<smtutil::Expression> stateVariablesAtIndex(unsigned _index, ContractDefinition const& _contract); /// @returns the current symbolic values of the current state variables. std::vector<smtutil::Expression> currentStateVariables(); std::vector<smtutil::Expression> currentStateVariables(ContractDefinition const& _contract); /// @returns \bigwedge currentValue(_vars[i]) == initialState(_var[i]) smtutil::Expression currentEqualInitialVarsConstraints(std::vector<VariableDeclaration const*> const& _vars) const; /// @returns the predicate name for a given node. std::string predicateName(ASTNode const* _node, ContractDefinition const* _contract = nullptr); /// @returns a predicate application after checking the predicate's type. smtutil::Expression predicate(Predicate const& _block); /// @returns the summary predicate for the called function. smtutil::Expression predicate( FunctionDefinition const* _funDef, std::optional<Expression const*> _boundArgumentCall, FunctionType const* _funType, std::vector<Expression const*> _arguments, smtutil::Expression _contractAddressValue ); /// @returns a predicate that defines a contract initializer for _contract in the context of _contractContext. smtutil::Expression initializer(ContractDefinition const& _contract, ContractDefinition const& _contractContext); /// @returns a predicate that defines a constructor summary. smtutil::Expression summary(ContractDefinition const& _contract); /// @returns a predicate that defines a function summary. smtutil::Expression summary(FunctionDefinition const& _function); smtutil::Expression summary(FunctionDefinition const& _function, ContractDefinition const& _contract); /// @returns a predicate that applies a function summary /// over the constrained variables. smtutil::Expression summaryCall(FunctionDefinition const& _function); smtutil::Expression summaryCall(FunctionDefinition const& _function, ContractDefinition const& _contract); /// @returns a predicate that defines an external function summary. smtutil::Expression externalSummary(FunctionDefinition const& _function); smtutil::Expression externalSummary(FunctionDefinition const& _function, ContractDefinition const& _contract); //@} /// Solver related. //@{ /// Adds Horn rule to the solver. void addRule(smtutil::Expression const& _rule, std::string const& _ruleName); /// @returns <true, invariant, empty> if query is unsatisfiable (safe). /// @returns <false, Expression(true), model> otherwise. smtutil::CHCSolverInterface::QueryResult query(smtutil::Expression const& _query, langutil::SourceLocation const& _location); void verificationTargetEncountered(ASTNode const* const _errorNode, VerificationTargetType _type, smtutil::Expression const& _errorCondition); void checkVerificationTargets(); struct CHCQueryPlaceholder; void checkAssertTarget(ASTNode const* _scope, CHCVerificationTarget const& _target); void checkAndReportTarget( CHCVerificationTarget const& _target, std::vector<CHCQueryPlaceholder> const& _placeholders, langutil::ErrorId _errorReporterId, std::string _satMsg, std::string _unknownMsg = "" ); std::pair<std::string, langutil::ErrorId> targetDescription(CHCVerificationTarget const& _target); std::optional<std::string> generateCounterexample(smtutil::CHCSolverInterface::CexGraph const& _graph, std::string const& _root); /// @returns a call graph for function summaries in the counterexample graph. /// The returned map also contains a key _root, whose value are the /// summaries called by _root. std::map<unsigned, std::vector<unsigned>> summaryCalls( smtutil::CHCSolverInterface::CexGraph const& _graph, unsigned _root ); /// @returns a set of pairs _var = _value separated by _separator. template <typename T> std::string formatVariableModel(std::vector<T> const& _variables, std::vector<std::optional<std::string>> const& _values, std::string const& _separator) const { solAssert(_variables.size() == _values.size(), ""); std::vector<std::string> assignments; for (unsigned i = 0; i < _values.size(); ++i) { auto var = _variables.at(i); if (var && _values.at(i)) assignments.emplace_back(var->name() + " = " + *_values.at(i)); } return boost::algorithm::join(assignments, _separator); } /// @returns a DAG in the dot format. /// Used for debugging purposes. std::string cex2dot(smtutil::CHCSolverInterface::CexGraph const& _graph); //@} /// Misc. //@{ /// @returns a prefix to be used in a new unique block name /// and increases the block counter. std::string uniquePrefix(); /// @returns a suffix to be used by contract related predicates. std::string contractSuffix(ContractDefinition const& _contract); /// @returns a new unique error id associated with _expr and stores /// it into m_errorIds. unsigned newErrorId(); smt::SymbolicIntVariable& errorFlag(); /// Adds to the solver constraints that /// - propagate tx.origin /// - set the current contract as msg.sender /// - set the msg.value as _value, if not nullptr void newTxConstraints(Expression const* _value); /// @returns the expression representing the value sent in /// an external call if present, /// and nullptr otherwise. frontend::Expression const* valueOption(FunctionCallOptions const* _options); /// Adds constraints that decrease the balance of the caller by _value. void decreaseBalanceFromOptionsValue(Expression const& _value); std::vector<smtutil::Expression> commonStateExpressions(smtutil::Expression const& error, smtutil::Expression const& address); //@} /// Predicates. //@{ /// Artificial Interface predicate. /// Single entry block for all functions. std::map<ContractDefinition const*, Predicate const*> m_interfaces; /// Nondeterministic interfaces. /// These are used when the analyzed contract makes external calls to unknown code, /// which means that the analyzed contract can potentially be called /// nondeterministically. std::map<ContractDefinition const*, Predicate const*> m_nondetInterfaces; std::map<ContractDefinition const*, Predicate const*> m_constructorSummaries; std::map<ContractDefinition const*, std::map<ContractDefinition const*, Predicate const*>> m_contractInitializers; /// Artificial Error predicate. /// Single error block for all assertions. Predicate const* m_errorPredicate = nullptr; /// Function predicates. std::map<ContractDefinition const*, std::map<FunctionDefinition const*, Predicate const*>> m_summaries; /// External function predicates. std::map<ContractDefinition const*, std::map<FunctionDefinition const*, Predicate const*>> m_externalSummaries; //@} /// Variables. //@{ /// State variables. /// Used to create all predicates. std::vector<VariableDeclaration const*> m_stateVariables; //@} /// Verification targets. //@{ /// Query placeholder stores information necessary to create the final query edge in the CHC system. /// It is combined with the unique error id (and error type) to create a complete Verification Target. struct CHCQueryPlaceholder { smtutil::Expression const constraints; smtutil::Expression const errorExpression; smtutil::Expression const fromPredicate; }; /// Query placeholders for constructors, if the key has type ContractDefinition*, /// or external functions, if the key has type FunctionDefinition*. /// A placeholder is created for each possible context of a function (e.g. multiple contracts in contract inheritance hierarchy). std::map<ASTNode const*, std::vector<CHCQueryPlaceholder>, smt::EncodingContext::IdCompare> m_queryPlaceholders; /// Records verification conditions IDs per function encountered during an analysis of that function. /// The key is the ASTNode of the function where the verification condition has been encountered, /// or the ASTNode of the contract if the verification condition happens inside an implicit constructor. std::map<ASTNode const*, std::vector<unsigned>, smt::EncodingContext::IdCompare> m_functionTargetIds; /// Helper mapping unique IDs to actual verification targets. std::map<unsigned, CHCVerificationTarget> m_verificationTargets; /// Targets proved safe. std::map<ASTNode const*, std::set<CHCVerificationTarget, SafeTargetsCompare>, smt::EncodingContext::IdCompare> m_safeTargets; /// Targets proved unsafe. std::map<ASTNode const*, std::map<VerificationTargetType, ReportTargetInfo>, smt::EncodingContext::IdCompare> m_unsafeTargets; /// Targets not proved. std::map<ASTNode const*, std::map<VerificationTargetType, ReportTargetInfo>, smt::EncodingContext::IdCompare> m_unprovedTargets; /// Inferred invariants. std::map<Predicate const*, std::set<std::string>, PredicateCompare> m_invariants; //@} /// Control-flow. //@{ FunctionDefinition const* m_currentFunction = nullptr; std::map<ASTNode const*, std::set<ASTNode const*, smt::EncodingContext::IdCompare>, smt::EncodingContext::IdCompare> m_callGraph; /// The current block. smtutil::Expression m_currentBlock = smtutil::Expression(true); /// Counter to generate unique block names. unsigned m_blockCounter = 0; /// Whether a function call was seen in the current scope. bool m_unknownFunctionCallSeen = false; /// Block where a loop break should go to. Predicate const* m_breakDest = nullptr; /// Block where a loop continue should go to. Predicate const* m_continueDest = nullptr; /// Block where an error condition should go to. /// This can be: /// 1) Constructor initializer summary, if error happens while evaluating initial values of state variables. /// 2) Constructor summary, if error happens while evaluating base constructor arguments. /// 3) Function summary, if error happens inside a function. Predicate const* m_errorDest = nullptr; /// Represents the stack of destinations where a `return` should go. /// This is different from `m_errorDest` above: /// - Constructor initializers and constructor summaries will never be `return` targets because they are artificial. /// - Modifiers also have their own `return` target blocks, whereas they do not have their own error destination. std::vector<Predicate const*> m_returnDests; //@} /// CHC solver. std::unique_ptr<smtutil::CHCSolverInterface> m_interface; std::map<util::h256, std::string> const& m_smtlib2Responses; ReadCallback::Callback const& m_smtCallback; }; }
20,580
C++
.h
406
48.366995
203
0.779614
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,521
ExpressionFormatter.h
ethereum_solidity/libsolidity/formal/ExpressionFormatter.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 #pragma once /** * Helper methods for formatting SMT expressions */ #include <libsmtutil/SolverInterface.h> #include <libsolidity/ast/Types.h> #include <map> #include <string> namespace solidity::frontend::smt { /// @returns another smtutil::Expressions where every term in _from /// may be replaced if it is in the substitution map _subst. smtutil::Expression substitute(smtutil::Expression _from, std::map<std::string, std::string> const& _subst); /// @returns a Solidity-like expression string built from _expr. /// This is done at best-effort and is not guaranteed to always create a perfect Solidity expression string. std::string toSolidityStr(smtutil::Expression const& _expr); /// @returns a string representation of the SMT expression based on a Solidity type. std::optional<std::string> expressionToString(smtutil::Expression const& _expr, Type const* _type); /// @returns the formatted version of the given SMT expressions. Those expressions must be SMT constants. std::vector<std::optional<std::string>> formatExpressions(std::vector<smtutil::Expression> const& _exprs, std::vector<Type const*> const& _types); }
1,822
C++
.h
35
50.314286
146
0.781285
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,522
SymbolicTypes.h
ethereum_solidity/libsolidity/formal/SymbolicTypes.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 #pragma once #include <libsolidity/formal/SymbolicVariables.h> #include <libsolidity/ast/AST.h> #include <libsolidity/ast/Types.h> namespace solidity::frontend::smt { class EncodingContext; /// Returns the SMT sort that models the Solidity type _type. smtutil::SortPointer smtSort(frontend::Type const& _type); std::vector<smtutil::SortPointer> smtSort(std::vector<frontend::Type const*> const& _types); /// If _type has type Function, abstract it to Integer. /// Otherwise return smtSort(_type). smtutil::SortPointer smtSortAbstractFunction(frontend::Type const& _type); std::vector<smtutil::SortPointer> smtSortAbstractFunction(std::vector<frontend::Type const*> const& _types); /// Returns the SMT kind that models the Solidity type type category _category. smtutil::Kind smtKind(frontend::Type const& _type); /// Returns true if type is fully supported (declaration and operations). bool isSupportedType(frontend::Type const& _type); bool isSupportedType(frontend::Type const& _type); /// Returns true if type is partially supported (declaration). bool isSupportedTypeDeclaration(frontend::Type const& _type); bool isSupportedTypeDeclaration(frontend::Type const& _type); bool isInteger(frontend::Type const& _type); bool isFixedPoint(frontend::Type const& _type); bool isRational(frontend::Type const& _type); bool isFixedBytes(frontend::Type const& _type); bool isAddress(frontend::Type const& _type); bool isContract(frontend::Type const& _type); bool isEnum(frontend::Type const& _type); bool isNumber(frontend::Type const& _type); bool isBool(frontend::Type const& _type); bool isFunction(frontend::Type const& _type); bool isMapping(frontend::Type const& _type); bool isArray(frontend::Type const& _type); bool isTuple(frontend::Type const& _type); bool isStringLiteral(frontend::Type const& _type); bool isNonRecursiveStruct(frontend::Type const& _type); bool isInaccessibleDynamic(frontend::Type const& _type); /// Returns a new symbolic variable, according to _type. /// Also returns whether the type is abstract or not, /// which is true for unsupported types. std::pair<bool, std::shared_ptr<SymbolicVariable>> newSymbolicVariable(frontend::Type const& _type, std::string const& _uniqueName, EncodingContext& _context); smtutil::Expression minValue(frontend::IntegerType const& _type); smtutil::Expression minValue(frontend::Type const* _type); smtutil::Expression maxValue(frontend::IntegerType const& _type); smtutil::Expression maxValue(frontend::Type const* _type); smtutil::Expression zeroValue(frontend::Type const* _type); bool isSigned(frontend::Type const* _type); std::pair<unsigned, bool> typeBvSizeAndSignedness(frontend::Type const* type); void setSymbolicZeroValue(SymbolicVariable const& _variable, EncodingContext& _context); void setSymbolicZeroValue(smtutil::Expression _expr, frontend::Type const* _type, EncodingContext& _context); void setSymbolicUnknownValue(SymbolicVariable const& _variable, EncodingContext& _context); void setSymbolicUnknownValue(smtutil::Expression _expr, frontend::Type const* _type, EncodingContext& _context); smtutil::Expression symbolicUnknownConstraints(smtutil::Expression _expr, frontend::Type const* _type); std::optional<smtutil::Expression> symbolicTypeConversion(frontend::Type const* _from, frontend::Type const* _to); smtutil::Expression member(smtutil::Expression const& _tuple, std::string const& _member); smtutil::Expression assignMember(smtutil::Expression const _tuple, std::map<std::string, smtutil::Expression> const& _values); }
4,210
C++
.h
72
57.083333
159
0.793011
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,523
Predicate.h
ethereum_solidity/libsolidity/formal/Predicate.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 #pragma once #include <libsolidity/ast/AST.h> #include <libsmtutil/SolverInterface.h> #include <libsmtutil/Sorts.h> #include <map> #include <optional> #include <vector> namespace solidity::langutil { class CharStreamProvider; } namespace solidity::frontend { namespace smt { class EncodingContext; } enum class PredicateType { Interface, NondetInterface, ConstructorSummary, FunctionSummary, FunctionBlock, FunctionErrorBlock, InternalCall, ExternalCallTrusted, ExternalCallUntrusted, Error, Custom }; /** * Represents a predicate used by the CHC engine. */ class Predicate { public: static Predicate const* create( smtutil::SortPointer _sort, std::string _name, PredicateType _type, smt::EncodingContext& _context, ASTNode const* _node = nullptr, ContractDefinition const* _contractContext = nullptr, std::vector<ScopeOpener const*> _scopeStack = {} ); Predicate( std::string _name, smtutil::SortPointer _sort, PredicateType _type, bool _bytesConcatFunctionInContext, ASTNode const* _node = nullptr, ContractDefinition const* _contractContext = nullptr, std::vector<ScopeOpener const*> _scopeStack = {} ); /// Predicate should not be copiable. Predicate(Predicate const&) = delete; Predicate& operator=(Predicate const&) = delete; /// @returns the Predicate associated with _name. static Predicate const* predicate(std::string const& _name); /// Resets all the allocated predicates. static void reset(); /// @returns a function application of the predicate over _args. smtutil::Expression operator()(std::vector<smtutil::Expression> const& _args) const; /// @returns the function declaration of the predicate. smtutil::Expression const& functor() const; /// @returns the program node this predicate represents. ASTNode const* programNode() const; /// @returns the ContractDefinition of the most derived contract /// being analyzed. ContractDefinition const* contextContract() const; /// @returns the ContractDefinition that this predicate represents /// or nullptr otherwise. ContractDefinition const* programContract() const; /// @returns the FunctionDefinition that this predicate represents /// or nullptr otherwise. FunctionDefinition const* programFunction() const; /// @returns the FunctionCall that this predicate represents /// or nullptr otherwise. FunctionCall const* programFunctionCall() const; /// @returns the VariableDeclaration that this predicate represents /// or nullptr otherwise. VariableDeclaration const* programVariable() const; /// @returns the program state variables in the scope of this predicate. std::optional<std::vector<VariableDeclaration const*>> stateVariables() const; /// @returns true if this predicate represents a summary. bool isSummary() const; /// @returns true if this predicate represents a function summary. bool isFunctionSummary() const; /// @returns true if this predicate represents a function block. bool isFunctionBlock() const; /// @returns true if this predicate represents a function error block. bool isFunctionErrorBlock() const; /// @returns true if this predicate represents an internal function call. bool isInternalCall() const; /// @returns true if this predicate represents a trusted external function call. bool isExternalCallTrusted() const; /// @returns true if this predicate represents an untrusted external function call. bool isExternalCallUntrusted() const; /// @returns true if this predicate represents a constructor summary. bool isConstructorSummary() const; /// @returns true if this predicate represents an interface. bool isInterface() const; /// @returns true if this predicate represents a nondeterministic interface. bool isNondetInterface() const; PredicateType type() const { return m_type; } /// @returns a formatted string representing a call to this predicate /// with _args. std::string formatSummaryCall( std::vector<smtutil::Expression> const& _args, langutil::CharStreamProvider const& _charStreamProvider, bool _appendTxVars = false ) const; /// @returns the values of the state variables from _args at the point /// where this summary was reached. std::vector<std::optional<std::string>> summaryStateValues(std::vector<smtutil::Expression> const& _args) const; /// @returns the values of the function input variables from _args at the point /// where this summary was reached. std::vector<std::optional<std::string>> summaryPostInputValues(std::vector<smtutil::Expression> const& _args) const; /// @returns the values of the function output variables from _args at the point /// where this summary was reached. std::vector<std::optional<std::string>> summaryPostOutputValues(std::vector<smtutil::Expression> const& _args) const; /// @returns the values of the local variables used by this predicate. std::pair<std::vector<std::optional<std::string>>, std::vector<VariableDeclaration const*>> localVariableValues(std::vector<smtutil::Expression> const& _args) const; /// @returns a substitution map from the arguments of _predExpr /// to a Solidity-like expression. std::map<std::string, std::string> expressionSubstitution(smtutil::Expression const& _predExprs) const; private: /// Recursively fills _array from _expr. /// _expr should have the form `store(store(...(const_array(x_0), i_0, e_0), i_m, e_m), i_k, e_k)`. /// @returns true if the construction worked, /// and false if at least one element could not be built. bool fillArray(smtutil::Expression const& _expr, std::vector<std::string>& _array, ArrayType const& _type) const; std::map<std::string, std::optional<std::string>> readTxVars(smtutil::Expression const& _tx) const; /// @returns index at which transaction values start in args list size_t txValuesIndex() const { return m_bytesConcatFunctionInContext ? 5 : 4; } /// @returns index at which function arguments start in args list size_t firstArgIndex() const { return m_bytesConcatFunctionInContext ? 7 : 6; } /// @returns index at which state variables values start in args list size_t firstStateVarIndex() const { return m_bytesConcatFunctionInContext ? 8 : 7; } smtutil::Expression m_functor; /// The type of this predicate. PredicateType m_type; /// The ASTNode that this predicate represents. /// nullptr if this predicate is not associated with a specific program AST node. ASTNode const* m_node = nullptr; /// The ContractDefinition that contains this predicate. /// nullptr if this predicate is not associated with a specific contract. /// This is unfortunately necessary because of virtual resolution for /// function nodes. ContractDefinition const* m_contractContext = nullptr; /// Maps the name of the predicate to the actual Predicate. /// Used in counterexample generation. static std::map<std::string, Predicate> m_predicates; /// The scope stack when the predicate was created. /// Used to identify the subset of variables in scope. std::vector<ScopeOpener const*> const m_scopeStack; /// True iff there is a bytes concat function in contract scope bool m_bytesConcatFunctionInContext; }; struct PredicateCompare { bool operator()(Predicate const* lhs, Predicate const* rhs) const { // We cannot use m_node->id() because different predicates may // represent the same program node. // We use the symbolic name since it is unique per predicate and // the order does not really matter. return lhs->functor().name < rhs->functor().name; } }; }
8,170
C++
.h
186
41.688172
166
0.772481
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,524
PredicateInstance.h
ethereum_solidity/libsolidity/formal/PredicateInstance.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 #pragma once #include <libsolidity/formal/Predicate.h> #include <libsolidity/formal/SymbolicState.h> namespace solidity::frontend::smt { class EncodingContext; /** * This file represents the specification for building CHC predicate instances. * The predicates follow the specification in PredicateSort.h. * */ smtutil::Expression interfacePre(Predicate const& _pred, ContractDefinition const& _contract, EncodingContext& _context); smtutil::Expression interface(Predicate const& _pred, ContractDefinition const& _contract, EncodingContext& _context); smtutil::Expression nondetInterface(Predicate const& _pred, ContractDefinition const& _contract, EncodingContext& _context, unsigned _preIdx, unsigned _postIdx); smtutil::Expression constructor(Predicate const& _pred, EncodingContext& _context); /// The encoding of the deployment procedure includes adding constraints /// for base constructors if inheritance is used. /// From the predicate point of view this is not different, /// but some of the arguments are different. /// @param _internal = true means that this constructor call is used in the /// deployment procedure, whereas false means it is used in the deployment /// of a contract. smtutil::Expression constructorCall(Predicate const& _pred, EncodingContext& _context, bool _internal = true); smtutil::Expression function( Predicate const& _pred, ContractDefinition const* _contract, EncodingContext& _context ); smtutil::Expression functionCall( Predicate const& _pred, ContractDefinition const* _contract, EncodingContext& _context ); smtutil::Expression functionBlock( Predicate const& _pred, FunctionDefinition const& _function, ContractDefinition const* _contract, EncodingContext& _context ); /// Helpers std::vector<smtutil::Expression> initialStateVariables(ContractDefinition const& _contract, EncodingContext& _context); std::vector<smtutil::Expression> stateVariablesAtIndex(unsigned _index, ContractDefinition const& _contract, EncodingContext& _context); std::vector<smtutil::Expression> currentStateVariables(ContractDefinition const& _contract, EncodingContext& _context); std::vector<smtutil::Expression> newStateVariables(ContractDefinition const& _contract, EncodingContext& _context); std::vector<smtutil::Expression> currentFunctionVariablesForDefinition( FunctionDefinition const& _function, ContractDefinition const* _contract, EncodingContext& _context ); std::vector<smtutil::Expression> currentFunctionVariablesForCall( FunctionDefinition const& _function, ContractDefinition const* _contract, EncodingContext& _context, bool _internal = true ); std::vector<smtutil::Expression> currentBlockVariables( FunctionDefinition const& _function, ContractDefinition const* _contract, EncodingContext& _context ); std::vector<smtutil::Expression> getStateExpressionsForInterfacePre(SymbolicState const& _state); std::vector<smtutil::Expression> getStateExpressionsForInterface(SymbolicState const& _state); std::vector<smtutil::Expression> getStateExpressionsForNondetInterface(SymbolicState const& _state); std::vector<smtutil::Expression> getStateExpressionsForConstructor(SymbolicState const& _state); std::vector<smtutil::Expression> getStateExpressionsForCall(SymbolicState const& _state, bool _internal); std::vector<smtutil::Expression> getStateExpressionsForDefinition(SymbolicState const& _state); }
4,072
C++
.h
80
49.175
161
0.81628
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,526
PredicateSort.h
ethereum_solidity/libsolidity/formal/PredicateSort.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 #pragma once #include <libsolidity/formal/Predicate.h> #include <libsolidity/formal/SymbolicState.h> #include <libsmtutil/Sorts.h> namespace solidity::frontend::smt { /** * This file represents the specification for CHC predicate sorts. * Types of predicates: * * 1. Interface * The idle state of a contract. Signature: * interface(this, abiFunctions, cryptoFunctions, blockchainState, stateVariables). * * 2. Nondet interface * The nondeterminism behavior of a contract. Signature: * nondet_interface(error, this, abiFunctions, cryptoFunctions, blockchainState, stateVariables, blockchainState', stateVariables'). * * 3. Constructor entry/summary * The summary of a contract's deployment procedure. * Signature: * If the contract has a constructor function, this is the same as the summary of that function. Otherwise: * constructor_summary(error, this, abiFunctions, cryptoFunctions, txData, blockchainState, blockchainState', stateVariables, stateVariables'). * * 4. Function entry/summary * The entry point of a function definition. Signature: * function_entry(error, this, abiFunctions, cryptoFunctions, txData, blockchainState, stateVariables, inputVariables, blockchainState', stateVariables', inputVariables', outputVariables'). * * 5. Function body * Use for any predicate within a function. Signature: * function_body(error, this, abiFunctions, cryptoFunctions, txData, blockchainState, stateVariables, inputVariables, blockchainState', stateVariables', inputVariables', outputVariables', localVariables). */ /// @returns the interface predicate sort for _contract. smtutil::SortPointer interfaceSort(ContractDefinition const& _contract, SymbolicState& _state); /// @returns the nondeterminisc interface predicate sort for _contract. smtutil::SortPointer nondetInterfaceSort(ContractDefinition const& _contract, SymbolicState& _state); /// @returns the constructor entry/summary predicate sort for _contract. smtutil::SortPointer constructorSort(ContractDefinition const& _contract, SymbolicState& _state); /// @returns the function entry/summary predicate sort for _function contained in _contract. smtutil::SortPointer functionSort(FunctionDefinition const& _function, ContractDefinition const* _contract, SymbolicState& _state); /// @returns the function body predicate sort for _function contained in _contract. smtutil::SortPointer functionBodySort(FunctionDefinition const& _function, ContractDefinition const* _contract, SymbolicState& _state); /// @returns the sort of a predicate without parameters. smtutil::SortPointer arity0FunctionSort(); /// Helpers std::vector<smtutil::SortPointer> stateSorts(ContractDefinition const& _contract); std::vector<smtutil::SortPointer> getBuiltInFunctionsSorts(SymbolicState& _state); }
3,468
C++
.h
62
54.048387
204
0.803661
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,527
SymbolicState.h
ethereum_solidity/libsolidity/formal/SymbolicState.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 #pragma once #include <libsolidity/formal/SymbolicTypes.h> #include <libsolidity/formal/SymbolicVariables.h> #include <libsmtutil/Sorts.h> #include <libsmtutil/SolverInterface.h> namespace solidity::frontend::smt { class EncodingContext; class SymbolicAddressVariable; class SymbolicArrayVariable; class BlockchainVariable { public: BlockchainVariable(std::string _name, std::map<std::string, smtutil::SortPointer> _members, EncodingContext& _context); /// @returns the variable data as a tuple. smtutil::Expression value() const { return m_tuple->currentValue(); } smtutil::Expression value(unsigned _idx) const { return m_tuple->valueAtIndex(_idx); } smtutil::SortPointer const& sort() const { return m_tuple->sort(); } unsigned index() const { return m_tuple->index(); } void newVar() { m_tuple->increaseIndex(); } void reset() { m_tuple->resetIndex(); } /// @returns the symbolic _member. smtutil::Expression member(std::string const& _member) const; /// Generates a new tuple where _member is assigned _value. smtutil::Expression assignMember(std::string const& _member, smtutil::Expression const& _value); private: std::string const m_name; std::map<std::string, smtutil::SortPointer> const m_members; EncodingContext& m_context; std::map<std::string, unsigned> m_componentIndices; std::unique_ptr<SymbolicTupleVariable> m_tuple; }; /** * Symbolic representation of the blockchain context: * - error flag * - this (the address of the currently executing contract) * - state, represented as a tuple of: * - balances * - array of address => bool representing whether an address is used by a contract * - storage of contracts * - block and transaction properties, represented as a tuple of: * - blockhash * - block basefee * - block chainid * - block coinbase * - block gaslimit * - block number * - block prevrandao * - block timestamp * - TODO gasleft * - msg data * - msg sender * - msg sig * - msg value * - tx gasprice * - tx origin */ class SymbolicState { public: SymbolicState(EncodingContext& _context): m_context(_context) {} void reset(); /// Error flag. //@{ SymbolicIntVariable& errorFlag() { return m_error; } SymbolicIntVariable const& errorFlag() const { return m_error; } smtutil::SortPointer const& errorFlagSort() const { return m_error.sort(); } //@} /// This. //@{ /// @returns the symbolic value of the currently executing contract's address. smtutil::Expression thisAddress() const { return m_thisAddress.currentValue(); } smtutil::Expression thisAddress(unsigned _idx) const { return m_thisAddress.valueAtIndex(_idx); } smtutil::Expression newThisAddress() { return m_thisAddress.increaseIndex(); } smtutil::SortPointer const& thisAddressSort() const { return m_thisAddress.sort(); } //@} /// Blockchain state. //@{ smtutil::Expression state() const { solAssert(m_state, ""); return m_state->value(); } smtutil::Expression state(unsigned _idx) const { solAssert(m_state, ""); return m_state->value(_idx); } smtutil::SortPointer const& stateSort() const { solAssert(m_state, ""); return m_state->sort(); } void newState() { solAssert(m_state, ""); m_state->newVar(); } void newBalances(); /// Balance. /// @returns the symbolic balances. smtutil::Expression balances() const; /// @returns the symbolic balance of address `this`. smtutil::Expression balance() const; /// @returns the symbolic balance of an address. smtutil::Expression balance(smtutil::Expression _address) const; /// Transfer _value from _from to _to. void transfer(smtutil::Expression _from, smtutil::Expression _to, smtutil::Expression _value); /// Adds _value to _account's balance. void addBalance(smtutil::Expression _account, smtutil::Expression _value); /// Storage. smtutil::Expression storage(ContractDefinition const& _contract) const; smtutil::Expression storage(ContractDefinition const& _contract, smtutil::Expression _address) const; smtutil::Expression addressActive(smtutil::Expression _address) const; void setAddressActive(smtutil::Expression _address, bool _active); void newStorage(); void writeStateVars(ContractDefinition const& _contract, smtutil::Expression _address); void readStateVars(ContractDefinition const& _contract, smtutil::Expression _address); //@} /// Transaction data. //@{ /// @returns the tx data as a tuple. smtutil::Expression tx() const { return m_tx.value(); } smtutil::Expression tx(unsigned _idx) const { return m_tx.value(_idx); } smtutil::SortPointer const& txSort() const { return m_tx.sort(); } void newTx() { m_tx.newVar(); } smtutil::Expression txMember(std::string const& _member) const; smtutil::Expression txFunctionConstraints(FunctionDefinition const& _function) const; smtutil::Expression txTypeConstraints() const; smtutil::Expression txNonPayableConstraint() const; smtutil::Expression blockhash(smtutil::Expression _blockNumber) const; smtutil::Expression evmParisConstraints() const; //@} /// Crypto functions. //@{ /// @returns the crypto functions represented as a tuple of arrays. smtutil::Expression crypto() const { return m_crypto.value(); } smtutil::Expression crypto(unsigned _idx) const { return m_crypto.value(_idx); } smtutil::SortPointer const& cryptoSort() const { return m_crypto.sort(); } void newCrypto() { m_crypto.newVar(); } smtutil::Expression cryptoFunction(std::string const& _member) const { return m_crypto.member(_member); } //@} /// Calls the internal methods that build /// - the symbolic ABI functions based on the abi.* calls /// in _source and referenced sources. /// - the symbolic storages for all contracts in _source and /// referenced sources. void prepareForSourceUnit(SourceUnit const& _source, bool _storage); /// ABI functions. //@{ smtutil::Expression abiFunction(FunctionCall const* _funCall); using SymbolicABIFunction = std::tuple< std::string, std::vector<frontend::Type const*>, std::vector<frontend::Type const*> >; SymbolicABIFunction const& abiFunctionTypes(FunctionCall const* _funCall) const; smtutil::Expression abi() const { solAssert(m_abi, ""); return m_abi->value(); } smtutil::Expression abi(unsigned _idx) const { solAssert(m_abi, ""); return m_abi->value(_idx); } smtutil::SortPointer const& abiSort() const { solAssert(m_abi, ""); return m_abi->sort(); } //@} /// bytes.concat functions. //@{ smtutil::Expression bytesConcatFunction(FunctionCall const* _funCall); using SymbolicBytesConcatFunction = std::tuple< std::string, std::vector<frontend::Type const*>, frontend::Type const* >; SymbolicBytesConcatFunction const& bytesConcatFunctionTypes(FunctionCall const* _funCall) const; smtutil::Expression bytesConcat() const { solAssert(m_bytesConcat, ""); return m_bytesConcat->value(); } smtutil::Expression bytesConcat(unsigned _idx) const { solAssert(m_bytesConcat, ""); return m_bytesConcat->value(_idx); } smtutil::SortPointer const& bytesConcatSort() const { solAssert(m_bytesConcat, ""); return m_bytesConcat->sort(); } bool hasBytesConcatFunction() const {solAssert(m_bytesConcat, ""); return !m_bytesConcatMembers.empty(); } //@} private: std::string contractSuffix(ContractDefinition const& _contract) const; std::string contractStorageKey(ContractDefinition const& _contract) const; std::string stateVarStorageKey(VariableDeclaration const& _var, ContractDefinition const& _contract) const; /// Builds state.storage based on _contracts. void buildState(std::set<ContractDefinition const*, ASTCompareByID<ContractDefinition>> const& _contracts, bool _allStorages); /// Builds m_abi based on the abi.* calls _abiFunctions. void buildABIFunctions(std::set<FunctionCall const*, ASTCompareByID<FunctionCall>> const& _abiFunctions); /// Builds m_bytesConcat based on the bytes.concat calls void buildBytesConcatFunctions(std::set<FunctionCall const*, ASTCompareByID<FunctionCall>> const& _bytesConcatCalls); EncodingContext& m_context; SymbolicIntVariable m_error{ TypeProvider::uint256(), TypeProvider::uint256(), "error", m_context }; SymbolicAddressVariable m_thisAddress{ "this", m_context }; /// m_state is a tuple of /// - balances: array of address to balance of address. /// - isActive: array of address to Boolean, where element is true iff address is used. /// - storage: tuple containing the storage of every contract, where /// each element of the tuple represents a contract, /// and is defined by an array where the index is the contract's address /// and the element is a tuple containing the state variables of that contract. std::unique_ptr<BlockchainVariable> m_state; BlockchainVariable m_tx{ "tx", { {"block.basefee", smtutil::SortProvider::uintSort}, {"block.chainid", smtutil::SortProvider::uintSort}, {"block.coinbase", smt::smtSort(*TypeProvider::address())}, {"block.prevrandao", smtutil::SortProvider::uintSort}, {"block.gaslimit", smtutil::SortProvider::uintSort}, {"block.number", smtutil::SortProvider::uintSort}, {"block.timestamp", smtutil::SortProvider::uintSort}, {"blockhash", std::make_shared<smtutil::ArraySort>(smtutil::SortProvider::uintSort, smtutil::SortProvider::uintSort)}, // TODO gasleft {"msg.data", smt::smtSort(*TypeProvider::bytesMemory())}, {"msg.sender", smt::smtSort(*TypeProvider::address())}, {"msg.sig", smtutil::SortProvider::uintSort}, {"msg.value", smtutil::SortProvider::uintSort}, {"tx.gasprice", smtutil::SortProvider::uintSort}, {"tx.origin", smt::smtSort(*TypeProvider::address())} }, m_context }; BlockchainVariable m_crypto{ "crypto", { {"keccak256", std::make_shared<smtutil::ArraySort>( smt::smtSort(*TypeProvider::bytesStorage()), smtSort(*TypeProvider::fixedBytes(32)) )}, {"sha256", std::make_shared<smtutil::ArraySort>( smt::smtSort(*TypeProvider::bytesStorage()), smtSort(*TypeProvider::fixedBytes(32)) )}, {"ripemd160", std::make_shared<smtutil::ArraySort>( smt::smtSort(*TypeProvider::bytesStorage()), smtSort(*TypeProvider::fixedBytes(20)) )}, {"ecrecover", std::make_shared<smtutil::ArraySort>( std::make_shared<smtutil::TupleSort>( "ecrecover_input_type", std::vector<std::string>{"hash", "v", "r", "s"}, std::vector<smtutil::SortPointer>{ smt::smtSort(*TypeProvider::fixedBytes(32)), smt::smtSort(*TypeProvider::uint(8)), smt::smtSort(*TypeProvider::fixedBytes(32)), smt::smtSort(*TypeProvider::fixedBytes(32)) } ), smtSort(*TypeProvider::address()) )} }, m_context }; /// Tuple containing all used ABI functions. std::unique_ptr<BlockchainVariable> m_abi; /// Maps ABI functions calls to their tuple names generated by /// `buildABIFunctions`. std::map<FunctionCall const*, SymbolicABIFunction> m_abiMembers; /// Tuple containing all used bytes.concat functions. std::unique_ptr<BlockchainVariable> m_bytesConcat; /// Maps bytes.concat functions calls to their tuple names generated by /// `buildBytesConcatFunctions`. std::map<FunctionCall const*, SymbolicBytesConcatFunction> m_bytesConcatMembers; }; }
11,822
C++
.h
266
41.902256
127
0.740188
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,528
Invariants.h
ethereum_solidity/libsolidity/formal/Invariants.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 #pragma once #include <libsolidity/formal/ModelCheckerSettings.h> #include <libsolidity/formal/Predicate.h> #include <map> #include <set> #include <string> 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& _invariantsSettings ); }
1,092
C++
.h
28
37.178571
69
0.792417
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,530
YulUtilFunctions.h
ethereum_solidity/libsolidity/codegen/YulUtilFunctions.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 /** * Component that can generate various useful Yul functions. */ #pragma once #include <liblangutil/EVMVersion.h> #include <libsolidity/ast/Types.h> #include <libsolidity/ast/AST.h> #include <libsolidity/codegen/MultiUseYulFunctionCollector.h> #include <libsolidity/interface/DebugSettings.h> #include <libsolutil/ErrorCodes.h> #include <memory> #include <string> #include <vector> namespace solidity::frontend { class Type; class ArrayType; class MappingType; class IntegerType; class StructType; /** * Component that can generate various useful Yul functions. */ class YulUtilFunctions { public: explicit YulUtilFunctions( langutil::EVMVersion _evmVersion, RevertStrings _revertStrings, MultiUseYulFunctionCollector& _functionCollector ): m_evmVersion(_evmVersion), m_revertStrings(_revertStrings), m_functionCollector(_functionCollector) {} /// @returns the name of a function that returns its argument. /// Sometimes needed to satisfy templates. std::string identityFunction(); /// @returns a function that combines the address and selector to a single value /// for use in the ABI. std::string combineExternalFunctionIdFunction(); /// @returns a function that splits the address and selector from a single value /// for use in the ABI. std::string splitExternalFunctionIdFunction(); /// @returns a function that copies raw bytes of dynamic length from calldata /// or memory to memory. /// @params _cleanup If true, pads with zeros up to the 32 byte boundary after the specified length /// signature: (src, dst, length) -> std::string copyToMemoryFunction(bool _fromCalldata, bool _cleanup); /// @returns the name of a function that copies a string literal to memory /// and returns a pointer to the memory area containing the string literal. /// signature: () -> memPtr std::string copyLiteralToMemoryFunction(std::string const& _literal); /// @returns the name of a function that stores a string literal at a specific location in memory /// signature: (memPtr) -> std::string storeLiteralInMemoryFunction(std::string const& _literal); /// @returns the name of a function that stores a string literal at a specific location in storage /// signature: (slot) -> std::string copyLiteralToStorageFunction(std::string const& _literal); /// @returns statements to revert with an error. /// Generates code to revert with an error. The error arguments are assumed to /// be already evaluated and available in local IRVariables, but not yet /// converted. std::string 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 = {} ); // @returns the name of a function that has the equivalent logic of an // `assert` or `require` call. std::string requireOrAssertFunction( bool _assert, Type const* _messageType = nullptr, ASTPointer<Expression const> _stringArgumentExpression = nullptr ); // @returns function that has equivalent logic of a require function, but with a custom // error constructor parameter. std::string requireWithErrorFunction(FunctionCall const& errorConstructorCall); /// @returns the name of a function that takes a (cleaned) value of the given value type and /// left-aligns it, usually for use in non-padded encoding. std::string leftAlignFunction(Type const& _type); std::string shiftLeftFunction(size_t _numBits); std::string shiftLeftFunctionDynamic(); std::string shiftRightFunction(size_t _numBits); std::string shiftRightFunctionDynamic(); std::string shiftRightSignedFunctionDynamic(); /// @returns the name of a function that performs a left shift and subsequent cleanup /// and, if needed, prior cleanup. /// signature: (value, amountToShift) -> result std::string typedShiftLeftFunction(Type const& _type, Type const& _amountType); std::string typedShiftRightFunction(Type const& _type, Type const& _amountType); /// @returns the name of a function which replaces the /// _numBytes bytes starting at byte position _shiftBytes (counted from the least significant /// byte) by the _numBytes least significant bytes of `toInsert`. /// signature: (value, toInsert) -> result std::string updateByteSliceFunction(size_t _numBytes, size_t _shiftBytes); /// signature: (value, shiftBytes, toInsert) -> result std::string updateByteSliceFunctionDynamic(size_t _numBytes); /// Function that sets all but the first ``bytes`` bytes of ``value`` to zero. /// @note ``bytes`` has to be small enough not to overflow ``8 * bytes``. /// signature: (value, bytes) -> result std::string maskBytesFunctionDynamic(); /// Zeroes out all bytes above the first ``_bytes`` lower order bytes. /// signature: (value) -> result std::string maskLowerOrderBytesFunction(size_t _bytes); /// Zeroes out all bytes above the first ``bytes`` lower order bytes. /// @note ``bytes`` has to be small enough not to overflow ``8 * bytes``. /// signature: (value, bytes) -> result std::string maskLowerOrderBytesFunctionDynamic(); /// @returns the name of a function that rounds its input to the next multiple /// of 32 or the input if it is a multiple of 32. /// Ignores overflow. /// signature: (value) -> result std::string roundUpFunction(); /// @returns the name of a function that divides by 32 and rounds up during the division. /// In other words, on input x it returns the smallest y such that y * 32 >= x. /// Ignores overflow. /// signature: (x) -> y std::string divide32CeilFunction(); /// signature: (x, y) -> sum std::string overflowCheckedIntAddFunction(IntegerType const& _type); /// signature: (x, y) -> sum std::string wrappingIntAddFunction(IntegerType const& _type); /// signature: (x, y) -> product std::string overflowCheckedIntMulFunction(IntegerType const& _type); /// signature: (x, y) -> product std::string wrappingIntMulFunction(IntegerType const& _type); /// @returns name of function to perform division on integers. /// Checks for division by zero and the special case of /// signed division of the smallest number by -1. std::string overflowCheckedIntDivFunction(IntegerType const& _type); /// @returns name of function to perform division on integers. /// Checks for division by zero. std::string wrappingIntDivFunction(IntegerType const& _type); /// @returns name of function to perform modulo on integers. /// Reverts for modulo by zero. std::string intModFunction(IntegerType const& _type); /// @returns computes the difference between two values. /// Assumes the input to be in range for the type. /// signature: (x, y) -> diff std::string overflowCheckedIntSubFunction(IntegerType const& _type); /// @returns computes the difference between two values. /// signature: (x, y) -> diff std::string wrappingIntSubFunction(IntegerType const& _type); /// @returns the name of the exponentiation function. /// signature: (base, exponent) -> power std::string overflowCheckedIntExpFunction(IntegerType const& _type, IntegerType const& _exponentType); /// @returns the name of the exponentiation function, specialized for literal base. /// signature: exponent -> power std::string overflowCheckedIntLiteralExpFunction( RationalNumberType const& _baseType, IntegerType const& _exponentType, IntegerType const& _commonType ); /// Generic unsigned checked exponentiation function. /// Reverts if the result is larger than max. /// signature: (base, exponent, max) -> power std::string overflowCheckedUnsignedExpFunction(); /// Generic signed checked exponentiation function. /// Reverts if the result is smaller than min or larger than max. /// The code relies on max <= |min| and min < 0. /// signature: (base, exponent, min, max) -> power std::string overflowCheckedSignedExpFunction(); /// Helper function for the two checked exponentiation functions. /// signature: (power, base, exponent, max) -> power std::string overflowCheckedExpLoopFunction(); /// @returns the name of the exponentiation function. /// signature: (base, exponent) -> power std::string wrappingIntExpFunction(IntegerType const& _type, IntegerType const& _exponentType); /// @returns the name of a function that fetches the length of the given /// array /// signature: (array) -> length std::string arrayLengthFunction(ArrayType const& _type); /// @returns function name that extracts and returns byte array length from the value /// stored at the slot. /// Causes a Panic if the length encoding is wrong. /// signature: (data) -> length std::string extractByteArrayLengthFunction(); /// @returns the name of a function that resizes a storage array /// for statically sized arrays, it will just clean-up elements of array starting from newLen until the end /// signature: (array, newLen) std::string resizeArrayFunction(ArrayType const& _type); /// @returns the name of a function that zeroes all storage array elements from `startIndex` to `len` (excluding). /// Assumes that `len` is the array length. Does nothing if `startIndex >= len`. Does not modify the stored length. /// signature: (array, len, startIndex) std::string cleanUpStorageArrayEndFunction(ArrayType const& _type); /// @returns the name of a function that reduces the size of a storage array by one element /// signature: (array) std::string storageArrayPopFunction(ArrayType const& _type); /// @returns the name of a function that pushes an element to a storage array /// @param _fromType represents the type of the element being pushed. /// If _fromType is ReferenceType the function will perform deep copy. /// signature: (array, value) std::string storageArrayPushFunction(ArrayType const& _type, Type const* _fromType = nullptr); /// @returns the name of a function that pushes the base type's zero element to a storage array and returns storage slot and offset of the added element. /// signature: (array) -> slot, offset std::string storageArrayPushZeroFunction(ArrayType const& _type); /// @returns the name of a function that will clear the storage area given /// by the start and end (exclusive) parameters (slots). /// signature: (start, end) std::string clearStorageRangeFunction(Type const& _type); /// @returns the name of a function that will clear the given storage array /// signature: (slot) -> std::string clearStorageArrayFunction(ArrayType const& _type); /// @returns the name of a function that will copy an array to storage /// signature (to_slot, from_ptr) -> std::string copyArrayToStorageFunction(ArrayType const& _fromType, ArrayType const& _toType); /// @returns the name of a function that will copy a byte array to storage /// signature (to_slot, from_ptr) -> std::string copyByteArrayToStorageFunction(ArrayType const& _fromType, ArrayType const& _toType); /// @returns the name of a function that will copy an array of value types to storage. /// signature (to_slot, from_ptr[, from_length]) -> std::string copyValueArrayToStorageFunction(ArrayType const& _fromType, ArrayType const& _toType); /// Returns the name of a function that will convert a given length to the /// size in memory (number of storage slots or calldata/memory bytes) it /// will require. /// signature: (length) -> size std::string arrayConvertLengthToSize(ArrayType const& _type); /// @returns the name of a function that computes the number of bytes required /// to store an array in memory given its length (internally encoded, not ABI encoded). /// The function reverts for too large lengths. std::string arrayAllocationSizeFunction(ArrayType const& _type); /// @returns the name of a function that converts a storage slot number /// a memory pointer or a calldata pointer to the slot number / memory pointer / calldata pointer /// for the data position of an array which is stored in that slot / memory area / calldata area. std::string arrayDataAreaFunction(ArrayType const& _type); /// @returns the name of a function that returns the slot and offset for the /// given array and index /// signature: (array, index) -> slot, offset std::string storageArrayIndexAccessFunction(ArrayType const& _type); /// @returns the name of a function that returns the memory address for the /// given array base ref and index. /// Causes invalid opcode on out of range access. /// signature: (baseRef, index) -> address std::string memoryArrayIndexAccessFunction(ArrayType const& _type); /// @returns the name of a function that returns the calldata address for the /// given array base ref and index. /// signature: (baseRef, index) -> offset[, length] std::string calldataArrayIndexAccessFunction(ArrayType const& _type); /// @returns the name of a function that returns offset and length for array slice /// for the given array offset, length and start and end indices for slice /// signature: (arrayOffset, arrayLength, sliceStart, sliceEnd) -> offset, length std::string calldataArrayIndexRangeAccess(ArrayType const& _type); /// @returns the name of a function that follows a calldata tail while performing /// bounds checks. /// signature: (baseRef, tailPointer) -> offset[, length] std::string accessCalldataTailFunction(Type const& _type); /// @returns the name of a function that advances an array data pointer to the next element. /// Only works for memory arrays, calldata arrays and storage arrays that every item occupies one or multiple full slots. std::string nextArrayElementFunction(ArrayType const& _type); /// @returns the name of a function that allocates a memory array and copies the contents /// of the storage array into it. std::string copyArrayFromStorageToMemoryFunction(ArrayType const& _from, ArrayType const& _to); /// @returns the name of a function that does concatenation of variadic number of /// bytes if @a functionTypeKind is FunctionType::Kind::BytesConcat, /// or of strings, if @a functionTypeKind is FunctionType::Kind::StringConcat. std::string bytesOrStringConcatFunction( std::vector<Type const*> const& _argumentTypes, FunctionType::Kind _functionTypeKind ); /// @returns the name of a function that performs index access for mappings. /// @param _mappingType the type of the mapping /// @param _keyType the type of the value provided std::string mappingIndexAccessFunction(MappingType const& _mappingType, Type const& _keyType); /// @returns a function that reads a type from storage. /// @param _splitFunctionTypes if false, returns the address and function signature in a /// single variable. std::string readFromStorage( Type const& _type, size_t _offset, bool _splitFunctionTypes, VariableDeclaration::Location _location ); std::string readFromStorageDynamic( Type const& _type, bool _splitFunctionTypes, VariableDeclaration::Location _location ); /// @returns a function that reads a value type from memory. Performs cleanup. /// signature: (addr) -> value std::string readFromMemory(Type const& _type); /// @returns a function that reads a value type from calldata. /// Reverts on invalid input. /// signature: (addr) -> value std::string readFromCalldata(Type const& _type); /// @returns a function that extracts a value type from storage slot that has been /// retrieved already. /// Performs bit mask/sign extend cleanup and appropriate left / right shift, but not validation. /// /// For external function types, input and output is in "compressed"/"unsplit" form. std::string extractFromStorageValue(Type const& _type, size_t _offset); std::string extractFromStorageValueDynamic(Type const& _type); /// Returns the name of a function will write the given value to /// the specified slot and offset. If offset is not given, it is expected as /// runtime parameter. /// For reference types, offset is checked to be zero at runtime. /// signature: (slot, [offset,] value) std::string updateStorageValueFunction( Type const& _fromType, Type const& _toType, VariableDeclaration::Location _location, std::optional<unsigned> const& _offset = std::optional<unsigned>() ); /// Returns the name of a function that will write the given value to /// the specified address. /// Performs a cleanup before writing for value types. /// signature: (memPtr, value) -> std::string writeToMemoryFunction(Type const& _type); /// Performs cleanup after reading from a potentially compressed storage slot. /// The function does not perform any validation, it just masks or sign-extends /// higher order bytes or left-aligns (in case of bytesNN). /// The storage cleanup expects the value to be right-aligned with potentially /// dirty higher order bytes. /// For external functions, input and output is in "compressed"/"unsplit" form. std::string cleanupFromStorageFunction(Type const& _type); /// @returns the name of a function that prepares a value of the given type /// for being stored in storage. This usually includes cleanup and right-alignment /// to fit the number of bytes in storage. /// The resulting value might still have dirty higher order bits. std::string prepareStoreFunction(Type const& _type); /// @returns the name of a function that allocates memory. /// Modifies the "free memory pointer" /// signature: (size) -> memPtr std::string allocationFunction(); /// @returns the name of the function that allocates memory whose size might be defined later. /// The allocation can be finalized using finalizeAllocationFunction. /// Any other allocation will invalidate the memory pointer unless finalizeAllocationFunction /// is called. /// signature: () -> memPtr std::string allocateUnboundedFunction(); /// @returns the name of the function that finalizes an unbounded memory allocation, /// i.e. sets its size and makes the allocation permanent. /// signature: (memPtr, size) -> std::string finalizeAllocationFunction(); /// @returns the name of a function that zeroes an array. /// signature: (dataStart, dataSizeInBytes) -> std::string zeroMemoryArrayFunction(ArrayType const& _type); /// @returns the name of a function that zeroes a chunk of memory. /// signature: (dataStart, dataSizeInBytes) -> std::string zeroMemoryFunction(Type const& _type); /// @returns the name of a function that zeroes an array /// where the base does not have simple zero value in memory. /// signature: (dataStart, dataSizeInBytes) -> std::string zeroComplexMemoryArrayFunction(ArrayType const& _type); /// @returns the name of a function that allocates a memory array. /// For dynamic arrays it adds space for length and stores it. /// The contents of the data area are unspecified. /// signature: (length) -> memPtr std::string allocateMemoryArrayFunction(ArrayType const& _type); /// @returns the name of a function that allocates and zeroes a memory array. /// For dynamic arrays it adds space for length and stores it. /// signature: (length) -> memPtr std::string allocateAndInitializeMemoryArrayFunction(ArrayType const& _type); /// @returns the name of a function that allocates a memory struct (no /// initialization takes place). /// signature: () -> memPtr std::string allocateMemoryStructFunction(StructType const& _type); /// @returns the name of a function that allocates and zeroes a memory struct. /// signature: () -> memPtr std::string allocateAndInitializeMemoryStructFunction(StructType const& _type); /// @returns the name of the function that converts a value of type @a _from /// to a value of type @a _to. The resulting vale is guaranteed to be in range /// (i.e. "clean"). Asserts on failure. /// /// This is used for data being encoded or general type conversions in the code. std::string conversionFunction(Type const& _from, Type const& _to); /// @returns the name of a function that converts bytes array to fixed bytes type /// signature: (array) -> value std::string bytesToFixedBytesConversionFunction(ArrayType const& _from, FixedBytesType const& _to); /// @returns the name of the cleanup function for the given type and /// adds its implementation to the requested functions. /// The cleanup function defers to the validator function with "assert" /// if there is no reasonable way to clean a value. std::string cleanupFunction(Type const& _type); /// @returns the name of the validator function for the given type and /// adds its implementation to the requested functions. /// @param _revertOnFailure if true, causes revert on invalid data, /// otherwise an assertion failure. /// /// This is used for data decoded from external sources. std::string validatorFunction(Type const& _type, bool _revertOnFailure); std::string packedHashFunction(std::vector<Type const*> const& _givenTypes, std::vector<Type const*> const& _targetTypes); /// @returns the name of a function that reverts and uses returndata (if available) /// as reason string. std::string forwardingRevertFunction(); std::string incrementCheckedFunction(Type const& _type); std::string incrementWrappingFunction(Type const& _type); std::string decrementCheckedFunction(Type const& _type); std::string decrementWrappingFunction(Type const& _type); std::string negateNumberCheckedFunction(Type const& _type); std::string negateNumberWrappingFunction(Type const& _type); /// @returns the name of a function that returns the zero value for the /// provided type. /// @param _splitFunctionTypes if false, returns two zeroes std::string zeroValueFunction(Type const& _type, bool _splitFunctionTypes = true); /// @returns the name of a function that will set the given storage item to /// zero /// signature: (slot, offset) -> std::string storageSetToZeroFunction(Type const& _type, VariableDeclaration::Location _location); /// If revertStrings is debug, @returns the name of a function that /// stores @param _message in memory position 0 and reverts. /// Otherwise returns the name of a function that uses "revert(0, 0)". std::string revertReasonIfDebugFunction(std::string const& _message = ""); /// @returns the function body of ``revertReasonIfDebug``. /// Should only be used internally and by the old code generator. static std::string revertReasonIfDebugBody( RevertStrings _revertStrings, std::string const& _allocation, std::string const& _message ); /// Reverts with ``Panic(uint256)`` and the given code. std::string panicFunction(util::PanicCode _code); /// @returns the name of a function that returns the return data selector. /// Returns zero if return data is too short. std::string returnDataSelectorFunction(); /// @returns the name of a function that tries to abi-decode a string from offset 4 in the /// return data. On failure, returns 0, otherwise a pointer to the newly allocated string. /// Does not check the return data signature. /// signature: () -> ptr std::string tryDecodeErrorMessageFunction(); /// @returns the name of a function that tries to abi-decode a uint256 value from offset 4 in the /// return data. /// Does not check the return data signature. /// signature: () -> success, value std::string tryDecodePanicDataFunction(); /// Returns a function name that returns a newly allocated `bytes` array that contains the return data. /// /// If returndatacopy() is not supported by the underlying target, a empty array will be returned instead. std::string extractReturndataFunction(); /// @returns function name that returns constructor arguments copied to memory /// signature: () -> arguments std::string copyConstructorArgumentsToMemoryFunction( ContractDefinition const& _contract, std::string const& _creationObjectName ); /// @returns the name of a function that copies code from a given address to a newly /// allocated byte array in memory. /// Signature: (address) -> mpos std::string externalCodeFunction(); /// @return the name of a function that that checks if two external functions pointers are equal or not std::string externalFunctionPointersEqualFunction(); private: /// @returns the name of a function that copies a struct from calldata or memory to storage /// signature: (slot, value) -> std::string copyStructToStorageFunction(StructType const& _from, StructType const& _to); /// Special case of conversion functions - handles all array conversions. std::string arrayConversionFunction(ArrayType const& _from, ArrayType const& _to); /// Special case of conversionFunction - handles everything that does not /// use exactly one variable to hold the value. std::string conversionFunctionSpecial(Type const& _from, Type const& _to); /// @returns the name of a function that reduces the size of a storage byte array by one element /// signature: (byteArray) std::string storageByteArrayPopFunction(ArrayType const& _type); std::string readFromMemoryOrCalldata(Type const& _type, bool _fromCalldata); /// @returns a function that reads a value type from storage. /// Performs bit mask/sign extend cleanup and appropriate left / right shift, but not validation. /// @param _splitFunctionTypes if false, returns the address and function signature in a /// single variable. /// @param _offset if provided, read from static offset, otherwise offset is a parameter of the Yul function. /// @param _location if provided, indicates whether we're reading from storage our transient storage. std::string readFromStorageValueType( Type const& _type, std::optional<size_t> _offset, bool _splitFunctionTypes, VariableDeclaration::Location _location ); /// @returns a function that reads a reference type from storage to memory (performing a deep copy). std::string readFromStorageReferenceType(Type const& _type); /// @returns the name of a function that will clear given storage slot /// starting with given offset until the end of the slot /// signature: (slot, offset) std::string partialClearStorageSlotFunction(); /// @returns the name of a function that will clear the given storage struct /// signature: (slot) -> std::string clearStorageStructFunction(StructType const& _type); /// @returns the name of a function that resizes a storage byte array /// signature: (array, newLen) std::string resizeDynamicByteArrayFunction(ArrayType const& _type); /// @returns the name of a function that cleans up elements of a storage byte array starting from startIndex. /// It will not copy elements in case of transformation to short byte array, and will not change array length. /// In case of startIndex is greater than len, doesn't do anything. /// In case of short byte array (< 32 bytes) doesn't do anything. /// If the first slot to be cleaned up is partially occupied, does not touch it. Cleans up only completely unused slots. /// signature: (array, len, startIndex) std::string cleanUpDynamicByteArrayEndSlotsFunction(ArrayType const& _type); /// @returns the name of a function that increases size of byte array /// when we resize byte array frextractUsedSetLenom < 32 elements to >= 32 elements or we push to byte array of size 31 copying of data will occur /// signature: (array, data, oldLen, newLen) std::string increaseByteArraySizeFunction(ArrayType const& _type); /// @returns the name of a function that decreases size of byte array /// when we resize byte array from >= 32 elements to < 32 elements or we pop from byte array of size 32 copying of data will occur /// signature: (array, data, oldLen, newLen) std::string decreaseByteArraySizeFunction(ArrayType const& _type); /// @returns the name of a function that sets size of short byte array while copying data /// should be called when we resize from long byte array (more than 32 elements) to short byte array /// signature: (array, data, len) std::string byteArrayTransitLongToShortFunction(ArrayType const& _type); /// @returns the name of a function that extracts only used part of slot that represents short byte array /// signature: (data, len) -> data std::string shortByteArrayEncodeUsedAreaSetLengthFunction(); /// @returns the name of a function that calculates slot and offset for index /// Doesn't perform length checks, assumes that index is in bounds /// signature: (array, index) std::string longByteArrayStorageIndexAccessNoCheckFunction(); langutil::EVMVersion m_evmVersion; RevertStrings m_revertStrings; MultiUseYulFunctionCollector& m_functionCollector; }; }
29,077
C++
.h
525
53.131429
154
0.760394
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,542
IRGeneratorForStatements.h
ethereum_solidity/libsolidity/codegen/ir/IRGeneratorForStatements.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 /** * Component that translates Solidity code into Yul at statement level and below. */ #pragma once #include <libsolidity/ast/ASTVisitor.h> #include <libsolidity/codegen/ir/IRLValue.h> #include <libsolidity/codegen/ir/IRVariable.h> #include <libsolidity/interface/OptimiserSettings.h> #include <functional> namespace solidity::frontend { class IRGenerationContext; class YulUtilFunctions; /** * Base class for the statement generator. * Encapsulates access to the yul code stream and handles source code locations. */ class IRGeneratorForStatementsBase: public ASTConstVisitor { public: IRGeneratorForStatementsBase(IRGenerationContext& _context): m_context(_context) {} virtual std::string code() const; std::ostringstream& appendCode(bool _addLocationComment = true); protected: void setLocation(ASTNode const& _node); langutil::SourceLocation m_currentLocation = {}; langutil::SourceLocation m_lastLocation = {}; IRGenerationContext& m_context; private: std::ostringstream m_code; }; /** * Component that translates Solidity's AST into Yul at statement level and below. * It is an AST visitor that appends to an internal string buffer. */ class IRGeneratorForStatements: public IRGeneratorForStatementsBase { public: IRGeneratorForStatements( IRGenerationContext& _context, YulUtilFunctions& _utils, OptimiserSettings& _optimiserSettings, std::function<std::string()> _placeholderCallback = {} ): IRGeneratorForStatementsBase(_context), m_placeholderCallback(std::move(_placeholderCallback)), m_utils(_utils), m_optimiserSettings(_optimiserSettings) {} std::string code() const override; /// Generate the code for the statements in the block; void generate(Block const& _block); /// Generates code to initialize the given state variable. void initializeStateVar(VariableDeclaration const& _varDecl); /// Generates code to initialize the given local variable. void initializeLocalVar(VariableDeclaration const& _varDecl); /// Calculates expression's value and returns variable where it was stored IRVariable evaluateExpression(Expression const& _expression, Type const& _to); /// Defines @a _var using the value of @a _value while performing type conversions, if required. void define(IRVariable const& _var, IRVariable const& _value) { bool _declare = true; declareAssign(_var, _value, _declare); } /// Defines @a _var using the value of @a _value while performing type conversions, if required. /// It also cleans the value of the variable. void defineAndCleanup(IRVariable const& _var, IRVariable const& _value) { bool _forceCleanup = true; bool _declare = true; declareAssign(_var, _value, _declare, _forceCleanup); } /// @returns the name of a function that computes the value of the given constant /// and also generates the function. std::string constantValueFunction(VariableDeclaration const& _constant); void endVisit(VariableDeclarationStatement const& _variableDeclaration) override; bool visit(Conditional const& _conditional) override; bool visit(Assignment const& _assignment) override; bool visit(TupleExpression const& _tuple) override; void endVisit(PlaceholderStatement const& _placeholder) override; bool visit(Block const& _block) override; void endVisit(Block const& _block) override; bool visit(IfStatement const& _ifStatement) override; bool visit(ForStatement const& _forStatement) override; bool visit(WhileStatement const& _whileStatement) override; bool visit(Continue const& _continueStatement) override; bool visit(Break const& _breakStatement) override; void endVisit(Return const& _return) override; bool visit(UnaryOperation const& _unaryOperation) override; bool visit(BinaryOperation const& _binOp) override; void endVisit(FunctionCall const& _funCall) override; void endVisit(FunctionCallOptions const& _funCallOptions) override; bool visit(MemberAccess const& _memberAccess) override; void endVisit(MemberAccess const& _memberAccess) override; bool visit(InlineAssembly const& _inlineAsm) override; void endVisit(IndexAccess const& _indexAccess) override; void endVisit(IndexRangeAccess const& _indexRangeAccess) override; void endVisit(Identifier const& _identifier) override; bool visit(Literal const& _literal) override; void endVisit(RevertStatement const& _revertStatement) override; bool visit(TryStatement const& _tryStatement) override; bool visit(TryCatchClause const& _tryCatchClause) override; private: /// Handles all catch cases of a try statement, except the success-case. void handleCatch(TryStatement const& _tryStatement); void handleCatchFallback(TryCatchClause const& _fallback); /// Generates code to revert with an error. The error arguments are assumed to /// be already evaluated and available in local IRVariables, but not yet /// converted. void revertWithError( std::string const& _signature, std::vector<Type const*> const& _parameterTypes, std::vector<ASTPointer<Expression const>> const& _errorArguments ); void handleVariableReference( VariableDeclaration const& _variable, Expression const& _referencingExpression ); /// Appends code to call an external function with the given arguments. /// All involved expressions have already been visited. void appendExternalFunctionCall( FunctionCall const& _functionCall, std::vector<ASTPointer<Expression const>> const& _arguments ); /// Appends code for .call / .delegatecall / .staticcall. /// All involved expressions have already been visited. void appendBareCall( FunctionCall const& _functionCall, std::vector<ASTPointer<Expression const>> const& _arguments ); /// Requests and assigns the internal ID of the referenced function to the referencing /// expression and adds the function to the internal dispatch. /// If the function is called right away, it does nothing. void assignInternalFunctionIDIfNotCalledDirectly( Expression const& _expression, FunctionDefinition const& _referencedFunction ); /// Generates the required conversion code and @returns an IRVariable referring to the value of @a _variable IRVariable convert(IRVariable const& _variable, Type const& _to); /// Generates the required conversion code and @returns an IRVariable referring to the value of @a _variable /// It also cleans the value of the variable. IRVariable convertAndCleanup(IRVariable const& _from, Type const& _to); /// @returns a Yul expression representing the current value of @a _expression, /// converted to type @a _to if it does not yet have that type. std::string expressionAsType(Expression const& _expression, Type const& _to); /// @returns a Yul expression representing the current value of @a _expression, /// converted to type @a _to if it does not yet have that type. /// It also cleans the value, in case it already has type @a _to. std::string expressionAsCleanedType(Expression const& _expression, Type const& _to); /// @returns an output stream that can be used to define @a _var using a function call or /// single stack slot expression. std::ostream& define(IRVariable const& _var); /// Assigns @a _var to the value of @a _value while performing type conversions, if required. void assign(IRVariable const& _var, IRVariable const& _value) { declareAssign(_var, _value, false); } /// Declares variable @a _var. void declare(IRVariable const& _var); void declareAssign(IRVariable const& _var, IRVariable const& _value, bool _define, bool _forceCleanup = false); /// @returns an IRVariable with the zero /// value of @a _type. /// @param _splitFunctionTypes if false, returns two zeroes IRVariable zeroValue(Type const& _type, bool _splitFunctionTypes = true); void appendAndOrOperatorCode(BinaryOperation const& _binOp); void appendSimpleUnaryOperation(UnaryOperation const& _operation, Expression const& _expr); /// @returns code to perform the given binary operation in the given type on the two values. std::string binaryOperation( langutil::Token _op, Type const& _type, std::string const& _left, std::string const& _right ); /// @returns code to perform the given shift operation. /// The operation itself will be performed in the type of the value, /// while the amount to shift can have its own type. std::string shiftOperation(langutil::Token _op, IRVariable const& _value, IRVariable const& _shiftAmount); /// Assigns the value of @a _value to the lvalue @a _lvalue. void writeToLValue(IRLValue const& _lvalue, IRVariable const& _value); /// @returns a fresh IR variable containing the value of the lvalue @a _lvalue. IRVariable readFromLValue(IRLValue const& _lvalue); /// Stores the given @a _lvalue in m_currentLValue, if it will be written to (willBeWrittenTo). Otherwise /// defines the expression @a _expression by reading the value from @a _lvalue. void setLValue(Expression const& _expression, IRLValue _lvalue); void generateLoop( Statement const& _body, Expression const* _conditionExpression, Statement const* _initExpression = nullptr, ExpressionStatement const* _loopExpression = nullptr, bool _isDoWhile = false, bool _isSimpleCounterLoop = false ); static Type const& type(Expression const& _expression); std::string linkerSymbol(ContractDefinition const& _library) const; std::function<std::string()> m_placeholderCallback; YulUtilFunctions& m_utils; std::optional<IRLValue> m_currentLValue; OptimiserSettings m_optimiserSettings; }; }
10,120
C++
.h
213
45.2723
112
0.784041
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,543
IRGenerationContext.h
ethereum_solidity/libsolidity/codegen/ir/IRGenerationContext.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 /** * Class that contains contextual information during IR generation. */ #pragma once #include <libsolidity/ast/AST.h> #include <libsolidity/codegen/ir/IRVariable.h> #include <libsolidity/interface/DebugSettings.h> #include <libsolidity/codegen/MultiUseYulFunctionCollector.h> #include <libsolidity/codegen/ir/Common.h> #include <liblangutil/CharStreamProvider.h> #include <liblangutil/DebugInfoSelection.h> #include <liblangutil/EVMVersion.h> #include <libsolutil/Common.h> #include <set> #include <string> #include <memory> #include <deque> namespace solidity::frontend { class YulUtilFunctions; class ABIFunctions; using DispatchQueue = std::deque<FunctionDefinition const*>; using InternalDispatchMap = std::map<YulArity, DispatchQueue>; /** * Class that contains contextual information during IR generation. */ class IRGenerationContext { public: enum class ExecutionContext { Creation, Deployed }; IRGenerationContext( langutil::EVMVersion _evmVersion, std::optional<uint8_t> _eofVersion, ExecutionContext _executionContext, RevertStrings _revertStrings, std::map<std::string, unsigned> _sourceIndices, langutil::DebugInfoSelection const& _debugInfoSelection, langutil::CharStreamProvider const* _soliditySourceProvider ): m_evmVersion(_evmVersion), m_eofVersion(_eofVersion), m_executionContext(_executionContext), m_revertStrings(_revertStrings), m_sourceIndices(std::move(_sourceIndices)), m_debugInfoSelection(_debugInfoSelection), m_soliditySourceProvider(_soliditySourceProvider) {} MultiUseYulFunctionCollector& functionCollector() { return m_functions; } /// Adds a Solidity function to the function generation queue and returns the name of the /// corresponding Yul function. std::string enqueueFunctionForCodeGeneration(FunctionDefinition const& _function); /// Pops one item from the function generation queue. Must not be called if the queue is empty. FunctionDefinition const* dequeueFunctionForCodeGeneration(); bool functionGenerationQueueEmpty() { return m_functionGenerationQueue.empty(); } /// Sets the most derived contract (the one currently being compiled)> void setMostDerivedContract(ContractDefinition const& _mostDerivedContract) { m_mostDerivedContract = &_mostDerivedContract; } ContractDefinition const& mostDerivedContract() const; IRVariable const& addLocalVariable(VariableDeclaration const& _varDecl); bool isLocalVariable(VariableDeclaration const& _varDecl) const { return m_localVariables.count(&_varDecl); } IRVariable const& localVariable(VariableDeclaration const& _varDecl); void resetLocalVariables(); /// Registers an immutable variable of the contract. /// Should only be called at construction time. void registerImmutableVariable(VariableDeclaration const& _varDecl); void registerLibraryAddressImmutable(); size_t libraryAddressImmutableOffset() const; size_t libraryAddressImmutableOffsetRelative() const; /// @returns the reserved memory for storing the value of the /// immutable @a _variable during contract creation. size_t immutableMemoryOffset(VariableDeclaration const& _variable) const; size_t immutableMemoryOffsetRelative(VariableDeclaration const& _variable) const; /// @returns the reserved memory and resets it to mark it as used. /// Intended to be used only once for initializing the free memory pointer /// to after the area used for immutables. size_t reservedMemory(); size_t reservedMemorySize() const; void addStateVariable(VariableDeclaration const& _varDecl, u256 _storageOffset, unsigned _byteOffset); bool isStateVariable(VariableDeclaration const& _varDecl) const { return m_stateVariables.count(&_varDecl); } std::pair<u256, unsigned> storageLocationOfStateVariable(VariableDeclaration const& _varDecl) const { solAssert(isStateVariable(_varDecl), ""); return m_stateVariables.at(&_varDecl); } std::string newYulVariable(); void initializeInternalDispatch(InternalDispatchMap _internalDispatchMap); InternalDispatchMap consumeInternalDispatchMap(); bool internalDispatchClean() const { return m_internalDispatchMap.empty(); } /// Notifies the context that a function call that needs to go through internal dispatch was /// encountered while visiting the AST. This ensures that the corresponding dispatch function /// gets added to the dispatch map even if there are no entries in it (which may happen if /// the code contains a call to an uninitialized function variable). void internalFunctionCalledThroughDispatch(YulArity const& _arity); /// Adds a function to the internal dispatch. void addToInternalDispatch(FunctionDefinition const& _function); /// @returns a new copy of the utility function generator (but using the same function set). YulUtilFunctions utils(); langutil::EVMVersion evmVersion() const { return m_evmVersion; } std::optional<uint8_t> eofVersion() const { return m_eofVersion; } ExecutionContext executionContext() const { return m_executionContext; } void setArithmetic(Arithmetic _value) { m_arithmetic = _value; } Arithmetic arithmetic() const { return m_arithmetic; } ABIFunctions abiFunctions(); RevertStrings revertStrings() const { return m_revertStrings; } util::UniqueVector<ContractDefinition const*> const& subObjectsCreated() const { return m_subObjects; } void addSubObject(ContractDefinition const* _contractDefinition) { m_subObjects.pushBack(_contractDefinition); } bool memoryUnsafeInlineAssemblySeen() const { return m_memoryUnsafeInlineAssemblySeen; } void setMemoryUnsafeInlineAssemblySeen() { m_memoryUnsafeInlineAssemblySeen = true; } std::map<std::string, unsigned> const& sourceIndices() const { return m_sourceIndices; } void markSourceUsed(std::string const& _name) { m_usedSourceNames.insert(_name); } std::set<std::string> const& usedSourceNames() const { return m_usedSourceNames; } bool immutableRegistered(VariableDeclaration const& _varDecl) const { return m_immutableVariables.count(&_varDecl); } langutil::DebugInfoSelection debugInfoSelection() const { return m_debugInfoSelection; } langutil::CharStreamProvider const* soliditySourceProvider() const { return m_soliditySourceProvider; } private: langutil::EVMVersion m_evmVersion; std::optional<uint8_t> m_eofVersion; ExecutionContext m_executionContext; RevertStrings m_revertStrings; std::map<std::string, unsigned> m_sourceIndices; std::set<std::string> m_usedSourceNames; ContractDefinition const* m_mostDerivedContract = nullptr; std::map<VariableDeclaration const*, IRVariable> m_localVariables; /// Memory offsets reserved for the values of immutable variables during contract creation. /// This map is empty in the runtime context. std::map<VariableDeclaration const*, size_t> m_immutableVariables; std::optional<size_t> m_libraryAddressImmutableOffset; /// Total amount of reserved memory. Reserved memory is used to store /// immutable variables during contract creation. std::optional<size_t> m_reservedMemory = {0}; /// Storage offsets of state variables std::map<VariableDeclaration const*, std::pair<u256, unsigned>> m_stateVariables; MultiUseYulFunctionCollector m_functions; size_t m_varCounter = 0; /// Whether to use checked or wrapping arithmetic. Arithmetic m_arithmetic = Arithmetic::Checked; /// Flag indicating whether any memory-unsafe inline assembly block was seen. bool m_memoryUnsafeInlineAssemblySeen = false; /// Function definitions queued for code generation. They're the Solidity functions whose calls /// were discovered by the IR generator during AST traversal. /// Note that the queue gets filled in a lazy way - new definitions can be added while the /// collected ones get removed and traversed. /// The order and duplicates are relevant here /// (see: IRGenerationContext::[enqueue|dequeue]FunctionForCodeGeneration) DispatchQueue m_functionGenerationQueue; /// Collection of functions that need to be callable via internal dispatch. /// Note that having a key with an empty set of functions is a valid situation. It means that /// the code contains a call via a pointer even though a specific function is never assigned to it. /// It will fail at runtime but the code must still compile. InternalDispatchMap m_internalDispatchMap; util::UniqueVector<ContractDefinition const*> m_subObjects; langutil::DebugInfoSelection m_debugInfoSelection = {}; langutil::CharStreamProvider const* m_soliditySourceProvider = nullptr; }; }
9,125
C++
.h
171
51.187135
118
0.803704
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,544
IRGenerator.h
ethereum_solidity/libsolidity/codegen/ir/IRGenerator.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 Alex Beregszaszi * @date 2017 * Component that translates Solidity code into Yul. */ #pragma once #include <libsolutil/JSON.h> #include <libsolidity/ast/ASTForward.h> #include <libsolidity/ast/CallGraph.h> #include <libsolidity/codegen/ir/IRGenerationContext.h> #include <libsolidity/codegen/YulUtilFunctions.h> #include <libsolidity/interface/OptimiserSettings.h> #include <liblangutil/CharStreamProvider.h> #include <liblangutil/EVMVersion.h> #include <string> namespace solidity::frontend { class SourceUnit; class IRGenerator { public: using ExecutionContext = IRGenerationContext::ExecutionContext; IRGenerator( langutil::EVMVersion _evmVersion, std::optional<uint8_t> _eofVersion, RevertStrings _revertStrings, std::map<std::string, unsigned> _sourceIndices, langutil::DebugInfoSelection const& _debugInfoSelection, langutil::CharStreamProvider const* _soliditySourceProvider, OptimiserSettings& _optimiserSettings ): m_evmVersion(_evmVersion), m_eofVersion(_eofVersion), m_context( _evmVersion, _eofVersion, ExecutionContext::Creation, _revertStrings, std::move(_sourceIndices), _debugInfoSelection, _soliditySourceProvider ), m_utils(_evmVersion, m_context.revertStrings(), m_context.functionCollector()), m_optimiserSettings(_optimiserSettings) {} /// Generates and returns (unoptimized) IR code. std::string run( ContractDefinition const& _contract, bytes const& _cborMetadata, std::map<ContractDefinition const*, std::string_view const> const& _otherYulSources ); private: std::string generate( ContractDefinition const& _contract, bytes const& _cborMetadata, std::map<ContractDefinition const*, std::string_view const> const& _otherYulSources ); std::string generate(Block const& _block); /// Generates code for all the functions from the function generation queue. /// The resulting code is stored in the function collector in IRGenerationContext. /// @returns A set of ast nodes of the generated functions. std::set<FunctionDefinition const*> generateQueuedFunctions(); /// Generates all the internal dispatch functions necessary to handle any function that could /// possibly be called via a pointer. /// @return The content of the dispatch for reuse in runtime code. Reuse is necessary because /// pointers to functions can be passed from the creation code in storage variables. InternalDispatchMap generateInternalDispatchFunctions(ContractDefinition const& _contract); /// Generates code for and returns the name of the function. std::string generateFunction(FunctionDefinition const& _function); std::string generateModifier( ModifierInvocation const& _modifierInvocation, FunctionDefinition const& _function, std::string const& _nextFunction ); std::string generateFunctionWithModifierInner(FunctionDefinition const& _function); /// Generates a getter for the given declaration and returns its name std::string generateGetter(VariableDeclaration const& _varDecl); /// Generates the external part (ABI decoding and encoding) of a function or getter. std::string generateExternalFunction(ContractDefinition const& _contract, FunctionType const& _functionType); /// Generates code that assigns the initial value of the respective type. std::string generateInitialAssignment(VariableDeclaration const& _varDecl); /// Generates constructors for all contracts in the inheritance hierarchy of /// @a _contract /// If there are user defined constructors, their body will be included in the implicit constructor's body. void generateConstructors(ContractDefinition const& _contract); /// Evaluates constructor's arguments for all base contracts (listed in inheritance specifiers) of /// @a _contract /// @returns Pair of expressions needed to evaluate params and list of parameters in a map contract -> params std::pair<std::string, std::map<ContractDefinition const*, std::vector<std::string>>> evaluateConstructorArguments(ContractDefinition const& _contract); /// Initializes state variables of /// @a _contract /// @returns Source code to initialize state variables std::string initStateVariables(ContractDefinition const& _contract); std::string deployCode(ContractDefinition const& _contract); std::string callValueCheck(); std::string dispatchRoutine(ContractDefinition const& _contract); /// @a _useMemoryGuard If true, use a memory guard, allowing the optimiser /// to perform memory optimizations. std::string memoryInit(bool _useMemoryGuard); void resetContext(ContractDefinition const& _contract, ExecutionContext _context); std::string dispenseLocationComment(ASTNode const& _node); langutil::EVMVersion const m_evmVersion; std::optional<uint8_t> const m_eofVersion; IRGenerationContext m_context; YulUtilFunctions m_utils; OptimiserSettings m_optimiserSettings; }; }
5,542
C++
.h
123
42.723577
110
0.797255
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,545
Common.h
ethereum_solidity/libsolidity/codegen/ir/Common.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 /** * Miscellaneous utilities for use in IR generator. */ #pragma once #include <libsolidity/ast/AST.h> #include <algorithm> #include <string> namespace solidity::frontend { class IRGenerationContext; /** * Structure that describes arity and co-arity of a Yul function, i.e. the number of its inputs and outputs. */ struct YulArity { explicit YulArity(size_t _in, size_t _out): in(_in), out(_out) {} static YulArity fromType(FunctionType const& _functionType); bool operator==(YulArity const& _other) const { return in == _other.in && out == _other.out; } bool operator!=(YulArity const& _other) const { return !(*this == _other); } size_t in; /// Number of input parameters size_t out; /// Number of output parameters }; struct IRNames { static std::string externalFunctionABIWrapper(Declaration const& _functionOrVardecl); static std::string function(FunctionDefinition const& _function); static std::string function(VariableDeclaration const& _varDecl); static std::string modifierInvocation(ModifierInvocation const& _modifierInvocation); static std::string functionWithModifierInner(FunctionDefinition const& _function); static std::string creationObject(ContractDefinition const& _contract); static std::string deployedObject(ContractDefinition const& _contract); static std::string internalDispatch(YulArity const& _arity); static std::string constructor(ContractDefinition const& _contract); static std::string libraryAddressImmutable(); static std::string constantValueFunction(VariableDeclaration const& _constant); static std::string localVariable(VariableDeclaration const& _declaration); static std::string localVariable(Expression const& _expression); /// @returns the variable name that can be used to inspect the success or failure of an external /// function call that was invoked as part of the try statement. static std::string trySuccessConditionVariable(Expression const& _expression); static std::string tupleComponent(size_t _i); static std::string zeroValue(Type const& _type, std::string const& _variableName); }; /** * @returns a source location comment in the form of * `/// @src <sourceIndex>:<locationStart>:<locationEnd>` * and marks the source index as used. */ std::string dispenseLocationComment(langutil::SourceLocation const& _location, IRGenerationContext& _context); std::string dispenseLocationComment(ASTNode const& _node, IRGenerationContext& _context); } // Overloading std::less() makes it possible to use YulArity as a map key. We could define operator< // instead but such an operator would be a bit ambiguous (e.g. YulArity{2, 2} would be greater than // YulArity{1, 10} in lexicographical order but the latter has greater total number of inputs and outputs). template<> struct std::less<solidity::frontend::YulArity> { bool operator() (solidity::frontend::YulArity const& _lhs, solidity::frontend::YulArity const& _rhs) const { return _lhs.in < _rhs.in || (_lhs.in == _rhs.in && _lhs.out < _rhs.out); } };
3,689
C++
.h
76
46.684211
110
0.77614
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,546
FunctionCallGraph.h
ethereum_solidity/libsolidity/analysis/FunctionCallGraph.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 #pragma once #include <libsolidity/ast/ASTForward.h> #include <libsolidity/ast/ASTVisitor.h> #include <libsolidity/ast/CallGraph.h> #include <deque> #include <ostream> namespace solidity::frontend { /** * Creates a function call graph for a contract at the granularity of Solidity functions and modifiers. * or after deployment. The graph does not preserve temporal relations between calls - edges * coming out of the same node show which calls were performed but not in what order. * * Includes the following special nodes: * - Entry: represents a call from the outside of the contract. * After deployment this is the node that connects to all the functions exposed through the * external interface. At contract creation it connects to the constructors and variable * initializers, which are not explicitly called from within another function. * - InternalDispatch: Represents the internal dispatch function, which calls internal functions * determined at runtime by values of variables and expressions. Functions that are not called * right away get an edge from this node. * * Nodes are a variant of either the enum SpecialNode or a CallableDeclaration which currently * can be a function or a modifier. There are no nodes representing event calls. Instead all * emitted events and created contracts are gathered in separate sets included in the graph just * for that purpose. * * Auto-generated getter functions for public state variables are ignored, but function calls * inside initial assignments are included in the creation graph. * * Only calls reachable from an Entry node are included in the graph. The map representing edges * is also guaranteed to contain keys representing all the reachable functions and modifiers, even * if they have no outgoing edges. */ class FunctionCallGraphBuilder: private ASTConstVisitor { public: static CallGraph buildCreationGraph(ContractDefinition const& _contract); static CallGraph buildDeployedGraph( ContractDefinition const& _contract, CallGraph const& _creationGraph ); private: FunctionCallGraphBuilder(ContractDefinition const& _contract): m_contract(_contract) {} bool visit(FunctionCall const& _functionCall) override; bool visit(EmitStatement const& _emitStatement) override; bool visit(Identifier const& _identifier) override; bool visit(MemberAccess const& _memberAccess) override; bool visit(BinaryOperation const& _binaryOperation) override; bool visit(UnaryOperation const& _unaryOperation) override; bool visit(ModifierInvocation const& _modifierInvocation) override; bool visit(NewExpression const& _newExpression) override; void enqueueCallable(CallableDeclaration const& _callable); void processQueue(); void add(CallGraph::Node _caller, CallGraph::Node _callee); void functionReferenced(CallableDeclaration const& _callable, bool _calledDirectly = true); CallGraph::Node m_currentNode = CallGraph::SpecialNode::Entry; ContractDefinition const& m_contract; CallGraph m_graph; std::deque<CallableDeclaration const*> m_visitQueue; }; std::ostream& operator<<(std::ostream& _out, CallGraph::Node const& _node); }
3,851
C++
.h
79
46.759494
103
0.799042
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,547
ImmutableValidator.h
ethereum_solidity/libsolidity/analysis/ImmutableValidator.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 #pragma once #include <libsolidity/ast/ASTVisitor.h> #include <liblangutil/ErrorReporter.h> namespace solidity::frontend { /** * Validates access and initialization of immutable variables: * must be directly initialized in a c'tor or inline */ class ImmutableValidator: private ASTConstVisitor { public: ImmutableValidator(langutil::ErrorReporter& _errorReporter, ContractDefinition const& _contractDefinition): m_mostDerivedContract(_contractDefinition), m_errorReporter(_errorReporter) { } void analyze(); private: bool visit(FunctionDefinition const& _functionDefinition); void endVisit(MemberAccess const& _memberAccess); void endVisit(Identifier const& _identifier); void analyseVariableReference(Declaration const* _variableReference, Expression const& _expression); ContractDefinition const& m_mostDerivedContract; langutil::ErrorReporter& m_errorReporter; }; }
1,579
C++
.h
40
37.5
108
0.810616
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,550
DeclarationContainer.h
ethereum_solidity/libsolidity/analysis/DeclarationContainer.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 Christian <c@ethdev.com> * @date 2014 * Scope - object that holds declaration of names. */ #pragma once #include <libsolidity/ast/ASTForward.h> #include <liblangutil/Exceptions.h> #include <liblangutil/SourceLocation.h> #include <memory> namespace solidity::frontend { /** * Settings for how the function DeclarationContainer::resolveName operates. */ struct ResolvingSettings { /// if true and there are no matching declarations in the current container, /// recursively searches the enclosing containers as well. bool recursive = false; /// if true, include invisible declaration in the results. bool alsoInvisible = false; /// if true, do not include declarations which can never actually be referenced using their /// name alone (without being qualified with the name of scope in which they are declared). bool onlyVisibleAsUnqualifiedNames = false; }; /** * Container that stores mappings between names and declarations. It also contains a link to the * enclosing scope. */ class DeclarationContainer { public: using Homonyms = std::vector<std::pair<langutil::SourceLocation const*, std::vector<Declaration const*>>>; DeclarationContainer() = default; explicit DeclarationContainer(ASTNode const* _enclosingNode, DeclarationContainer* _enclosingContainer): m_enclosingNode(_enclosingNode), m_enclosingContainer(_enclosingContainer) { if (_enclosingContainer) _enclosingContainer->m_innerContainers.emplace_back(this); } /// Registers the declaration in the scope unless its name is already declared or the name is empty. /// @param _name the name to register, if nullptr the intrinsic name of @a _declaration is used. /// @param _location alternative location, used to point at homonymous declarations. /// @param _invisible if true, registers the declaration, reports name clashes but does not return it in @a resolveName. /// @param _update if true, replaces a potential declaration that is already present. /// @returns false if the name was already declared. bool registerDeclaration(Declaration const& _declaration, ASTString const* _name, langutil::SourceLocation const* _location, bool _invisible, bool _update); bool registerDeclaration(Declaration const& _declaration, bool _invisible, bool _update); /// Finds all declarations that in the current scope can be referred to using specified name. /// @param _name the name to look for. /// @param _settings see ResolvingSettings std::vector<Declaration const*> resolveName(ASTString const& _name, ResolvingSettings _settings = ResolvingSettings{}) const; ASTNode const* enclosingNode() const { return m_enclosingNode; } DeclarationContainer const* enclosingContainer() const { return m_enclosingContainer; } std::map<ASTString, std::vector<Declaration const*>> const& declarations() const { return m_declarations; } /// @returns whether declaration is valid, and if not also returns previous declaration. Declaration const* conflictingDeclaration(Declaration const& _declaration, ASTString const* _name = nullptr) const; /// Activates a previously inactive (invisible) variable. To be used in C99 scoping for /// VariableDeclarationStatements. void activateVariable(ASTString const& _name); /// @returns true if declaration is currently invisible. bool isInvisible(ASTString const& _name) const; /// @returns existing declaration names similar to @a _name. /// Searches this and all parent containers. std::vector<ASTString> similarNames(ASTString const& _name) const; /// Populates a vector of (location, declaration) pairs, where location is a location of an inner-scope declaration, /// and declaration is the corresponding homonymous outer-scope declaration. void populateHomonyms(std::back_insert_iterator<Homonyms> _it) const; private: ASTNode const* m_enclosingNode = nullptr; DeclarationContainer const* m_enclosingContainer = nullptr; std::vector<DeclarationContainer const*> m_innerContainers; std::map<ASTString, std::vector<Declaration const*>> m_declarations; std::map<ASTString, std::vector<Declaration const*>> m_invisibleDeclarations; /// List of declarations (name and location) to check later for homonymity. std::vector<std::pair<std::string, langutil::SourceLocation const*>> m_homonymCandidates; }; }
4,964
C++
.h
94
50.797872
157
0.786068
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,552
Scoper.h
ethereum_solidity/libsolidity/analysis/Scoper.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 #pragma once #include <libsolidity/ast/ASTForward.h> #include <libsolidity/ast/ASTVisitor.h> namespace solidity::frontend { /** * AST visitor that assigns syntactic scopes. */ class Scoper: private ASTConstVisitor { public: static void assignScopes(ASTNode const& _astRoot); private: bool visit(ContractDefinition const& _contract) override; void endVisit(ContractDefinition const& _contract) override; bool visitNode(ASTNode const& _node) override; void endVisitNode(ASTNode const& _node) override; ContractDefinition const* m_contract = nullptr; std::vector<ASTNode const*> m_scopes; }; }
1,292
C++
.h
35
35.057143
69
0.795509
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,553
DocStringTagParser.h
ethereum_solidity/libsolidity/analysis/DocStringTagParser.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 #pragma once #include <libsolidity/ast/ASTVisitor.h> namespace solidity::langutil { class ErrorReporter; } namespace solidity::frontend { /** * Parses the doc tags and does basic validity checks. * Stores the parsing results in the AST annotations and reports errors. */ class DocStringTagParser: private ASTConstVisitor { public: explicit DocStringTagParser(langutil::ErrorReporter& _errorReporter): m_errorReporter(_errorReporter) {} bool parseDocStrings(SourceUnit const& _sourceUnit); /// Validate the parsed doc strings, requires parseDocStrings() and the /// DeclarationTypeChecker to have run. bool validateDocStringsUsingTypes(SourceUnit const& _sourceUnit); private: bool visit(ContractDefinition const& _contract) override; bool visit(FunctionDefinition const& _function) override; bool visit(VariableDeclaration const& _variable) override; bool visit(ModifierDefinition const& _modifier) override; bool visit(EventDefinition const& _event) override; bool visit(ErrorDefinition const& _error) override; bool visit(InlineAssembly const& _assembly) override; void checkParameters( CallableDeclaration const& _callable, StructurallyDocumented const& _node, StructurallyDocumentedAnnotation& _annotation ); void handleConstructor( CallableDeclaration const& _callable, StructurallyDocumented const& _node, StructurallyDocumentedAnnotation& _annotation ); void handleCallable( CallableDeclaration const& _callable, StructurallyDocumented const& _node, StructurallyDocumentedAnnotation& _annotation ); void parseDocStrings( StructurallyDocumented const& _node, StructurallyDocumentedAnnotation& _annotation, std::set<std::string> const& _validTags, std::string const& _nodeName ); langutil::ErrorReporter& m_errorReporter; }; }
2,479
C++
.h
66
35.409091
105
0.809842
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,557
GlobalContext.h
ethereum_solidity/libsolidity/analysis/GlobalContext.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 Christian <c@ethdev.com> * @date 2014 * Container of the (implicit and explicit) global objects. */ #pragma once #include <liblangutil/EVMVersion.h> #include <libsolidity/ast/ASTForward.h> #include <map> #include <memory> #include <string> #include <vector> namespace solidity::frontend { class Type; // forward /** * Container for all global objects which look like AST nodes, but are not part of the AST * that is currently being compiled. * @note must not be destroyed or moved during compilation as its objects can be referenced from * other objects. */ class GlobalContext { public: /// Noncopyable. GlobalContext(GlobalContext const&) = delete; GlobalContext& operator=(GlobalContext const&) = delete; GlobalContext(langutil::EVMVersion _evmVersion); void setCurrentContract(ContractDefinition const& _contract); void resetCurrentContract() { m_currentContract = nullptr; } MagicVariableDeclaration const* currentThis() const; MagicVariableDeclaration const* currentSuper() const; /// @returns a vector of all implicit global declarations excluding "this". std::vector<Declaration const*> declarations() const; private: std::vector<std::shared_ptr<MagicVariableDeclaration const>> m_magicVariables; ContractDefinition const* m_currentContract = nullptr; std::map<ContractDefinition const*, std::shared_ptr<MagicVariableDeclaration const>> mutable m_thisPointer; std::map<ContractDefinition const*, std::shared_ptr<MagicVariableDeclaration const>> mutable m_superPointer; }; }
2,213
C++
.h
55
38.4
109
0.792171
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,559
DocStringAnalyser.h
ethereum_solidity/libsolidity/analysis/DocStringAnalyser.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 #pragma once #include <libsolidity/ast/ASTVisitor.h> namespace solidity::langutil { class ErrorReporter; } namespace solidity::frontend { /** * Analyses and validates the doc strings. * Stores the parsing results in the AST annotations and reports errors. */ class DocStringAnalyser: private ASTConstVisitor { public: DocStringAnalyser(langutil::ErrorReporter& _errorReporter): m_errorReporter(_errorReporter) {} bool analyseDocStrings(SourceUnit const& _sourceUnit); private: bool visit(FunctionDefinition const& _function) override; bool visit(VariableDeclaration const& _variable) override; bool visit(ModifierDefinition const& _modifier) override; bool visit(EventDefinition const& _event) override; bool visit(ErrorDefinition const& _error) override; CallableDeclaration const* resolveInheritDoc( std::set<CallableDeclaration const*> const& _baseFunctions, StructurallyDocumented const& _node, StructurallyDocumentedAnnotation& _annotation ); void handleCallable( CallableDeclaration const& _callable, StructurallyDocumented const& _node, StructurallyDocumentedAnnotation& _annotation, FunctionType const* _functionType = nullptr ); langutil::ErrorReporter& m_errorReporter; }; }
1,909
C++
.h
51
35.392157
95
0.809756
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,560
PostTypeContractLevelChecker.h
ethereum_solidity/libsolidity/analysis/PostTypeContractLevelChecker.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 /** * Component that verifies properties at contract level, after the type checker has run. */ #pragma once #include <libsolidity/ast/ASTForward.h> namespace solidity::langutil { class ErrorReporter; } namespace solidity::frontend { /** * Component that verifies properties at contract level, after the type checker has run. */ class PostTypeContractLevelChecker { public: explicit PostTypeContractLevelChecker(langutil::ErrorReporter& _errorReporter): m_errorReporter(_errorReporter) {} /// Performs checks on the given source ast. /// @returns true iff all checks passed. Note even if all checks passed, errors() can still contain warnings bool check(SourceUnit const& _sourceUnit); private: /// Performs checks on the given contract. /// @returns true iff all checks passed. Note even if all checks passed, errors() can still contain warnings bool check(ContractDefinition const& _contract); langutil::ErrorReporter& m_errorReporter; }; }
1,651
C++
.h
44
35.659091
109
0.791223
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,562
ControlFlowRevertPruner.h
ethereum_solidity/libsolidity/analysis/ControlFlowRevertPruner.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 #pragma once #include <libsolidity/ast/AST.h> #include <libsolidity/analysis/ControlFlowGraph.h> #include <libsolutil/Algorithms.h> namespace solidity::frontend { /** * Analyses all function flows and recursively removes all exit edges from CFG * nodes that make function calls that will always revert. */ class ControlFlowRevertPruner { public: ControlFlowRevertPruner(CFG& _cfg): m_cfg(_cfg) {} void run(); private: /// Possible revert states of a function call enum class RevertState { AllPathsRevert, HasNonRevertingPath, Unknown, }; /// Identify revert states of all function flows void findRevertStates(); /// Modify function flows so that edges with reverting function calls are removed void modifyFunctionFlows(); /// Control Flow Graph object. CFG& m_cfg; /// function/contract pairs mapped to their according revert state std::map<CFG::FunctionContractTuple, RevertState> m_functions; std::map< std::tuple<FunctionCall const*, ContractDefinition const*>, FunctionDefinition const* > m_resolveCache; }; }
1,740
C++
.h
51
32.039216
82
0.787336
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,565
ControlFlowAnalyzer.h
ethereum_solidity/libsolidity/analysis/ControlFlowAnalyzer.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 #pragma once #include <libsolidity/analysis/ControlFlowGraph.h> #include <liblangutil/ErrorReporter.h> #include <set> namespace solidity::frontend { class ControlFlowAnalyzer { public: explicit ControlFlowAnalyzer(CFG const& _cfg, langutil::ErrorReporter& _errorReporter): m_cfg(_cfg), m_errorReporter(_errorReporter) {} bool run(); private: void analyze(FunctionDefinition const& _function, ContractDefinition const* _contract, FunctionFlow const& _flow); /// Checks for uninitialized variable accesses in the control flow between @param _entry and @param _exit. /// @param _entry entry node /// @param _exit exit node /// @param _emptyBody whether the body of the function is empty (true) or not (false) /// @param _contractName name of the most derived contract, should be empty /// if the function is also defined in it void checkUninitializedAccess(CFGNode const* _entry, CFGNode const* _exit, bool _emptyBody, std::optional<std::string> _contractName = {}); /// Checks for unreachable code, i.e. code ending in @param _exit, @param _revert or @param _transactionReturn /// that can not be reached from @param _entry. void checkUnreachable(CFGNode const* _entry, CFGNode const* _exit, CFGNode const* _revert, CFGNode const* _transactionReturn); CFG const& m_cfg; langutil::ErrorReporter& m_errorReporter; std::set<langutil::SourceLocation> m_unreachableLocationsAlreadyWarnedFor; std::set<VariableDeclaration const*> m_unassignedReturnVarsAlreadyWarnedFor; }; }
2,187
C++
.h
44
47.75
140
0.778977
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,568
NameAndTypeResolver.h
ethereum_solidity/libsolidity/analysis/NameAndTypeResolver.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 Christian <c@ethdev.com> * @date 2014 * Parser part that determines the declarations corresponding to names and the types of expressions. */ #pragma once #include <libsolidity/analysis/DeclarationContainer.h> #include <libsolidity/analysis/GlobalContext.h> #include <libsolidity/analysis/ReferencesResolver.h> #include <libsolidity/ast/ASTAnnotations.h> #include <libsolidity/ast/ASTVisitor.h> #include <liblangutil/EVMVersion.h> #include <list> #include <map> namespace solidity::langutil { class ErrorReporter; } namespace solidity::frontend { /** * Resolves name references, typenames and sets the (explicitly given) types for all variable * declarations. */ class NameAndTypeResolver { public: /// Noncopyable. NameAndTypeResolver(NameAndTypeResolver const&) = delete; NameAndTypeResolver& operator=(NameAndTypeResolver const&) = delete; /// Creates the resolver with the given declarations added to the global scope. /// @param _scopes mapping of scopes to be used (usually default constructed), these /// are filled during the lifetime of this object. NameAndTypeResolver( GlobalContext& _globalContext, langutil::EVMVersion _evmVersion, langutil::ErrorReporter& _errorReporter, bool _experimentalSolidity ); /// Registers all declarations found in the AST node, usually a source unit. /// @returns false in case of error. /// @param _currentScope should be nullptr but can be used to inject new declarations into /// existing scopes, used by the snippets feature. bool registerDeclarations(SourceUnit& _sourceUnit, ASTNode const* _currentScope = nullptr); /// Applies the effect of import directives. bool performImports(SourceUnit& _sourceUnit, std::map<std::string, SourceUnit const*> const& _sourceUnits); /// Resolves all names and types referenced from the given Source Node. /// @returns false in case of error. bool resolveNamesAndTypes(SourceUnit& _source); /// Updates the given global declaration (used for "this"). Not to be used with declarations /// that create their own scope. /// @returns false in case of error. bool updateDeclaration(Declaration const& _declaration); /// Activates a previously inactive (invisible) variable. To be used in C99 scoping for /// VariableDeclarationStatements. void activateVariable(std::string const& _name); /// Resolves the given @a _name inside the scope @a _scope. If @a _scope is omitted, /// the global scope is used (i.e. the one containing only the pre-defined global variables). /// @returns a pointer to the declaration on success or nullptr on failure. /// SHOULD only be used for testing. std::vector<Declaration const*> resolveName(ASTString const& _name, ASTNode const* _scope = nullptr) const; /// Resolves a name in the "current" scope, but also searches parent scopes. /// Should only be called during the initial resolving phase. std::vector<Declaration const*> nameFromCurrentScope(ASTString const& _name, bool _includeInvisibles = false) const; /// Resolves a path starting from the "current" scope, but also searches parent scopes. /// Should only be called during the initial resolving phase. /// @note Returns a null pointer if any component in the path was not unique or not found. Declaration const* pathFromCurrentScope(std::vector<ASTString> const& _path) const; /// Resolves a path starting from the "current" scope, but also searches parent scopes. /// Should only be called during the initial resolving phase. /// @note Returns an empty vector if any component in the path was non-unique or not found. Otherwise, all declarations along the path are returned. std::vector<Declaration const*> pathFromCurrentScopeWithAllDeclarations(std::vector<ASTString> const& _path, bool _includeInvisibles = false) const; /// Generate and store warnings about declarations with the same name. void warnHomonymDeclarations() const; /// @returns a list of similar identifiers in the current and enclosing scopes. May return empty string if no suggestions. std::string similarNameSuggestions(ASTString const& _name) const; /// Sets the current scope. void setScope(ASTNode const* _node); bool experimentalSolidity() const { return m_experimentalSolidity; } private: /// Internal version of @a resolveNamesAndTypes (called from there) throws exceptions on fatal errors. bool resolveNamesAndTypesInternal(ASTNode& _node, bool _resolveInsideCode = true); /// Imports all members declared directly in the given contract (i.e. does not import inherited members) /// into the current scope if they are not present already. void importInheritedScope(ContractDefinition const& _base); /// Computes "C3-Linearization" of base contracts and stores it inside the contract. Reports errors if any void linearizeBaseContracts(ContractDefinition& _contract); /// Computes the C3-merge of the given list of lists of bases. /// @returns the linearized vector or an empty vector if linearization is not possible. template <class T> static std::vector<T const*> cThreeMerge(std::list<std::list<T const*>>& _toMerge); /// Maps nodes declaring a scope to scopes, i.e. ContractDefinition and FunctionDeclaration, /// where nullptr denotes the global scope. Note that structs are not scope since they do /// not contain code. /// Aliases (for example `import "x" as y;`) create multiple pointers to the same scope. std::map<ASTNode const*, std::shared_ptr<DeclarationContainer>> m_scopes; langutil::EVMVersion m_evmVersion; DeclarationContainer* m_currentScope = nullptr; langutil::ErrorReporter& m_errorReporter; GlobalContext& m_globalContext; bool m_experimentalSolidity = false; }; /** * Traverses the given AST upon construction and fills _scopes with all declarations inside the * AST. */ class DeclarationRegistrationHelper: private ASTVisitor { public: /// Registers declarations in their scopes and creates new scopes as a side-effect /// of construction. /// @param _currentScope should be nullptr if we start at SourceUnit, but can be different /// to inject new declarations into an existing scope, used by snippets. DeclarationRegistrationHelper( std::map<ASTNode const*, std::shared_ptr<DeclarationContainer>>& _scopes, ASTNode& _astRoot, langutil::ErrorReporter& _errorReporter, GlobalContext& _globalContext, ASTNode const* _currentScope = nullptr ); static bool registerDeclaration( DeclarationContainer& _container, Declaration const& _declaration, std::string const* _name, langutil::SourceLocation const* _errorLocation, bool _inactive, langutil::ErrorReporter& _errorReporter ); private: bool visit(SourceUnit& _sourceUnit) override; void endVisit(SourceUnit& _sourceUnit) override; bool visit(ImportDirective& _import) override; bool visit(ContractDefinition& _contract) override; void endVisit(ContractDefinition& _contract) override; void endVisit(VariableDeclarationStatement& _variableDeclarationStatement) override; bool visitNode(ASTNode& _node) override; void endVisitNode(ASTNode& _node) override; void enterNewSubScope(ASTNode& _subScope); void closeCurrentScope(); void registerDeclaration(Declaration& _declaration); static bool isOverloadedFunction(Declaration const& _declaration1, Declaration const& _declaration2); std::map<ASTNode const*, std::shared_ptr<DeclarationContainer>>& m_scopes; ASTNode const* m_currentScope = nullptr; VariableScope* m_currentFunction = nullptr; ContractDefinition const* m_currentContract = nullptr; langutil::ErrorReporter& m_errorReporter; GlobalContext& m_globalContext; }; }
8,254
C++
.h
163
48.552147
149
0.787097
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,569
IRGeneratorForStatements.h
ethereum_solidity/libsolidity/experimental/codegen/IRGeneratorForStatements.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 #pragma once #include <libsolidity/experimental/codegen/IRGenerationContext.h> #include <libsolidity/ast/ASTVisitor.h> #include <functional> #include <sstream> namespace solidity::frontend::experimental { class Analysis; class IRGeneratorForStatements: public ASTConstVisitor { public: IRGeneratorForStatements(IRGenerationContext& _context): m_context(_context) {} std::string generate(ASTNode const& _node); private: bool visit(ExpressionStatement const& _expressionStatement) override; bool visit(Block const& _block) override; bool visit(IfStatement const& _ifStatement) override; bool visit(Assignment const& _assignment) override; bool visit(Identifier const& _identifier) override; bool visit(FunctionCall const& _functionCall) override; void endVisit(FunctionCall const& _functionCall) override; bool visit(ElementaryTypeNameExpression const& _elementaryTypeNameExpression) override; bool visit(MemberAccess const&) override { return true; } bool visit(TupleExpression const&) override; void endVisit(MemberAccess const& _memberAccess) override; bool visit(InlineAssembly const& _inlineAssembly) override; bool visit(BinaryOperation const&) override { return true; } void endVisit(BinaryOperation const& _binaryOperation) override; bool visit(VariableDeclarationStatement const& _variableDeclarationStatement) override; bool visit(Return const&) override { return true; } void endVisit(Return const& _return) override; /// Default visit will reject all AST nodes that are not explicitly supported. bool visitNode(ASTNode const& _node) override; IRGenerationContext& m_context; std::stringstream m_code; enum class Builtins { Identity, FromBool, ToBool }; std::map<Expression const*, std::variant<Declaration const*, Builtins>> m_expressionDeclaration; Type type(ASTNode const& _node) const; FunctionDefinition const& resolveTypeClassFunction(TypeClass _class, std::string _name, Type _type); }; }
2,633
C++
.h
60
41.933333
101
0.807572
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,570
IRGenerationContext.h
ethereum_solidity/libsolidity/experimental/codegen/IRGenerationContext.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 #pragma once #include <libsolidity/ast/ASTForward.h> #include <libsolidity/experimental/analysis/Analysis.h> #include <libsolidity/experimental/ast/TypeSystem.h> #include <list> #include <set> namespace solidity::frontend::experimental { class Analysis; struct IRGenerationContext { Analysis const& analysis; TypeEnvironment const* env = nullptr; void enqueueFunctionDefinition(FunctionDefinition const* _functionDefinition, Type _type) { QueuedFunction queue{_functionDefinition, env->resolve(_type)}; for (auto type: generatedFunctions[_functionDefinition]) if (env->typeEquals(type, _type)) return; functionQueue.emplace_back(queue); } struct QueuedFunction { FunctionDefinition const* function = nullptr; Type type = std::monostate{}; }; std::list<QueuedFunction> functionQueue; std::map<FunctionDefinition const*, std::vector<Type>> generatedFunctions; }; }
1,583
C++
.h
44
33.863636
90
0.793848
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,571
IRGenerator.h
ethereum_solidity/libsolidity/experimental/codegen/IRGenerator.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 #pragma once #include <libsolidity/experimental/codegen/IRGenerationContext.h> #include <libsolidity/interface/DebugSettings.h> #include <libsolidity/interface/OptimiserSettings.h> #include <libsolidity/ast/ASTForward.h> #include <libsolidity/ast/CallGraph.h> #include <libsolidity/experimental/ast/TypeSystem.h> #include <liblangutil/CharStreamProvider.h> #include <liblangutil/DebugInfoSelection.h> #include <liblangutil/EVMVersion.h> #include <libsolutil/JSON.h> #include <string> namespace solidity::frontend::experimental { class Analysis; class IRGenerator { public: IRGenerator( langutil::EVMVersion _evmVersion, std::optional<uint8_t> _eofVersion, RevertStrings /*_revertStrings*/, std::map<std::string, unsigned> /*_sourceIndices*/, langutil::DebugInfoSelection const& /*_debugInfoSelection*/, langutil::CharStreamProvider const* /*_soliditySourceProvider*/, Analysis const& _analysis ); std::string run( ContractDefinition const& _contract, bytes const& _cborMetadata, std::map<ContractDefinition const*, std::string_view const> const& _otherYulSources ); std::string generate(ContractDefinition const& _contract); std::string generate(FunctionDefinition const& _function, Type _type); private: langutil::EVMVersion const m_evmVersion; std::optional<uint8_t> const m_eofVersion; OptimiserSettings const m_optimiserSettings; //langutil::DebugInfoSelection m_debugInfoSelection = {}; //langutil::CharStreamProvider const* m_soliditySourceProvider = nullptr; TypeEnvironment m_env; IRGenerationContext m_context; }; }
2,254
C++
.h
58
36.862069
85
0.802016
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,572
Common.h
ethereum_solidity/libsolidity/experimental/codegen/Common.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 #pragma once #include <libsolidity/ast/AST.h> #include <libsolidity/experimental/ast/TypeSystem.h> #include <algorithm> #include <string> namespace solidity::frontend::experimental { struct IRNames { static std::string function(TypeEnvironment const& _env, FunctionDefinition const& _function, Type _type); static std::string function(VariableDeclaration const& _varDecl); static std::string creationObject(ContractDefinition const& _contract); static std::string deployedObject(ContractDefinition const& _contract); static std::string constructor(ContractDefinition const& _contract); static std::string localVariable(VariableDeclaration const& _declaration); static std::string localVariable(Expression const& _expression); }; }
1,429
C++
.h
32
42.8125
107
0.804755
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,573
DebugWarner.h
ethereum_solidity/libsolidity/experimental/analysis/DebugWarner.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 #pragma once #include <libsolidity/ast/ASTVisitor.h> #include <liblangutil/ErrorReporter.h> namespace solidity::frontend::experimental { class Analysis; class DebugWarner: public ASTConstVisitor { public: DebugWarner(Analysis& _analysis); bool analyze(ASTNode const& _astRoot); private: bool visitNode(ASTNode const& _node) override; Analysis& m_analysis; langutil::ErrorReporter& m_errorReporter; }; }
1,101
C++
.h
31
33.645161
69
0.799811
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,574
TypeInference.h
ethereum_solidity/libsolidity/experimental/analysis/TypeInference.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 #pragma once #include <libsolidity/ast/ASTVisitor.h> #include <libsolidity/experimental/ast/TypeSystem.h> #include <liblangutil/ErrorReporter.h> namespace solidity::frontend::experimental { class Analysis; class TypeInference: public ASTConstVisitor { public: TypeInference(Analysis& _analysis); bool analyze(SourceUnit const& _sourceUnit); struct Annotation { /// Expressions, variable declarations, function declarations. std::optional<Type> type; }; struct TypeMember { Type type; }; struct GlobalAnnotation { std::map<BuiltinClass, TypeClass> builtinClasses; std::map<std::string, BuiltinClass> builtinClassesByName; std::map<TypeClass, std::map<std::string, Type>> typeClassFunctions; std::map<Token, std::tuple<TypeClass, std::string>> operators; std::map<TypeConstructor, std::map<std::string, TypeMember>> members; }; bool visit(Block const&) override { return true; } bool visit(VariableDeclarationStatement const&) override { return true; } void endVisit(VariableDeclarationStatement const& _variableDeclarationStatement) override; bool visit(VariableDeclaration const& _variableDeclaration) override; bool visit(ForAllQuantifier const& _forAllQuantifier) override; bool visit(FunctionDefinition const& _functionDefinition) override; void endVisit(FunctionDefinition const& _functionDefinition) override; bool visit(ParameterList const&) override { return true; } void endVisit(ParameterList const& _parameterList) override; bool visit(SourceUnit const&) override { return true; } bool visit(ContractDefinition const&) override { return true; } bool visit(InlineAssembly const& _inlineAssembly) override; bool visit(ImportDirective const&) override { return true; } bool visit(PragmaDirective const&) override { return false; } bool visit(IfStatement const&) override { return true; } void endVisit(IfStatement const& _ifStatement) override; bool visit(ExpressionStatement const&) override { return true; } bool visit(Assignment const&) override { return true; } void endVisit(Assignment const& _assignment) override; bool visit(Identifier const&) override; bool visit(IdentifierPath const&) override; bool visit(FunctionCall const& _functionCall) override; void endVisit(FunctionCall const& _functionCall) override; bool visit(Return const&) override { return true; } void endVisit(Return const& _return) override; bool visit(MemberAccess const& _memberAccess) override; void endVisit(MemberAccess const& _memberAccess) override; bool visit(TypeClassDefinition const& _typeClassDefinition) override; bool visit(TypeClassInstantiation const& _typeClassInstantiation) override; bool visit(TupleExpression const&) override { return true; } void endVisit(TupleExpression const& _tupleExpression) override; bool visit(TypeDefinition const& _typeDefinition) override; bool visitNode(ASTNode const& _node) override; bool visit(BinaryOperation const& _operation) override; bool visit(Literal const& _literal) override; private: Analysis& m_analysis; langutil::ErrorReporter& m_errorReporter; TypeSystem& m_typeSystem; TypeEnvironment* m_env = nullptr; Type m_voidType; Type m_wordType; Type m_integerType; Type m_unitType; Type m_boolType; std::optional<Type> m_currentFunctionType; Type type(ASTNode const& _node) const; Annotation& annotation(ASTNode const& _node); Annotation const& annotation(ASTNode const& _node) const; GlobalAnnotation& annotation(); void unify(Type _a, Type _b, langutil::SourceLocation _location = {}); /// Creates a polymorphic instance of a global type scheme Type polymorphicInstance(Type const& _scheme); Type memberType(Type _type, std::string _memberName, langutil::SourceLocation _location = {}); enum class ExpressionContext { Term, Type, Sort }; Type handleIdentifierByReferencedDeclaration(langutil::SourceLocation _location, Declaration const& _declaration); TypeConstructor typeConstructor(Declaration const* _type) const; Type type(Declaration const* _type, std::vector<Type> _arguments) const; ExpressionContext m_expressionContext = ExpressionContext::Term; std::set<TypeClassInstantiation const*, ASTCompareByID<TypeClassInstantiation>> m_activeInstantiations; }; }
4,900
C++
.h
105
44.542857
115
0.800587
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,575
FunctionDependencyAnalysis.h
ethereum_solidity/libsolidity/experimental/analysis/FunctionDependencyAnalysis.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 #pragma once #include <liblangutil/ErrorReporter.h> #include <libsolidity/ast/ASTForward.h> #include <libsolidity/ast/ASTVisitor.h> #include <libsolidity/experimental/ast/FunctionCallGraph.h> #include <memory> namespace solidity::frontend::experimental { class Analysis; class FunctionDependencyAnalysis: private ASTConstVisitor { public: FunctionDependencyAnalysis(Analysis& _analysis); bool analyze(SourceUnit const& _sourceUnit); struct Annotation {}; struct GlobalAnnotation { FunctionDependencyGraph functionCallGraph; }; private: bool visit(FunctionDefinition const& _functionDefinition) override; void endVisit(FunctionDefinition const&) override; void endVisit(Identifier const& _identifier) override; void addEdge(FunctionDefinition const* _caller, FunctionDefinition const* _callee); GlobalAnnotation& annotation(); Analysis& m_analysis; langutil::ErrorReporter& m_errorReporter; FunctionDefinition const* m_currentFunction = nullptr; }; }
1,661
C++
.h
44
35.840909
84
0.815461
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,576
Analysis.h
ethereum_solidity/libsolidity/experimental/analysis/Analysis.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 #pragma once #include <libsolidity/experimental/ast/TypeSystem.h> #include <cstdint> #include <memory> #include <vector> namespace solidity::frontend { class SourceUnit; class ASTNode; } namespace solidity::langutil { class ErrorReporter; } namespace solidity::frontend::experimental { class TypeSystem; class Analysis; namespace detail { template<typename Step> struct AnnotationFetcher { Analysis& analysis; typename Step::Annotation& get(ASTNode const& _node); typename Step::GlobalAnnotation& get(); }; template<typename Step> struct ConstAnnotationFetcher { Analysis const& analysis; typename Step::Annotation const& get(ASTNode const& _node) const; typename Step::GlobalAnnotation const& get() const; }; } class Analysis { struct AnnotationContainer; struct GlobalAnnotationContainer; public: Analysis(langutil::ErrorReporter& _errorReporter, uint64_t _maxAstId); Analysis(Analysis const&) = delete; ~Analysis(); Analysis const& operator=(Analysis const&) = delete; bool check(std::vector<std::shared_ptr<SourceUnit const>> const& _sourceUnits); langutil::ErrorReporter& errorReporter() { return m_errorReporter; } uint64_t maxAstId() const { return m_maxAstId; } TypeSystem& typeSystem() { return m_typeSystem; } TypeSystem const& typeSystem() const { return m_typeSystem; } template<typename Step> typename Step::Annotation& annotation(ASTNode const& _node) { return detail::AnnotationFetcher<Step>{*this}.get(_node); } template<typename Step> typename Step::Annotation const& annotation(ASTNode const& _node) const { return detail::ConstAnnotationFetcher<Step>{*this}.get(_node); } template<typename Step> typename Step::GlobalAnnotation& annotation() { return detail::AnnotationFetcher<Step>{*this}.get(); } template<typename Step> typename Step::GlobalAnnotation const& annotation() const { return detail::ConstAnnotationFetcher<Step>{*this}.get(); } AnnotationContainer& annotationContainer(ASTNode const& _node); AnnotationContainer const& annotationContainer(ASTNode const& _node) const; GlobalAnnotationContainer& annotationContainer() { return *m_globalAnnotation; } GlobalAnnotationContainer const& annotationContainer() const { return *m_globalAnnotation; } private: langutil::ErrorReporter& m_errorReporter; TypeSystem m_typeSystem; uint64_t m_maxAstId = 0; std::unique_ptr<AnnotationContainer[]> m_annotations; std::unique_ptr<GlobalAnnotationContainer> m_globalAnnotation; }; }
3,151
C++
.h
95
31.315789
93
0.796443
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,577
TypeClassRegistration.h
ethereum_solidity/libsolidity/experimental/analysis/TypeClassRegistration.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 #pragma once #include <libsolidity/ast/ASTVisitor.h> #include <libsolidity/experimental/ast/TypeSystem.h> namespace solidity::langutil { class ErrorReporter; } namespace solidity::frontend::experimental { class Analysis; class TypeSystem; class TypeClassRegistration: public ASTConstVisitor { public: struct Annotation { // Type classes. std::optional<TypeClass> typeClass; }; struct GlobalAnnotation { }; TypeClassRegistration(Analysis& _analysis); bool analyze(SourceUnit const& _sourceUnit); private: bool visit(TypeClassDefinition const& _typeClassDefinition) override; Analysis& m_analysis; langutil::ErrorReporter& m_errorReporter; TypeSystem& m_typeSystem; }; }
1,380
C++
.h
45
28.777778
70
0.805598
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,578
TypeRegistration.h
ethereum_solidity/libsolidity/experimental/analysis/TypeRegistration.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 #pragma once #include <libsolidity/ast/ASTVisitor.h> #include <libsolidity/experimental/ast/TypeSystem.h> #include <liblangutil/ErrorReporter.h> namespace solidity::frontend::experimental { class Analysis; class TypeRegistration: public ASTConstVisitor { public: using TypeClassInstantiations = std::map<TypeConstructor, TypeClassInstantiation const*>; struct Annotation { // For type class definitions. TypeClassInstantiations instantiations; // For builtins, type definitions, type class definitions, type names and type name expressions. std::optional<TypeConstructor> typeConstructor; }; struct GlobalAnnotation { std::map<PrimitiveClass, TypeClassInstantiations> primitiveClassInstantiations; std::map<BuiltinClass, TypeClassInstantiations> builtinClassInstantiations; std::map<std::string, TypeDefinition const*> builtinTypeDefinitions; }; TypeRegistration(Analysis& _analysis); bool analyze(SourceUnit const& _sourceUnit); private: bool visit(TypeClassDefinition const& _typeClassDefinition) override; bool visit(TypeClassInstantiation const& _typeClassInstantiation) override; bool visit(TypeDefinition const& _typeDefinition) override; void endVisit(TypeDefinition const& _typeDefinition) override; bool visit(UserDefinedTypeName const& _typeName) override; void endVisit(ElementaryTypeNameExpression const& _typeName) override; bool visit(Builtin const& _builtin) override; Annotation& annotation(ASTNode const& _node); GlobalAnnotation& annotation(); Analysis& m_analysis; langutil::ErrorReporter& m_errorReporter; TypeSystem& m_typeSystem; std::set<int64_t> m_visitedClasses; }; }
2,322
C++
.h
56
39.428571
98
0.816408
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,579
SyntaxRestrictor.h
ethereum_solidity/libsolidity/experimental/analysis/SyntaxRestrictor.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 #pragma once #include <libsolidity/ast/ASTVisitor.h> #include <liblangutil/ErrorReporter.h> #include <liblangutil/Exceptions.h> namespace solidity::frontend::experimental { class Analysis; class SyntaxRestrictor: public ASTConstVisitor { public: SyntaxRestrictor(Analysis& _analysis); bool analyze(ASTNode const& _astRoot); private: /// Default visit will reject all AST nodes that are not explicitly allowed. bool visitNode(ASTNode const& _node) override; bool visit(SourceUnit const&) override { return true; } bool visit(PragmaDirective const&) override { return true; } bool visit(ImportDirective const&) override { return true; } bool visit(ContractDefinition const& _contractDefinition) override; bool visit(FunctionDefinition const& _functionDefinition) override; bool visit(ExpressionStatement const&) override { return true; } bool visit(FunctionCall const&) override { return true; } bool visit(Assignment const&) override { return true; } bool visit(Block const&) override { return true; } bool visit(InlineAssembly const&) override { return true; } bool visit(Identifier const&) override { return true; } bool visit(IdentifierPath const&) override { return true; } bool visit(IfStatement const&) override { return true; } bool visit(VariableDeclarationStatement const&) override; bool visit(VariableDeclaration const&) override; bool visit(ElementaryTypeName const&) override { return true; } bool visit(ParameterList const&) override { return true; } bool visit(Return const&) override { return true; } bool visit(MemberAccess const&) override { return true; } bool visit(BinaryOperation const&) override { return true; } bool visit(ElementaryTypeNameExpression const&) override { return true; } bool visit(TupleExpression const&) override { return true; } bool visit(Literal const&) override { return true; } langutil::ErrorReporter& m_errorReporter; }; }
2,592
C++
.h
55
45.2
77
0.789307
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,580
FunctionCallGraph.h
ethereum_solidity/libsolidity/experimental/ast/FunctionCallGraph.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 /// Data structure representing a function dependency graph. #pragma once #include <libsolidity/ast/AST.h> #include <map> #include <set> #include <ostream> namespace solidity::frontend::experimental { struct FunctionDependencyGraph { /// Graph edges. Edges are directed and lead from the caller to the callee. /// The map contains a key for every function, even if does not actually perform /// any calls. std::map<FunctionDefinition const*, std::set<FunctionDefinition const*, ASTCompareByID<FunctionDefinition>>, ASTCompareByID<FunctionDefinition>> edges; }; }
1,259
C++
.h
30
40.133333
152
0.791632
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,581
TypeSystemHelper.h
ethereum_solidity/libsolidity/experimental/ast/TypeSystemHelper.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 #pragma once #include <libsolidity/experimental/ast/TypeSystem.h> #include <libsolidity/ast/ASTForward.h> #include <liblangutil/Token.h> namespace solidity::frontend::experimental { class Analysis; enum class BuiltinClass; //std::optional<TypeConstructor> typeConstructorFromTypeName(Analysis const& _analysis, TypeName const& _typeName); //std::optional<TypeConstructor> typeConstructorFromToken(Analysis const& _analysis, langutil::Token _token); //std::optional<TypeClass> typeClassFromTypeClassName(TypeClassName const& _typeClass); std::optional<BuiltinClass> builtinClassFromToken(langutil::Token _token); struct TypeSystemHelpers { TypeSystem const& typeSystem; std::tuple<TypeConstructor, std::vector<Type>> destTypeConstant(Type _type) const; bool isTypeConstant(Type _type) const; bool isPrimitiveType(Type _type, PrimitiveType _primitiveType) const; Type tupleType(std::vector<Type> _elements) const; std::vector<Type> destTupleType(Type _tupleType) const; Type sumType(std::vector<Type> _elements) const; std::vector<Type> destSumType(Type _tupleType) const; Type functionType(Type _argType, Type _resultType) const; std::tuple<Type, Type> destFunctionType(Type _functionType) const; bool isFunctionType(Type _type) const; Type typeFunctionType(Type _argType, Type _resultType) const; std::tuple<Type, Type> destTypeFunctionType(Type _functionType) const; bool isTypeFunctionType(Type _type) const; std::string sortToString(Sort _sort) const; }; struct TypeEnvironmentHelpers { TypeEnvironment const& env; std::string typeToString(Type const& _type) const; std::string canonicalTypeName(Type _type) const; std::vector<Type> typeVars(Type _type) const; bool hasGenericTypeVars(Type const& _type) const; Type substitute(Type const& _type, Type const& _partToReplace, Type const& _replacement) const; }; }
2,528
C++
.h
54
45.037037
115
0.801136
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,582
Type.h
ethereum_solidity/libsolidity/experimental/ast/Type.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 #pragma once #include <cstddef> #include <set> #include <variant> #include <vector> namespace solidity::frontend::experimental { class TypeSystem; struct TypeConstant; struct TypeVariable; using Type = std::variant<std::monostate, TypeConstant, TypeVariable>; enum class PrimitiveType { Void, Function, TypeFunction, Itself, Unit, Pair, Sum, Word, Bool, Integer }; enum class PrimitiveClass { Type }; // TODO: move elsewhere? enum class BuiltinClass { Integer, Mul, Add, Equal, Less, LessOrEqual, Greater, GreaterOrEqual }; struct TypeConstructor { public: TypeConstructor(TypeConstructor const& _typeConstructor): m_index(_typeConstructor.m_index) {} TypeConstructor& operator=(TypeConstructor const& _typeConstructor) { m_index = _typeConstructor.m_index; return *this; } bool operator<(TypeConstructor const& _rhs) const { return m_index < _rhs.m_index; } bool operator==(TypeConstructor const& _rhs) const { return m_index == _rhs.m_index; } bool operator!=(TypeConstructor const& _rhs) const { return m_index != _rhs.m_index; } private: friend class TypeSystem; TypeConstructor(std::size_t _index): m_index(_index) {} std::size_t m_index = 0; }; struct TypeConstant { TypeConstructor constructor; std::vector<Type> arguments; }; struct TypeClass { public: TypeClass(TypeClass const& _typeClass): m_index(_typeClass.m_index) {} TypeClass& operator=(TypeClass const& _typeConstructor) { m_index = _typeConstructor.m_index; return *this; } bool operator<(TypeClass const& _rhs) const { return m_index < _rhs.m_index; } bool operator==(TypeClass const& _rhs) const { return m_index == _rhs.m_index; } bool operator!=(TypeClass const& _rhs) const { return m_index != _rhs.m_index; } private: friend class TypeSystem; TypeClass(std::size_t _index): m_index(_index) {} std::size_t m_index = 0; }; struct Sort { std::set<TypeClass> classes; bool operator==(Sort const& _rhs) const; bool operator!=(Sort const& _rhs) const { return !operator==(_rhs); } bool operator<=(Sort const& _rhs) const; Sort operator+(Sort const& _rhs) const; Sort operator-(Sort const& _rhs) const; }; struct Arity { std::vector<Sort> argumentSorts; TypeClass typeClass; }; struct TypeVariable { std::size_t index() const { return m_index; } Sort const& sort() const { return m_sort; } private: friend class TypeSystem; std::size_t m_index = 0; Sort m_sort; TypeVariable(std::size_t _index, Sort _sort): m_index(_index), m_sort(std::move(_sort)) {} }; }
3,212
C++
.h
136
21.764706
95
0.750164
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,583
TypeSystem.h
ethereum_solidity/libsolidity/experimental/ast/TypeSystem.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 #pragma once #include <libsolidity/experimental/ast/Type.h> #include <liblangutil/Exceptions.h> #include <optional> #include <string> #include <variant> #include <vector> namespace solidity::frontend { class Declaration; } namespace solidity::frontend::experimental { class TypeEnvironment { public: struct TypeMismatch { Type a; Type b; }; struct SortMismatch { Type type; Sort sort; }; struct RecursiveUnification { Type var; Type type; }; using UnificationFailure = std::variant< TypeMismatch, SortMismatch, RecursiveUnification >; TypeEnvironment(TypeSystem& _typeSystem): m_typeSystem(_typeSystem) {} TypeEnvironment(TypeEnvironment const&) = delete; TypeEnvironment& operator=(TypeEnvironment const&) = delete; TypeEnvironment clone() const; Type resolve(Type _type) const; Type resolveRecursive(Type _type) const; Type fresh(Type _type); [[nodiscard]] std::vector<UnificationFailure> unify(Type _a, Type _b); Sort sort(Type _type) const; bool typeEquals(Type _lhs, Type _rhs) const; TypeSystem& typeSystem() { return m_typeSystem; } TypeSystem const& typeSystem() const { return m_typeSystem; } bool isFixedTypeVar(Type const& _typeVar) const; void fixTypeVars(std::vector<Type> const& _typeVars); private: TypeEnvironment(TypeEnvironment&& _env): m_typeSystem(_env.m_typeSystem), m_typeVariables(std::move(_env.m_typeVariables)) {} [[nodiscard]] std::vector<TypeEnvironment::UnificationFailure> instantiate(TypeVariable _variable, Type _type); TypeSystem& m_typeSystem; /// For each @a TypeVariable (identified by its index) stores the type is has been successfully /// unified with. Used for type resolution. Note that @a Type may itself be a type variable /// or may contain type variables so resolution must be recursive. std::map<size_t, Type> m_typeVariables; /// Type variables marked as fixed free type variables (as opposed to generic type variables). /// Identified by their indices. std::set<size_t> m_fixedTypeVariables; }; class TypeSystem { public: struct TypeConstructorInfo { std::string name; std::string canonicalName; std::vector<Arity> arities; Declaration const* typeDeclaration = nullptr; size_t arguments() const { solAssert(!arities.empty()); return arities.front().argumentSorts.size(); } }; struct TypeClassInfo { Type typeVariable; std::string name; Declaration const* classDeclaration = nullptr; }; TypeSystem(); TypeSystem(TypeSystem const&) = delete; TypeSystem const& operator=(TypeSystem const&) = delete; Type type(PrimitiveType _typeConstructor, std::vector<Type> _arguments) const { return type(m_primitiveTypeConstructors.at(_typeConstructor), std::move(_arguments)); } Type type(TypeConstructor _typeConstructor, std::vector<Type> _arguments) const; std::string typeName(TypeConstructor _typeConstructor) const { // TODO: proper error handling return m_typeConstructors.at(_typeConstructor.m_index).name; } std::string canonicalName(TypeConstructor _typeConstructor) const { // TODO: proper error handling return m_typeConstructors.at(_typeConstructor.m_index).canonicalName; } TypeConstructor declareTypeConstructor(std::string _name, std::string _canonicalName, size_t _arguments, Declaration const* _declaration); TypeConstructor constructor(PrimitiveType _type) const { return m_primitiveTypeConstructors.at(_type); } TypeClass primitiveClass(PrimitiveClass _class) const { return m_primitiveTypeClasses.at(_class); } size_t constructorArguments(TypeConstructor _typeConstructor) const { // TODO: error handling return m_typeConstructors.at(_typeConstructor.m_index).arguments(); } TypeConstructorInfo const& constructorInfo(TypeConstructor _typeConstructor) const { // TODO: error handling return m_typeConstructors.at(_typeConstructor.m_index); } TypeConstructorInfo const& constructorInfo(PrimitiveType _typeConstructor) const { return constructorInfo(constructor(_typeConstructor)); } std::variant<TypeClass, std::string> declareTypeClass(std::string _name, Declaration const* _declaration, bool _primitive = false); [[nodiscard]] std::optional<std::string> instantiateClass(Type _instanceVariable, Arity _arity); Type freshTypeVariable(Sort _sort); TypeEnvironment const& env() const { return m_globalTypeEnvironment; } TypeEnvironment& env() { return m_globalTypeEnvironment; } Type freshVariable(Sort _sort); std::string typeClassName(TypeClass _class) const { return m_typeClasses.at(_class.m_index).name; } Declaration const* typeClassDeclaration(TypeClass _class) const { return m_typeClasses.at(_class.m_index).classDeclaration; } Type typeClassVariable(TypeClass _class) const { return m_typeClasses.at(_class.m_index).typeVariable; } TypeClassInfo const& typeClassInfo(TypeClass _class) const { return m_typeClasses.at(_class.m_index); } private: friend class TypeEnvironment; size_t m_numTypeVariables = 0; std::map<PrimitiveType, TypeConstructor> m_primitiveTypeConstructors; std::map<PrimitiveClass, TypeClass> m_primitiveTypeClasses; std::set<std::string> m_canonicalTypeNames; std::vector<TypeConstructorInfo> m_typeConstructors; std::vector<TypeClassInfo> m_typeClasses; TypeEnvironment m_globalTypeEnvironment{*this}; }; }
5,969
C++
.h
167
33.502994
139
0.785244
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,584
OptimiserSettings.h
ethereum_solidity/libsolidity/interface/OptimiserSettings.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 Alex Beregszaszi * @date 2017 * Helper class for optimiser settings. */ #pragma once #include <liblangutil/Exceptions.h> #include <cstddef> #include <string> namespace solidity::frontend { enum class OptimisationPreset { None, Minimal, Standard, Full, }; struct OptimiserSettings { static char constexpr DefaultYulOptimiserSteps[] = "dhfoDgvulfnTUtnIf" // None of these can make stack problems worse "xa[r]EscLM" // Turn into SSA and simplify "Vcul [j]" // Reverse SSA // should have good "compilability" property here. "Trpeul" // Run functional expression inliner "xa[r]cL" // Turn into SSA again and simplify "gvifM" // Run full inliner "CTUca[r]LSsTFOtfDnca[r]Iulc" // SSA plus simplify "scCTUt" "gvifM" // Run full inliner "x[scCTUt] TOntnfDIul" // Perform structural simplification "gvifM" // Run full inliner "jmul[jul] VcTOcul jmul"; // Make source short and pretty static char constexpr DefaultYulOptimiserCleanupSteps[] = "fDnTOcmuO"; /// No optimisations at all - not recommended. static OptimiserSettings none() { return {}; } /// Minimal optimisations: Peephole and jumpdest remover static OptimiserSettings minimal() { OptimiserSettings s = none(); s.runJumpdestRemover = true; s.runPeephole = true; s.simpleCounterForLoopUncheckedIncrement = true; return s; } /// Standard optimisations. static OptimiserSettings standard() { OptimiserSettings s; s.runOrderLiterals = true; s.runInliner = true; s.runJumpdestRemover = true; s.runPeephole = true; s.runDeduplicate = true; s.runCSE = true; s.runConstantOptimiser = true; s.simpleCounterForLoopUncheckedIncrement = true; s.runYulOptimiser = true; s.optimizeStackAllocation = true; return s; } /// Full optimisations. Currently an alias for standard optimisations. static OptimiserSettings full() { return standard(); } static OptimiserSettings preset(OptimisationPreset _preset) { switch (_preset) { case OptimisationPreset::None: return none(); case OptimisationPreset::Minimal: return minimal(); case OptimisationPreset::Standard: return standard(); case OptimisationPreset::Full: return full(); } util::unreachable(); } bool operator==(OptimiserSettings const& _other) const { return runOrderLiterals == _other.runOrderLiterals && runInliner == _other.runInliner && runJumpdestRemover == _other.runJumpdestRemover && runPeephole == _other.runPeephole && runDeduplicate == _other.runDeduplicate && runCSE == _other.runCSE && runConstantOptimiser == _other.runConstantOptimiser && simpleCounterForLoopUncheckedIncrement == _other.simpleCounterForLoopUncheckedIncrement && optimizeStackAllocation == _other.optimizeStackAllocation && runYulOptimiser == _other.runYulOptimiser && yulOptimiserSteps == _other.yulOptimiserSteps && expectedExecutionsPerDeployment == _other.expectedExecutionsPerDeployment; } bool operator!=(OptimiserSettings const& _other) const { return !(*this == _other); } /// Move literals to the right of commutative binary operators during code generation. /// This helps exploiting associativity. bool runOrderLiterals = false; /// Inliner bool runInliner = false; /// Non-referenced jump destination remover. bool runJumpdestRemover = false; /// Peephole optimizer bool runPeephole = false; /// Assembly block deduplicator bool runDeduplicate = false; /// Common subexpression eliminator based on assembly items. bool runCSE = false; /// Constant optimizer, which tries to find better representations that satisfy the given /// size/cost-trade-off. bool runConstantOptimiser = false; /// Perform more efficient stack allocation for variables during code generation from Yul to bytecode. bool simpleCounterForLoopUncheckedIncrement = false; /// Yul optimiser with default settings. Will only run on certain parts of the code for now. bool optimizeStackAllocation = false; /// Allow unchecked arithmetic when incrementing the counter of certain kinds of 'for' loop bool runYulOptimiser = false; /// Sequence of optimisation steps to be performed by Yul optimiser. /// Note that there are some hard-coded steps in the optimiser and you cannot disable /// them just by setting this to an empty string. Set @a runYulOptimiser to false if you want /// no optimisations. std::string yulOptimiserSteps = DefaultYulOptimiserSteps; /// Sequence of clean-up optimisation steps after yulOptimiserSteps is run. Note that if the string /// is left empty, there will still be hard-coded optimisation steps that will run regardless. /// Set @a runYulOptimiser to false if you want no optimisations. std::string yulOptimiserCleanupSteps = DefaultYulOptimiserCleanupSteps; /// This specifies an estimate on how often each opcode in this assembly will be executed, /// i.e. use a small value to optimise for size and a large value to optimise for runtime gas usage. size_t expectedExecutionsPerDeployment = 200; }; }
5,868
C++
.h
151
36.370861
103
0.749122
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,585
UniversalCallback.h
ethereum_solidity/libsolidity/interface/UniversalCallback.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 #pragma once #include <libsolidity/interface/FileReader.h> #include <libsolidity/interface/SMTSolverCommand.h> namespace solidity::frontend { /// UniversalCallback is used to wrap both FileReader and SMTSolverCommand /// callbacks in a single callback. It uses the Kind of the callback to /// determine which to call internally. class UniversalCallback { public: UniversalCallback(FileReader* _fileReader, SMTSolverCommand& _solver) : m_fileReader{_fileReader}, m_solver{_solver} {} ReadCallback::Result operator()(std::string const& _kind, std::string const& _data) { if (_kind == ReadCallback::kindString(ReadCallback::Kind::ReadFile)) if (!m_fileReader) return ReadCallback::Result{false, "No import callback."}; else return m_fileReader->readFile(_kind, _data); else if (_kind == ReadCallback::kindString(ReadCallback::Kind::SMTQuery)) return m_solver.solve(_kind, _data); solAssert(false, "Unknown callback kind."); } frontend::ReadCallback::Callback callback() const { return *this; } void resetImportCallback() { m_fileReader = nullptr; } SMTSolverCommand& smtCommand() { return m_solver; } private: FileReader* m_fileReader; SMTSolverCommand& m_solver; }; }
1,902
C++
.h
51
35.039216
84
0.770527
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,587
SMTSolverCommand.h
ethereum_solidity/libsolidity/interface/SMTSolverCommand.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 #pragma once #include <libsolidity/interface/ReadFile.h> #include <boost/filesystem.hpp> namespace solidity::frontend { /// SMTSolverCommand wraps an SMT solver called via its binary in the OS. class SMTSolverCommand { public: /// Calls an SMT solver with the given query. frontend::ReadCallback::Result solve(std::string const& _kind, std::string const& _query) const; frontend::ReadCallback::Callback solver() const { return [this](std::string const& _kind, std::string const& _query) { return solve(_kind, _query); }; } void setEldarica(std::optional<unsigned int> timeoutInMilliseconds, bool computeInvariants); void setCvc5(std::optional<unsigned int> timeoutInMilliseconds); void setZ3(std::optional<unsigned int> timeoutInMilliseconds, bool _preprocessing, bool _computeInvariants); private: /// The name of the solver's binary. std::string m_solverCmd; std::vector<std::string> m_arguments; }; }
1,610
C++
.h
38
40.447368
109
0.782191
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,588
ReadFile.h
ethereum_solidity/libsolidity/interface/ReadFile.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 #pragma once #include <liblangutil/Exceptions.h> #include <functional> #include <string> namespace solidity::frontend { class ReadCallback { public: /// Noncopyable. ReadCallback(ReadCallback const&) = delete; ReadCallback& operator=(ReadCallback const&) = delete; /// File reading or generic query result. struct Result { bool success; std::string responseOrErrorMessage; }; enum class Kind { ReadFile, SMTQuery }; static std::string kindString(Kind _kind) { switch (_kind) { case Kind::ReadFile: return "source"; case Kind::SMTQuery: return "smt-query"; default: solAssert(false, ""); } } /// File reading or generic query callback. using Callback = std::function<Result(std::string const&, std::string const&)>; }; }
1,459
C++
.h
53
25.245283
80
0.760948
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,589
StandardCompiler.h
ethereum_solidity/libsolidity/interface/StandardCompiler.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 Alex Beregszaszi * @date 2016 * Standard JSON compiler interface. */ #pragma once #include <libsolidity/interface/CompilerStack.h> #include <libsolutil/JSON.h> #include <liblangutil/DebugInfoSelection.h> #include <optional> #include <utility> #include <variant> namespace solidity::frontend { /** * Standard JSON compiler interface, which expects a JSON input and returns a JSON output. * See docs/using-the-compiler#compiler-input-and-output-json-description. */ class StandardCompiler { public: /// Noncopyable. StandardCompiler(StandardCompiler const&) = delete; StandardCompiler& operator=(StandardCompiler const&) = delete; /// Creates a new StandardCompiler. /// @param _readFile callback used to read files for import statements. Must return /// and must not emit exceptions. explicit StandardCompiler(ReadCallback::Callback _readFile = ReadCallback::Callback(), util::JsonFormat const& _format = {}): m_readFile(std::move(_readFile)), m_jsonPrintingFormat(std::move(_format)) { } /// Sets all input parameters according to @a _input which conforms to the standardized input /// format, performs compilation and returns a standardized output. Json compile(Json const& _input) noexcept; /// Parses input as JSON and performs the above processing steps, returning a serialized JSON /// output. Parsing errors are returned as regular errors. std::string compile(std::string const& _input) noexcept; static Json formatFunctionDebugData( std::map<std::string, evmasm::LinkerObject::FunctionDebugData> const& _debugInfo ); private: struct InputsAndSettings { std::string language; Json errors; CompilerStack::State stopAfter = CompilerStack::State::CompilationSuccessful; std::map<std::string, std::string> sources; std::map<std::string, Json> jsonSources; std::map<util::h256, std::string> smtLib2Responses; langutil::EVMVersion evmVersion; std::optional<uint8_t> eofVersion; std::vector<ImportRemapper::Remapping> remappings; RevertStrings revertStrings = RevertStrings::Default; OptimiserSettings optimiserSettings = OptimiserSettings::minimal(); std::optional<langutil::DebugInfoSelection> debugInfoSelection; std::map<std::string, util::h160> libraries; bool metadataLiteralSources = false; CompilerStack::MetadataFormat metadataFormat = CompilerStack::defaultMetadataFormat(); CompilerStack::MetadataHash metadataHash = CompilerStack::MetadataHash::IPFS; Json outputSelection; ModelCheckerSettings modelCheckerSettings = ModelCheckerSettings{}; bool viaIR = false; }; /// Parses the input json (and potentially invokes the read callback) and either returns /// it in condensed form or an error as a json object. std::variant<InputsAndSettings, Json> parseInput(Json const& _input); std::map<std::string, Json> parseAstFromInput(StringMap const& _sources); Json importEVMAssembly(InputsAndSettings _inputsAndSettings); Json compileSolidity(InputsAndSettings _inputsAndSettings); Json compileYul(InputsAndSettings _inputsAndSettings); ReadCallback::Callback m_readFile; util::JsonFormat m_jsonPrintingFormat; }; }
3,815
C++
.h
90
40.155556
94
0.790936
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,590
CompilerStack.h
ethereum_solidity/libsolidity/interface/CompilerStack.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 Christian <c@ethdev.com> * @author Gav Wood <g@ethdev.com> * @date 2014 * Full-stack compiler that converts a source code string to bytecode. */ #pragma once #include <libsolidity/analysis/FunctionCallGraph.h> #include <libsolidity/interface/ReadFile.h> #include <libsolidity/interface/ImportRemapper.h> #include <libsolidity/interface/OptimiserSettings.h> #include <libsolidity/interface/Version.h> #include <libsolidity/interface/DebugSettings.h> #include <libsolidity/formal/ModelCheckerSettings.h> #include <libsmtutil/SolverInterface.h> #include <liblangutil/CharStreamProvider.h> #include <liblangutil/DebugInfoSelection.h> #include <liblangutil/ErrorReporter.h> #include <liblangutil/EVMVersion.h> #include <liblangutil/SourceLocation.h> #include <libevmasm/AbstractAssemblyStack.h> #include <libevmasm/LinkerObject.h> #include <libsolutil/Common.h> #include <libsolutil/FixedHash.h> #include <libsolutil/LazyInit.h> #include <libsolutil/JSON.h> #include <libyul/ObjectOptimizer.h> #include <functional> #include <memory> #include <ostream> #include <set> #include <string> #include <vector> namespace solidity::langutil { class CharStream; } namespace solidity::evmasm { class Assembly; class AssemblyItem; using AssemblyItems = std::vector<AssemblyItem>; } namespace solidity::yul { class YulStack; } namespace solidity::frontend { // forward declarations class ASTNode; class ContractDefinition; class FunctionDefinition; class SourceUnit; class Compiler; class GlobalContext; class Natspec; class DeclarationContainer; namespace experimental { class Analysis; } /** * Easy to use and self-contained Solidity compiler with as few header dependencies as possible. * It holds state and can be used to either step through the compilation stages (and abort e.g. * before compilation to bytecode) or run the whole compilation in one call. */ class CompilerStack: public langutil::CharStreamProvider, public evmasm::AbstractAssemblyStack { public: /// Noncopyable. CompilerStack(CompilerStack const&) = delete; CompilerStack& operator=(CompilerStack const&) = delete; enum State { Empty, SourcesSet, Parsed, ParsedAndImported, AnalysisSuccessful, CompilationSuccessful }; enum class MetadataFormat { WithReleaseVersionTag, WithPrereleaseVersionTag, NoMetadata }; enum class MetadataHash { IPFS, Bzzr1, None }; enum class CompilationSourceType { /// Regular compilation from Solidity source files. Solidity, /// Compilation from an imported Solidity AST. SolidityAST, }; /// Indicates which stages of the compilation pipeline were explicitly requested and provides /// logic to determine which ones are effectively needed to accomplish that. /// Note that parsing and analysis are not selectable, since they cannot be skipped. struct PipelineConfig { bool irCodegen = false; ///< Want IR output straight from code generator. bool irOptimization = false; ///< Want reparsed IR that went through YulStack. May be optimized or not, depending on settings. bool bytecode = false; ///< Want EVM-level outputs, especially EVM assembly and bytecode. May be optimized or not, depending on settings. bool needIR(bool _viaIR) const { return irCodegen || irOptimization || (bytecode && _viaIR); } bool needIRCodegenOnly(bool _viaIR) const { return !(bytecode && _viaIR) && !irOptimization; } bool needBytecode() const { return bytecode; } PipelineConfig operator|(PipelineConfig const& _other) const { return { irCodegen || _other.irCodegen, irOptimization || _other.irOptimization, bytecode || _other.bytecode, }; } bool operator!=(PipelineConfig const& _other) const { return !(*this == _other); } bool operator==(PipelineConfig const& _other) const { return irCodegen == _other.irCodegen && irOptimization == _other.irOptimization && bytecode == _other.bytecode; } }; using ContractSelection = std::map<std::string, std::map<std::string, CompilerStack::PipelineConfig>>; /// Creates a new compiler stack. /// @param _readFile callback used to read files for import statements. Must return /// and must not emit exceptions. explicit CompilerStack(ReadCallback::Callback _readFile = ReadCallback::Callback()); ~CompilerStack() override; /// @returns the list of errors that occurred during parsing and type checking. langutil::ErrorList const& errors() const { return m_errorReporter.errors(); } /// @returns the current state. State state() const { return m_stackState; } virtual bool compilationSuccessful() const override { return m_stackState >= CompilationSuccessful; } /// Resets the compiler to an empty state. Unless @a _keepSettings is set to true, /// all settings are reset as well. void reset(bool _keepSettings = false); /// Sets path remappings. /// Must be set before parsing. void setRemappings(std::vector<ImportRemapper::Remapping> _remappings); /// Sets library addresses. Addresses are cleared iff @a _libraries is missing. /// Must be set before parsing. void setLibraries(std::map<std::string, util::h160> const& _libraries = {}); /// Changes the optimiser settings. /// Must be set before parsing. void setOptimiserSettings(bool _optimize, size_t _runs = OptimiserSettings{}.expectedExecutionsPerDeployment); /// Changes the optimiser settings. /// Must be set before parsing. void setOptimiserSettings(OptimiserSettings _settings); /// Sets whether to strip revert strings, add additional strings or do nothing at all. void setRevertStringBehaviour(RevertStrings _revertStrings); /// Sets the pipeline to go through the Yul IR or not. /// Must be set before parsing. void setViaIR(bool _viaIR); /// Set the EVM version used before running compile. /// When called without an argument it will revert to the default version. /// Must be set before parsing. void setEVMVersion(langutil::EVMVersion _version = langutil::EVMVersion{}); /// Set the EOF version used before running compile. /// If set to std::nullopt (the default), legacy non-EOF bytecode is generated. void setEOFVersion(std::optional<uint8_t> version); /// Set model checker settings. void setModelCheckerSettings(ModelCheckerSettings _settings); /// Sets names of the contracts from each source that should be compiled. /// If empty, no filtering is performed and every contract found in the supplied sources goes /// through the default pipeline stages (bytecode-only, no IR). /// Source/contract names are not validated - ones that do not exist are ignored. /// The empty source/contract name can be used as a wildcard that matches all sources/contracts. /// If a contract matches more than one entry, the pipeline selection from all matches is combined. void selectContracts(ContractSelection const& _selectedContracts); /// @arg _metadataLiteralSources When true, store sources as literals in the contract metadata. /// Must be set before parsing. void useMetadataLiteralSources(bool _metadataLiteralSources); /// Sets whether and which hash should be used /// to store the metadata in the bytecode. /// @param _metadataHash can be IPFS, Bzzr1, None void setMetadataHash(MetadataHash _metadataHash); /// Select components of debug info that should be included in comments in generated assembly. void selectDebugInfo(langutil::DebugInfoSelection _debugInfoSelection); /// Sets the sources. Must be set before parsing. void setSources(StringMap _sources); /// Adds a response to an SMTLib2 query (identified by the hash of the query input). /// Must be set before parsing. void addSMTLib2Response(util::h256 const& _hash, std::string const& _response); /// Parses all source units that were added /// @returns false on error. bool parse(); /// Imports given SourceUnits so they can be analyzed. Leads to the same internal state as parse(). /// Will throw errors if the import fails void importASTs(std::map<std::string, Json> const& _sources); /// Performs the analysis steps (imports, scopesetting, syntaxCheck, referenceResolving, /// typechecking, staticAnalysis) on previously parsed sources. /// @returns false on error. bool analyze(); /// Parses and analyzes all source units that were added /// @returns false on error. bool parseAndAnalyze(State _stopAfter = State::CompilationSuccessful); /// Compiles the source units that were previously added and parsed. /// @returns false on error. bool compile(State _stopAfter = State::CompilationSuccessful); /// Checks whether experimental analysis is on; used in SyntaxTests to skip compilation in case it's ``true``. /// @returns true if experimental analysis is set bool isExperimentalAnalysis() const { return !!m_experimentalAnalysis; } /// @returns the list of sources (paths) used virtual std::vector<std::string> sourceNames() const override; /// @returns a mapping assigning each source name its index inside the vector returned /// by sourceNames(). std::map<std::string, unsigned> sourceIndices() const; /// @returns the previously used character stream, useful for counting lines during error reporting. langutil::CharStream const& charStream(std::string const& _sourceName) const override; /// @returns the parsed source unit with the supplied name. SourceUnit const& ast(std::string const& _sourceName) const; /// @returns the parsed contract with the supplied name. Throws an exception if the contract /// does not exist. ContractDefinition const& contractDefinition(std::string const& _contractName) const; /// @returns a list of unhandled queries to the SMT solver (has to be supplied in a second run /// by calling @a addSMTLib2Response). std::vector<std::string> const& unhandledSMTLib2Queries() const { return m_unhandledSMTLib2Queries; } /// @returns a list of the contract names in the sources. virtual std::vector<std::string> contractNames() const override; /// @returns the name of the last contract. If _sourceName is defined the last contract of that source will be returned. std::string const lastContractName(std::optional<std::string> const& _sourceName = std::nullopt) const; /// @returns either the contract's name or a mixture of its name and source file, sanitized for filesystem use virtual std::string const filesystemFriendlyName(std::string const& _contractName) const override; /// @returns the IR representation of a contract. std::optional<std::string> const& yulIR(std::string const& _contractName) const; /// @returns the IR representation of a contract AST in format. std::optional<Json> yulIRAst(std::string const& _contractName) const; /// @returns the optimized IR representation of a contract. std::optional<std::string> const& yulIROptimized(std::string const& _contractName) const; /// @returns the optimized IR representation of a contract AST in JSON format. std::optional<Json> yulIROptimizedAst(std::string const& _contractName) const; std::optional<Json> yulCFGJson(std::string const& _contractName) const; /// @returns the assembled object for a contract. virtual evmasm::LinkerObject const& object(std::string const& _contractName) const override; /// @returns the runtime object for the contract. virtual evmasm::LinkerObject const& runtimeObject(std::string const& _contractName) const override; /// @returns normal contract assembly items evmasm::AssemblyItems const* assemblyItems(std::string const& _contractName) const; /// @returns runtime contract assembly items evmasm::AssemblyItems const* runtimeAssemblyItems(std::string const& _contractName) const; /// @returns an array containing all utility sources generated during compilation. /// Format: [ { name: string, id: number, language: "Yul", contents: string }, ... ] Json generatedSources(std::string const& _contractName, bool _runtime = false) const; /// @returns the string that provides a mapping between bytecode and sourcecode or a nullptr /// if the contract does not (yet) have bytecode. virtual std::string const* sourceMapping(std::string const& _contractName) const override; /// @returns the string that provides a mapping between runtime bytecode and sourcecode. /// if the contract does not (yet) have bytecode. virtual std::string const* runtimeSourceMapping(std::string const& _contractName) const override; /// @return a verbose text representation of the assembly. /// @arg _sourceCodes is the map of input files to source code strings /// Prerequisite: Successful compilation. virtual std::string assemblyString(std::string const& _contractName, StringMap const& _sourceCodes = StringMap()) const override; /// @returns a JSON representation of the assembly. /// @arg _sourceCodes is the map of input files to source code strings /// Prerequisite: Successful compilation. virtual Json assemblyJSON(std::string const& _contractName) const override; /// @returns a JSON representing the contract ABI. /// Prerequisite: Successful call to parse or compile. Json const& contractABI(std::string const& _contractName) const; /// @returns a JSON representing the storage layout of the contract. /// Prerequisite: Successful call to parse or compile. Json const& storageLayout(std::string const& _contractName) const; /// @returns a JSON representing the transient storage layout of the contract. /// Prerequisite: Successful call to parse or compile. Json const& transientStorageLayout(std::string const& _contractName) const; /// @returns a JSON representing the contract's user documentation. /// Prerequisite: Successful call to parse or compile. Json const& natspecUser(std::string const& _contractName) const; /// @returns a JSON representing the contract's developer documentation. /// Prerequisite: Successful call to parse or compile. Json const& natspecDev(std::string const& _contractName) const; /// @returns a JSON object with the three members ``methods``, ``events``, ``errors``. Each is a map, mapping identifiers (hashes) to function names. Json interfaceSymbols(std::string const& _contractName) const; /// @returns the Contract Metadata matching the pipeline selected using the viaIR setting. std::string const& metadata(std::string const& _contractName) const { return metadata(contract(_contractName)); } /// @returns the CBOR-encoded metadata matching the pipeline selected using the viaIR setting. bytes cborMetadata(std::string const& _contractName) const { return cborMetadata(_contractName, m_viaIR); } /// @returns the CBOR-encoded metadata. /// @param _forIR If true, the metadata for the IR codegen is used. Otherwise it's the metadata /// for the EVM codegen bytes cborMetadata(std::string const& _contractName, bool _forIR) const; /// @returns a JSON representing the estimated gas usage for contract creation, internal and external functions Json gasEstimates(std::string const& _contractName) const; /// Changes the format of the metadata appended at the end of the bytecode. void setMetadataFormat(MetadataFormat _metadataFormat) { m_metadataFormat = _metadataFormat; } bool isExperimentalSolidity() const; experimental::Analysis const& experimentalAnalysis() const; static MetadataFormat defaultMetadataFormat() { return VersionIsRelease ? MetadataFormat::WithReleaseVersionTag : MetadataFormat::WithPrereleaseVersionTag; } yul::ObjectOptimizer const& objectOptimizer() const { return *m_objectOptimizer; } private: /// The state per source unit. Filled gradually during parsing. struct Source { std::shared_ptr<langutil::CharStream> charStream; std::shared_ptr<SourceUnit> ast; util::h256 mutable keccak256HashCached; util::h256 mutable swarmHashCached; std::string mutable ipfsUrlCached; void reset() { *this = Source(); } util::h256 const& keccak256() const; util::h256 const& swarmHash() const; std::string const& ipfsUrl() const; }; /// The state per contract. Filled gradually during compilation. struct Contract { ContractDefinition const* contract = nullptr; std::shared_ptr<evmasm::Assembly> evmAssembly; std::shared_ptr<evmasm::Assembly> evmRuntimeAssembly; std::optional<std::string> generatedYulUtilityCode; ///< Extra Yul utility code that was used when compiling the creation assembly std::optional<std::string> runtimeGeneratedYulUtilityCode; ///< Extra Yul utility code that was used when compiling the deployed assembly evmasm::LinkerObject object; ///< Deployment object (includes the runtime sub-object). evmasm::LinkerObject runtimeObject; ///< Runtime object. std::optional<std::string> yulIR; ///< Yul IR code straight from the code generator. std::optional<std::string> yulIROptimized; ///< Reparsed and possibly optimized Yul IR code. util::LazyInit<std::string const> metadata; ///< The metadata json that will be hashed into the chain. util::LazyInit<Json const> abi; util::LazyInit<Json const> storageLayout; util::LazyInit<Json const> transientStorageLayout; util::LazyInit<Json const> userDocumentation; util::LazyInit<Json const> devDocumentation; mutable std::optional<std::string const> sourceMapping; mutable std::optional<std::string const> runtimeSourceMapping; }; void createAndAssignCallGraphs(); void findAndReportCyclicContractDependencies(); /// Loads the missing sources from @a _ast (named @a _path) using the callback /// @a m_readFile /// @returns the newly loaded sources. StringMap loadMissingSources(SourceUnit const& _ast); std::string applyRemapping(std::string const& _path, std::string const& _context); bool resolveImports(); /// Store the contract definitions in m_contracts. void storeContractDefinitions(); /// Annotate internal dispatch function Ids void annotateInternalFunctionIDs(); /// @returns true if the source is requested to be compiled. bool isRequestedSource(std::string const& _sourceName) const; /// @returns true if the contract is requested to be compiled. bool isRequestedContract(ContractDefinition const& _contract) const; /// @returns The effective pipeline configuration for a given contract. /// Applies defaults for contracts that were not explicitly selected and combines /// multiple entries if the contact is matched by wildcards. PipelineConfig requestedPipelineConfig(ContractDefinition const& _contract) const; /// Perform the analysis steps of legacy language mode. /// @returns false on error. bool analyzeLegacy(bool _noErrorsSoFar); /// Perform the analysis steps of experimental language mode. /// @returns false on error. bool analyzeExperimental(); /// Assembles the contract. /// This function should only be internally called by compileContract and generateEVMFromIR. void assembleYul( ContractDefinition const& _contract, std::shared_ptr<evmasm::Assembly> _assembly, std::shared_ptr<evmasm::Assembly> _runtimeAssembly ); /// Compile a single contract. /// @param _otherCompilers provides access to compilers of other contracts, to get /// their bytecode if needed. Only filled after they have been compiled. void compileContract( ContractDefinition const& _contract, std::map<ContractDefinition const*, std::shared_ptr<Compiler const>>& _otherCompilers ); /// Generate Yul IR for a single contract. /// Unoptimized IR is stored but otherwise unused, while optimized IR may be used for code /// generation if compilation via IR is enabled. Note that whether "optimized IR" is actually /// optimized depends on the optimizer settings. /// @param _contract Contract to generate IR for. /// @param _unoptimizedOnly If true, only the IR coming directly from the codegen is stored. /// Optimizer is not invoked and optimized IR output is not available, which means that /// optimized IR, its AST or compilation via IR must not be requested. void generateIR(ContractDefinition const& _contract, bool _unoptimizedOnly); /// Generate EVM representation for a single contract. /// Depends on output generated by generateIR. void generateEVMFromIR(ContractDefinition const& _contract); /// Links all the known library addresses in the available objects. Any unknown /// library will still be kept as an unlinked placeholder in the objects. void link(); /// Parses and analyzes specified Yul source and returns the YulStack that can be used to manipulate it. /// Assumes that the IR was generated from sources loaded currently into CompilerStack, which /// means that it is error-free and uses the same settings. yul::YulStack loadGeneratedIR(std::string const& _ir) const; /// @returns the contract object for the given @a _contractName. /// Can only be called after state is CompilationSuccessful. Contract const& contract(std::string const& _contractName) const; /// @returns the source object for the given @a _sourceName. /// Can only be called after state is SourcesSet. Source const& source(std::string const& _sourceName) const; /// @param _forIR If true, include a flag that indicates that the bytecode comes from IR codegen. /// @returns the metadata JSON as a compact string for the given contract. std::string createMetadata(Contract const& _contract, bool _forIR) const; /// @returns the metadata CBOR for the given serialised metadata JSON. /// @param _forIR If true, use the metadata for the IR codegen. Otherwise the one for EVM codegen. bytes createCBORMetadata(Contract const& _contract, bool _forIR) const; /// @returns the contract ABI as a JSON object. /// This will generate the JSON object and store it in the Contract object if it is not present yet. Json const& contractABI(Contract const&) const; /// @returns the storage layout of the contract as a JSON object. /// This will generate the JSON object and store it in the Contract object if it is not present yet. Json const& storageLayout(Contract const&) const; /// @returns the transient storage layout of the contract as a JSON object. /// This will generate the JSON object and store it in the Contract object if it is not present yet. Json const& transientStorageLayout(Contract const&) const; /// @returns the Natspec User documentation as a JSON object. /// This will generate the JSON object and store it in the Contract object if it is not present yet. Json const& natspecUser(Contract const&) const; /// @returns the Natspec Developer documentation as a JSON object. /// This will generate the JSON object and store it in the Contract object if it is not present yet. Json const& natspecDev(Contract const&) const; /// @returns the Contract Metadata matching the pipeline selected using the viaIR setting. /// This will generate the metadata and store it in the Contract object if it is not present yet. std::string const& metadata(Contract const& _contract) const; /// @returns the offset of the entry point of the given function into the list of assembly items /// or zero if it is not found or does not exist. size_t functionEntryPoint( std::string const& _contractName, FunctionDefinition const& _function ) const; void reportUnimplementedFeatureError(langutil::UnimplementedFeatureError const& _error); ReadCallback::Callback m_readFile; OptimiserSettings m_optimiserSettings; RevertStrings m_revertStrings = RevertStrings::Default; State m_stopAfter = State::CompilationSuccessful; bool m_viaIR = false; langutil::EVMVersion m_evmVersion; std::optional<uint8_t> m_eofVersion; ModelCheckerSettings m_modelCheckerSettings; ContractSelection m_selectedContracts; std::map<std::string, util::h160> m_libraries; ImportRemapper m_importRemapper; std::map<std::string const, Source> m_sources; std::optional<int64_t> m_maxAstId; std::vector<std::string> m_unhandledSMTLib2Queries; std::map<util::h256, std::string> m_smtlib2Responses; std::shared_ptr<GlobalContext> m_globalContext; std::vector<Source const*> m_sourceOrder; std::map<std::string const, Contract> m_contracts; std::shared_ptr<yul::ObjectOptimizer> m_objectOptimizer; langutil::ErrorList m_errorList; langutil::ErrorReporter m_errorReporter; std::unique_ptr<experimental::Analysis> m_experimentalAnalysis; bool m_metadataLiteralSources = false; MetadataHash m_metadataHash = MetadataHash::IPFS; langutil::DebugInfoSelection m_debugInfoSelection = langutil::DebugInfoSelection::Default(); State m_stackState = Empty; CompilationSourceType m_compilationSourceType = CompilationSourceType::Solidity; MetadataFormat m_metadataFormat = defaultMetadataFormat(); }; }
25,200
C++
.h
486
49.502058
150
0.775319
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,593
ImportRemapper.h
ethereum_solidity/libsolidity/interface/ImportRemapper.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 #pragma once #include <optional> #include <string> #include <vector> namespace solidity::frontend { // Some helper typedefs to make reading the signatures more self explaining. using SourceUnitName = std::string; using SourceCode = std::string; using ImportPath = std::string; /// The ImportRemapper is being used on imported file paths for being remapped to source unit IDs before being loaded. class ImportRemapper { public: struct Remapping { bool operator!=(Remapping const& _other) const noexcept { return !(*this == _other); } bool operator==(Remapping const& _other) const noexcept { return context == _other.context && prefix == _other.prefix && target == _other.target; } std::string context; std::string prefix; std::string target; }; void clear() { m_remappings.clear(); } void setRemappings(std::vector<Remapping> _remappings); std::vector<Remapping> const& remappings() const noexcept { return m_remappings; } SourceUnitName apply(ImportPath const& _path, std::string const& _context) const; /// @returns true if the string can be parsed as a remapping static bool isRemapping(std::string_view _input); /// Parses a remapping of the format "context:prefix=target". static std::optional<Remapping> parseRemapping(std::string_view _input); private: /// list of path prefix remappings, e.g. mylibrary: github.com/ethereum = /usr/local/ethereum /// "context:prefix=target" std::vector<Remapping> m_remappings = {}; }; }
2,169
C++
.h
56
36.5
118
0.759771
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,594
ABI.h
ethereum_solidity/libsolidity/interface/ABI.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 /** * Utilities to handle the Contract ABI (https://docs.soliditylang.org/en/develop/abi-spec.html) */ #pragma once #include <libsolutil/JSON.h> #include <memory> #include <string> namespace solidity::frontend { // Forward declarations class ContractDefinition; class Type; class ABI { public: /// Get the ABI Interface of the contract /// @param _contractDef The contract definition /// @return A JSONrepresentation of the contract's ABI Interface static Json generate(ContractDefinition const& _contractDef); private: /// @returns a json value suitable for a list of types in function input or output /// parameters or other places. If @a _forLibrary is true, complex types are referenced /// by name, otherwise they are anonymously expanded. /// @a _solidityTypes is the list of original Solidity types where @a _encodingTypes is the list of /// ABI types used for the actual encoding. static Json formatTypeList( std::vector<std::string> const& _names, std::vector<Type const*> const& _encodingTypes, std::vector<Type const*> const& _solidityTypes, bool _forLibrary ); /// @returns a Json object with "name", "type", "internalType" and potentially /// "components" keys, according to the ABI specification. /// If it is possible to express the type as a single string, it is allowed to return a single string. /// @a _solidityType is the original Solidity type and @a _encodingTypes is the /// ABI type used for the actual encoding. static Json formatType( std::string const& _name, Type const& _encodingType, Type const& _solidityType, bool _forLibrary ); }; }
2,305
C++
.h
58
37.775862
103
0.762735
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,595
Version.h
ethereum_solidity/libsolidity/interface/Version.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 Christian <c@ethdev.com> * @date 2015 * Versioning. */ #pragma once #include <cstdint> #include <vector> #include <string> namespace solidity { using bytes = std::vector<uint8_t>; namespace frontend { extern char const* VersionNumber; extern std::string const VersionString; extern std::string const VersionStringStrict; extern bytes const VersionCompactBytes; extern bool const VersionIsRelease; } }
1,110
C++
.h
35
30.028571
69
0.792683
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,597
FileReader.h
ethereum_solidity/libsolidity/interface/FileReader.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 #pragma once #include <libsolidity/interface/ImportRemapper.h> #include <libsolidity/interface/ReadFile.h> #include <boost/filesystem.hpp> #include <map> #include <set> namespace solidity::frontend { /// FileReader - used for progressively loading source code. /// /// It is used in solc to load files from CLI parameters, stdin, or from JSON and /// also used in the solc language server where solc is a long running process. class FileReader { public: using StringMap = std::map<SourceUnitName, SourceCode>; using PathMap = std::map<SourceUnitName, boost::filesystem::path>; using FileSystemPathSet = std::set<boost::filesystem::path>; enum SymlinkResolution { Disabled, ///< Do not resolve symbolic links in the path. Enabled, ///< Follow symbolic links. The path should contain no symlinks. }; /// Constructs a FileReader with a base path and sets of include paths and allowed directories /// that will be used when requesting files from this file reader instance. explicit FileReader( boost::filesystem::path _basePath = {}, std::vector<boost::filesystem::path> const& _includePaths = {}, FileSystemPathSet _allowedDirectories = {} ); void setBasePath(boost::filesystem::path const& _path); boost::filesystem::path const& basePath() const noexcept { return m_basePath; } void addIncludePath(boost::filesystem::path const& _path); std::vector<boost::filesystem::path> const& includePaths() const noexcept { return m_includePaths; } void allowDirectory(boost::filesystem::path _path); FileSystemPathSet const& allowedDirectories() const noexcept { return m_allowedDirectories; } /// @returns all sources by their internal source unit names. StringMap const& sourceUnits() const noexcept { return m_sourceCodes; } /// Resets all sources to the given map of source unit name to source codes. /// Does not enforce @a allowedDirectories(). void setSourceUnits(StringMap _sources); /// Adds the source code under a source unit name created by normalizing the file path /// or changes an existing source. /// Does not enforce @a allowedDirectories(). void addOrUpdateFile(boost::filesystem::path const& _path, SourceCode _source); /// Adds the source code under the source unit name of @a <stdin>. /// Does not enforce @a allowedDirectories(). void setStdin(SourceCode _source); /// Receives a @p _sourceUnitName that refers to a source unit in compiler's virtual filesystem /// and attempts to interpret it as a path and read the corresponding file from disk. /// The read will only succeed if the canonical path of the file is within one of the @a allowedDirectories(). /// @param _kind must be equal to "source". Other values are not supported. /// @return Content of the loaded file or an error message. If the operation succeeds, a copy of /// the content is retained in @a sourceUnits() under the key of @a _sourceUnitName. If the key /// already exists, previous content is discarded. frontend::ReadCallback::Result readFile(std::string const& _kind, std::string const& _sourceUnitName); frontend::ReadCallback::Callback reader() { return [this](std::string const& _kind, std::string const& _path) { return readFile(_kind, _path); }; } /// Creates a source unit name by normalizing a path given on the command line and, if possible, /// making it relative to base path or one of the include directories. std::string cliPathToSourceUnitName(boost::filesystem::path const& _cliPath) const; /// Checks if a set contains any paths that lead to different files but would receive identical /// source unit names. Files are considered the same if their paths are exactly the same after /// normalization (without following symlinks). /// @returns a map containing all the conflicting source unit names and the paths that would /// receive them. The returned paths are normalized. std::map<std::string, FileSystemPathSet> detectSourceUnitNameCollisions(FileSystemPathSet const& _cliPaths) const; /// Normalizes a filesystem path to make it include all components up to the filesystem root, /// remove small, inconsequential differences that do not affect the meaning and make it look /// the same on all platforms (if possible). /// The resulting path uses forward slashes as path separators, has no redundant separators, /// has no redundant . or .. segments and has no root name if removing it does not change the meaning. /// The path does not have to actually exist. /// @param _path Path to normalize. /// @param _symlinkResolution If @a Disabled, any symlinks present in @a _path are preserved. static boost::filesystem::path normalizeCLIPathForVFS( boost::filesystem::path const& _path, SymlinkResolution _symlinkResolution = SymlinkResolution::Disabled ); /// Normalizes a root path by excluding, in some cases, its root name. /// The function is used for better portability, and intended to omit root name /// if the path can be used without it. /// @param _path Path to normalize the root path. /// @param _workDir Current working directory path, must be absolute. /// @returns a normalized root path. static boost::filesystem::path normalizeCLIRootPathForVFS( boost::filesystem::path const& _path, boost::filesystem::path const& _workDir = boost::filesystem::current_path() ); /// @returns true if all the path components of @a _prefix are present at the beginning of @a _path. /// Both paths must be absolute (or have slash as root) and normalized (no . or .. segments, no /// multiple consecutive slashes). /// Paths are treated as case-sensitive. Does not require the path to actually exist in the /// filesystem and does not follow symlinks. Only considers whole segments, e.g. /abc/d is not /// considered a prefix of /abc/def. Both paths must be non-empty. /// Ignores the trailing slash, i.e. /a/b/c.sol/ is treated as a valid prefix of /a/b/c.sol. static bool isPathPrefix(boost::filesystem::path const& _prefix, boost::filesystem::path const& _path); /// If @a _prefix is actually a prefix of @p _path, removes it from @a _path to make it relative. /// @returns The path without the prefix or unchanged path if there is not prefix. /// If @a _path and @_prefix are identical, the result is '.'. static boost::filesystem::path stripPrefixIfPresent(boost::filesystem::path const& _prefix, boost::filesystem::path const& _path); /// @returns true if the specified path is an UNC path. /// UNC paths start with // followed by a name (on Windows they can also start with \\). /// They are used for network shares on Windows. On UNIX systems they do not have the same /// functionality but usually they are still recognized and treated in a special way. static bool isUNCPath(boost::filesystem::path const& _path); private: /// If @a _path starts with a number of .. segments, returns a path consisting only of those /// segments (root name is not included). Otherwise returns an empty path. @a _path must be /// absolute (or have slash as root). static boost::filesystem::path absoluteDotDotPrefix(boost::filesystem::path const& _path); /// @returns true if the path contains any .. segments. static bool hasDotDotSegments(boost::filesystem::path const& _path); /// Base path, used for resolving relative paths in imports. boost::filesystem::path m_basePath; /// Additional directories used for resolving relative paths in imports. std::vector<boost::filesystem::path> m_includePaths; /// list of allowed directories to read files from FileSystemPathSet m_allowedDirectories; /// map of input files to source code strings StringMap m_sourceCodes; }; }
8,295
C++
.h
138
57.949275
131
0.75997
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,598
ASTUtils.h
ethereum_solidity/libsolidity/ast/ASTUtils.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 #pragma once namespace solidity::frontend { class ASTNode; class Declaration; class Expression; class SourceUnit; class VariableDeclaration; /// Find the topmost referenced constant variable declaration when the given variable /// declaration value is an identifier. Works only for constant variable declarations. /// Returns nullptr if an identifier in the chain is not referencing a constant variable declaration. VariableDeclaration const* rootConstVariableDeclaration(VariableDeclaration const& _varDecl); /// Returns true if the constant variable declaration is recursive. bool isConstantVariableRecursive(VariableDeclaration const& _varDecl); /// Returns the innermost AST node that covers the given location or nullptr if not found. ASTNode const* locateInnermostASTNode(int _offsetInFile, SourceUnit const& _sourceUnit); /// @returns @a _expr itself, in case it is not a unary tuple expression. Otherwise it descends recursively /// into unary tuples and returns the contained expression. Expression const* resolveOuterUnaryTuples(Expression const* _expr); /// @returns the type of an expression and asserts that it is present. Type const* type(Expression const& _expression); /// @returns the type of the given variable and throws if the type is not present /// (this can happen for variables with non-explicit types before their types are resolved) Type const* type(VariableDeclaration const& _variable); }
2,111
C++
.h
39
52.538462
107
0.809223
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,604
UserDefinableOperators.h
ethereum_solidity/libsolidity/ast/UserDefinableOperators.h
#pragma once #include <liblangutil/Token.h> #include <vector> namespace solidity::frontend { std::vector<langutil::Token> const userDefinableOperators = { // Bitwise langutil::Token::BitOr, langutil::Token::BitAnd, langutil::Token::BitXor, langutil::Token::BitNot, // Arithmetic langutil::Token::Add, langutil::Token::Sub, langutil::Token::Mul, langutil::Token::Div, langutil::Token::Mod, // Comparison langutil::Token::Equal, langutil::Token::NotEqual, langutil::Token::LessThan, langutil::Token::GreaterThan, langutil::Token::LessThanOrEqual, langutil::Token::GreaterThanOrEqual, }; }
610
C++
.h
26
21.576923
61
0.770294
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,611
CallGraph.h
ethereum_solidity/libsolidity/ast/CallGraph.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 /// Data structure representing a function call graph. #pragma once #include <libsolidity/ast/AST.h> #include <map> #include <set> #include <variant> namespace solidity::frontend { /** * Function call graph for a contract at the granularity of Solidity functions and modifiers. * The graph can represent the situation either at contract creation or after deployment. * The graph does not preserve temporal relations between calls - edges coming out of the same node * show which calls were performed but not in what order. * * Stores also extra information about contracts that can be created and events that can be emitted * from any of the functions in it. */ struct CallGraph { enum class SpecialNode { InternalDispatch, Entry, }; using Node = std::variant<CallableDeclaration const*, SpecialNode>; struct CompareByID { using is_transparent = void; bool operator()(Node const& _lhs, Node const& _rhs) const; bool operator()(Node const& _lhs, int64_t _rhs) const; bool operator()(int64_t _lhs, Node const& _rhs) const; }; /// Graph edges. Edges are directed and lead from the caller to the callee. /// The map contains a key for every possible caller, even if does not actually perform /// any calls. std::map<Node, std::set<Node, CompareByID>, CompareByID> edges; /// Contracts that need to be compiled before this one can be compiled. /// The value is the ast node that created the dependency. std::map<ContractDefinition const*, ASTNode const*, ASTCompareByID<ContractDefinition>> bytecodeDependency; /// Events that may get emitted by functions present in the graph. std::set<EventDefinition const*, ASTNode::CompareByID> emittedEvents; /// Errors that are used by functions present in the graph. std::set<ErrorDefinition const*, ASTNode::CompareByID> usedErrors; }; }
2,511
C++
.h
59
40.457627
108
0.77381
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,612
Views.h
ethereum_solidity/libsolutil/Views.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 #pragma once #include <range/v3/view/transform.hpp> #include <liblangutil/Exceptions.h> namespace solidity::util::views { static constexpr auto dereference = ranges::views::transform([](auto&& x) -> decltype(auto) { return *x; }); static constexpr auto dereferenceChecked = ranges::views::transform( [](auto&& x) -> decltype(auto) { solAssert(x, ""); return *x; } ); }
1,069
C++
.h
28
36.142857
108
0.764078
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,613
Numeric.h
ethereum_solidity/libsolutil/Numeric.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 /** * Definition of u256 and similar types and helper functions. */ #pragma once #include <libsolutil/Common.h> #include <libsolutil/CommonData.h> #include <boost/version.hpp> // TODO: do this only conditionally as soon as a boost version with gcc 12 support is released. #if defined(__GNUC__) && !defined(__clang__) && (__GNUC__ >= 12) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wmaybe-uninitialized" #pragma GCC diagnostic ignored "-Warray-bounds" #pragma GCC diagnostic ignored "-Wstringop-overread" #pragma GCC diagnostic ignored "-Waggressive-loop-optimizations" #endif #include <boost/multiprecision/cpp_int.hpp> #if defined(__GNUC__) && !defined(__clang__) && (__GNUC__ >= 12) #pragma GCC diagnostic pop #endif #include <limits> namespace solidity { // Numeric types. using bigint = boost::multiprecision::cpp_int; using u256 = boost::multiprecision::uint256_t; using s256 = boost::multiprecision::int256_t; using u512 = boost::multiprecision::uint512_t; /// Interprets @a _u as a two's complement signed number and returns the resulting s256. inline s256 u2s(u256 _u) { static bigint const c_end = bigint(1) << 256; if (boost::multiprecision::bit_test(_u, 255)) return s256(-(c_end - _u)); else return s256(_u); } /// @returns the two's complement signed representation of the signed number _u. inline u256 s2u(s256 _u) { static bigint const c_end = bigint(1) << 256; if (_u >= 0) return u256(_u); else return u256(c_end + _u); } inline u256 exp256(u256 _base, u256 _exponent) { using boost::multiprecision::limb_type; u256 result = 1; while (_exponent) { if (boost::multiprecision::bit_test(_exponent, 0)) result *= _base; _base *= _base; _exponent >>= 1; } return result; } /// Checks whether _mantissa * (X ** _exp) fits into 4096 bits, /// where X is given indirectly via _log2OfBase = log2(X). bool fitsPrecisionBaseX(bigint const& _mantissa, double _log2OfBase, uint32_t _exp); // Big-endian to/from host endian conversion functions. /// Converts a templated integer value to the big-endian byte-stream represented on a templated collection. /// The size of the collection object will be unchanged. If it is too small, it will not represent the /// value properly, if too big then the additional elements will be zeroed out. /// @a Out will typically be either std::string or bytes. /// @a T will typically by unsigned, u160, u256 or bigint. template <class T, class Out> inline void toBigEndian(T _val, Out&& o_out) { static_assert(std::is_same<bigint, T>::value || !std::numeric_limits<T>::is_signed, "only unsigned types or bigint supported"); //bigint does not carry sign bit on shift for (auto i = o_out.size(); i != 0u; _val >>= 8u, i--) { T v = _val & (T)0xffu; o_out[i - 1u] = (typename std::remove_reference_t<Out>::value_type)(uint8_t)v; } } /// Converts a big-endian byte-stream represented on a templated collection to a templated integer value. /// @a In will typically be either std::string or bytes. /// @a T will typically by unsigned, u256 or bigint. template <class T, class In> inline T fromBigEndian(In const& _bytes) { T ret = (T)0; for (auto i: _bytes) ret = (T)((ret << 8) | (uint8_t)(typename std::make_unsigned<typename In::value_type>::type)i); return ret; } inline bytes toBigEndian(u256 _val) { bytes ret(32); toBigEndian(_val, ret); return ret; } /// Convenience function for toBigEndian. /// @returns a byte array just big enough to represent @a _val. template <class T> inline bytes toCompactBigEndian(T _val, unsigned _min = 0) { static_assert(std::is_same<bigint, T>::value || !std::numeric_limits<T>::is_signed, "only unsigned types or bigint supported"); //bigint does not carry sign bit on shift unsigned i = 0; for (T v = _val; v; ++i, v >>= 8) {} bytes ret(std::max<unsigned>(_min, i), 0); toBigEndian(_val, ret); return ret; } /// Convenience function for conversion of a u256 to hex inline std::string toHex(u256 val) { return util::toHex(toBigEndian(val)); } template <class T> inline std::string toCompactHexWithPrefix(T _value) { return "0x" + util::toHex(toCompactBigEndian(_value, 1)); } /// Returns decimal representation for small numbers and hex for large numbers. inline std::string formatNumber(bigint const& _value) { if (_value < 0) return "-" + formatNumber(-_value); if (_value > 0x1000000) return "0x" + util::toHex(toCompactBigEndian(_value, 1)); else return _value.str(); } inline std::string formatNumber(u256 const& _value) { if (_value > 0x1000000) return toCompactHexWithPrefix(_value); else return _value.str(); } // Algorithms for string and string-like collections. /// Determine bytes required to encode the given integer value. @returns 0 if @a _i is zero. template <class T> inline unsigned numberEncodingSize(T _i) { static_assert(std::is_same<bigint, T>::value || !std::numeric_limits<T>::is_signed, "only unsigned types or bigint supported"); //bigint does not carry sign bit on shift unsigned i = 0; for (; _i != 0; ++i, _i >>= 8) {} return i; } }
5,732
C++
.h
153
35.745098
170
0.728157
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,614
DisjointSet.h
ethereum_solidity/libsolutil/DisjointSet.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 #pragma once #include <cstddef> #include <set> #include <vector> namespace solidity::util { /// Implementation of the Disjoint set data structure [1], also called union-set, with path-halving [2]. /// This implementation assumes that each set element is identified with an element in a iota range (hence contiguous). /// /// [1] https://en.wikipedia.org/wiki/Disjoint-set_data_structure /// [2] Tarjan, Robert E., and Jan Van Leeuwen. "Worst-case analysis of set union algorithms." /// Journal of the ACM (JACM) 31.2 (1984): 245-281. class ContiguousDisjointSet { public: using size_type = size_t; using value_type = size_t; /// Constructs a new disjoint set datastructure with `_numNodes` elements and each element in its own individual set explicit ContiguousDisjointSet(size_t _numNodes); size_type numSets() const; /// finds one representative for a set that contains `_element` value_type find(value_type _element) const; /// joins the two sets containing `_x` and `_y`, returns true if the sets were disjoint, otherwise false void merge(value_type _x, value_type _y, bool _mergeBySize=true); bool sameSubset(value_type _x, value_type _y) const; size_type sizeOfSubset(value_type _x) const; std::set<value_type> subset(value_type _x) const; std::vector<std::set<value_type>> subsets() const; private: std::vector<value_type> mutable m_parents; // mutable for path compression, doesn't change semantic state std::vector<value_type> m_neighbors; std::vector<value_type> m_sizes; size_type m_numSets; }; }
2,229
C++
.h
49
43.571429
119
0.762367
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,617
FunctionSelector.h
ethereum_solidity/libsolutil/FunctionSelector.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 #pragma once #include <libsolutil/Keccak256.h> #include <libsolutil/FixedHash.h> #include <string> namespace solidity::util { /// @returns the ABI selector for a given function signature, as a FixedHash h32. inline FixedHash<4> selectorFromSignatureH32(std::string const& _signature) { return FixedHash<4>(util::keccak256(_signature), FixedHash<4>::AlignLeft); } /// @returns the ABI selector for a given function signature, as a 32 bit number. inline uint32_t selectorFromSignatureU32(std::string const& _signature) { return uint32_t(FixedHash<4>::Arith(selectorFromSignatureH32(_signature))); } /// @returns the ABI selector for a given function signature, as a u256 (left aligned) number. inline u256 selectorFromSignatureU256(std::string const& _signature) { return u256(selectorFromSignatureU32(_signature)) << (256 - 32); } }
1,528
C++
.h
36
40.75
94
0.787306
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,618
TemporaryDirectory.h
ethereum_solidity/libsolutil/TemporaryDirectory.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 /** * Utilities for creating temporary directories and temporarily changing the working directory * for use in tests. */ #pragma once #include <boost/filesystem.hpp> #include <string> #include <vector> namespace solidity::util { /** * An object that creates a unique temporary directory and automatically deletes it and its * content upon being destroyed. * * The directory is guaranteed to be newly created and empty. Directory names are generated * randomly. If a directory with the same name already exists (very unlikely but possible) the * object won't reuse it and will fail with an exception instead. */ class TemporaryDirectory { public: TemporaryDirectory(std::string const& _prefix = "solidity"); TemporaryDirectory( std::vector<boost::filesystem::path> const& _subdirectories, std::string const& _prefix = "solidity" ); ~TemporaryDirectory(); boost::filesystem::path const& path() const { return m_path; } operator boost::filesystem::path() const { return m_path; } private: boost::filesystem::path m_path; }; /** * An object that changes current working directory and restores it upon destruction. */ class TemporaryWorkingDirectory { public: TemporaryWorkingDirectory(boost::filesystem::path const& _newDirectory); ~TemporaryWorkingDirectory(); boost::filesystem::path const& originalWorkingDirectory() const { return m_originalWorkingDirectory; } operator boost::filesystem::path() const { return boost::filesystem::current_path(); } private: boost::filesystem::path m_originalWorkingDirectory; }; }
2,238
C++
.h
60
35.416667
103
0.783734
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,619
Exceptions.h
ethereum_solidity/libsolutil/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 #pragma once #include <liblangutil/SourceLocation.h> #include <boost/exception/exception.hpp> #include <boost/exception/info.hpp> #include <boost/exception/info_tuple.hpp> #include <boost/exception/diagnostic_information.hpp> #include <exception> #include <string> namespace solidity::util { /// Base class for all exceptions. struct Exception: virtual std::exception, virtual boost::exception { char const* what() const noexcept override; /// @returns "FileName:LineNumber" referring to the point where the exception was thrown. std::string lineInfo() const; /// @returns the errinfo_comment of this exception. std::string const* comment() const noexcept; /// @returns the errinfo_sourceLocation of this exception langutil::SourceLocation sourceLocation() const noexcept; }; /// Throws an exception with a given description and extra information about the location the /// exception was thrown from. /// @param _exceptionType The type of the exception to throw (not an instance). /// @param _description The message that describes the error. #define solThrow(_exceptionType, _description) \ ::boost::throw_exception( \ _exceptionType() << \ ::solidity::util::errinfo_comment((_description)) << \ ::boost::throw_function(ETH_FUNC) << \ ::boost::throw_file(__FILE__) << \ ::boost::throw_line(__LINE__) \ ) /// Throws an exception if condition is not met with a given description and extra information about the location the /// exception was thrown from. /// @param _condition if condition is not met, specified exception will be thrown. /// @param _exceptionType The type of the exception to throw (not an instance). /// @param _description The message that describes the error. #define solRequire(_condition, _exceptionType, _description) \ if (!(_condition)) \ solThrow(_exceptionType, (_description)) /// Defines an exception type that's meant to signal a specific condition and be caught rather than /// unwind the stack all the way to the top-level exception handler and interrupt the program. /// As such it does not carry a message - the code catching it is expected to handle it without /// letting it escape. #define DEV_SIMPLE_EXCEPTION(X) struct X: virtual ::solidity::util::Exception { const char* what() const noexcept override { return #X; } } DEV_SIMPLE_EXCEPTION(InvalidAddress); DEV_SIMPLE_EXCEPTION(BadHexCharacter); DEV_SIMPLE_EXCEPTION(BadHexCase); DEV_SIMPLE_EXCEPTION(FileNotFound); DEV_SIMPLE_EXCEPTION(NotAFile); DEV_SIMPLE_EXCEPTION(DataTooLong); DEV_SIMPLE_EXCEPTION(StringTooLong); DEV_SIMPLE_EXCEPTION(InvalidType); // error information to be added to exceptions using errinfo_comment = boost::error_info<struct tag_comment, std::string>; }
3,391
C++
.h
71
46.042254
139
0.774379
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,620
Profiler.h
ethereum_solidity/libsolutil/Profiler.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 #pragma once #include <chrono> #include <map> #include <optional> #include <string> #ifdef PROFILE_OPTIMIZER_STEPS #define PROFILER_PROBE(_scopeName, _variable) solidity::util::Profiler::Probe _variable(_scopeName); #else #define PROFILER_PROBE(_scopeName, _variable) void(0); #endif namespace solidity::util { #ifdef PROFILE_OPTIMIZER_STEPS /// Simpler profiler class that gathers metrics during program execution and prints them out on exit. /// /// To gather metrics, create a Probe instance and let it live until the end of the scope. /// The probe will register its creation and destruction time and store the results in the profiler /// singleton. /// /// Use the PROFILER_PROBE macro to create probes conditionally, in a way that will not affect performance /// unless profiling is enabled at compilation time via PROFILE_OPTIMIZER_STEPS CMake option. /// /// Scopes are identified by the name supplied to the probe. Using the same name multiple times /// will result in metrics for those scopes being aggregated together as if they were the same scope. class Profiler { public: class Probe { public: Probe(std::string _scopeName); ~Probe(); private: std::string m_scopeName; std::chrono::steady_clock::time_point m_startTime; }; static Profiler& singleton(); private: ~Profiler(); struct Metrics { std::chrono::microseconds durationInMicroseconds; size_t callCount; }; /// Summarizes gathered metric and prints a report to standard error output. void outputPerformanceMetrics(); std::map<std::string, Metrics> m_metrics; }; #endif }
2,265
C++
.h
64
33.5625
106
0.78022
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,621
cxx20.h
ethereum_solidity/libsolutil/cxx20.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 #pragma once #include <map> // Contains polyfills of STL functions and algorithms that will become available in C++20. namespace solidity::cxx20 { // Taken from https://en.cppreference.com/w/cpp/container/map/erase_if. template<class Key, class T, class Compare, class Alloc, class Pred> typename std::map<Key, T, Compare, Alloc>::size_type erase_if(std::map<Key,T,Compare,Alloc>& _c, Pred _pred) { auto old_size = _c.size(); for (auto i = _c.begin(), last = _c.end(); i != last;) if (_pred(*i)) i = _c.erase(i); else ++i; return old_size - _c.size(); } // Taken from https://en.cppreference.com/w/cpp/container/unordered_map/erase_if. template<class Key, class T, class Hash, class KeyEqual, class Alloc, class Pred> typename std::unordered_map<Key, T, Hash, KeyEqual, Alloc>::size_type erase_if(std::unordered_map<Key, T, Hash, KeyEqual, Alloc>& _c, Pred _pred) { auto old_size = _c.size(); for (auto i = _c.begin(), last = _c.end(); i != last;) if (_pred(*i)) i = _c.erase(i); else ++i; return old_size - _c.size(); } // Taken from https://en.cppreference.com/w/cpp/container/vector/erase2 template<class T, class Alloc, class Pred> constexpr typename std::vector<T, Alloc>::size_type erase_if(std::vector<T, Alloc>& c, Pred pred) { auto it = std::remove_if(c.begin(), c.end(), pred); auto r = std::distance(it, c.end()); c.erase(it, c.end()); return static_cast<typename std::vector<T, Alloc>::size_type>(r); } }
2,138
C++
.h
55
36.963636
108
0.717936
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,622
ErrorCodes.h
ethereum_solidity/libsolutil/ErrorCodes.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 #pragma once #include <string> namespace solidity::util { enum class PanicCode { Generic = 0x00, // generic / unspecified error Assert = 0x01, // used by the assert() builtin UnderOverflow = 0x11, // arithmetic underflow or overflow DivisionByZero = 0x12, // division or modulo by zero EnumConversionError = 0x21, // enum conversion error StorageEncodingError = 0x22, // invalid encoding in storage EmptyArrayPop = 0x31, // empty array pop ArrayOutOfBounds = 0x32, // array out of bounds access ResourceError = 0x41, // resource error (too large allocation or too large array) InvalidInternalFunction = 0x51, // calling invalid internal function }; }
1,350
C++
.h
32
40.3125
82
0.78032
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,625
CommonIO.h
ethereum_solidity/libsolutil/CommonIO.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 /** @file CommonIO.h * @author Gav Wood <i@gavwood.com> * @date 2014 * * File & stream I/O routines. */ #pragma once #include <boost/filesystem.hpp> #include <libsolutil/Common.h> #include <iostream> #include <sstream> #include <string> namespace solidity { inline std::ostream& operator<<(std::ostream& os, bytes const& _bytes) { std::ostringstream ss; ss << std::hex; std::copy(_bytes.begin(), _bytes.end(), std::ostream_iterator<int>(ss, ",")); std::string result = ss.str(); result.pop_back(); os << "[" + result + "]"; return os; } namespace util { /// Retrieves and returns the contents of the given file as a std::string. /// If the file doesn't exist, it will throw a FileNotFound exception. /// If the file exists but is not a regular file, it will throw NotAFile exception. /// If the file is empty, returns an empty string. std::string readFileAsString(boost::filesystem::path const& _file); /// Retrieves and returns the whole content of the specified input stream (until EOF). std::string readUntilEnd(std::istream& _stdin); /// Tries to read exactly @a _length bytes from @a _input. /// Returns a string containing as much data as has been read. std::string readBytes(std::istream& _input, size_t _length); /// Retrieves and returns a character from standard input (without waiting for EOL). int readStandardInputChar(); /// Converts arbitrary value to string representation using std::stringstream. template <class T> std::string toString(T const& _t) { std::ostringstream o; o << _t; return o.str(); } /// @returns the absolute path corresponding to @a _path relative to @a _reference. std::string absolutePath(std::string const& _path, std::string const& _reference); /// Helper function to return path converted strings. std::string sanitizePath(std::string const& _path); } }
2,509
C++
.h
66
36.363636
86
0.749382
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,626
Assertions.h
ethereum_solidity/libsolutil/Assertions.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 /** * @file Assertions.h * @author Christian <c@ethdev.com> * @date 2015 * * Assertion handling. */ #pragma once #include <libsolutil/Exceptions.h> #include <libsolutil/CommonData.h> #include <string> #include <utility> namespace solidity::util { #if defined(_MSC_VER) #define ETH_FUNC __FUNCSIG__ #elif defined(__GNUC__) #define ETH_FUNC __PRETTY_FUNCTION__ #else #define ETH_FUNC __func__ #endif #if defined(__GNUC__) // GCC 4.8+, Clang, Intel and other compilers compatible with GCC (-std=c++0x or above) [[noreturn]] inline __attribute__((always_inline)) void unreachable() { __builtin_unreachable(); } #elif defined(_MSC_VER) // MSVC [[noreturn]] __forceinline void unreachable() { __assume(false); } #else [[noreturn]] inline void unreachable() { solThrow(Exception, "Unreachable"); } #endif /// Base macro that can be used to implement assertion macros. /// Throws an exception containing the given description if the condition is not met. /// Allows you to provide the default description for the case where the user of your macro does /// not provide any. /// The second parameter must be an exception class (rather than an instance). #define assertThrowWithDefaultDescription(_condition, _exceptionType, _description, _defaultDescription) \ do \ { \ if (!(_condition)) \ solThrow( \ _exceptionType, \ ::solidity::util::stringOrDefault((_description), (_defaultDescription)) \ ); \ } \ while (false) /// Assertion that throws an exception containing the given description if it is not met. /// Use it as assertThrow(1 == 1, ExceptionType, "Mathematics is wrong."); /// The second parameter must be an exception class (rather than an instance). #define assertThrow(_condition, _exceptionType, _description) \ assertThrowWithDefaultDescription((_condition), _exceptionType, (_description), "Assertion failed") }
2,547
C++
.h
73
33.109589
106
0.753458
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,627
DominatorFinder.h
ethereum_solidity/libsolutil/DominatorFinder.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 /** * Dominator analysis of a control flow graph. * The implementation is based on the following paper: * https://www.cs.princeton.edu/courses/archive/spr03/cs423/download/dominators.pdf * See appendix B pg. 139. */ #pragma once #include <liblangutil/Exceptions.h> #include <libsolutil/Visitor.h> #include <range/v3/range/conversion.hpp> #include <range/v3/view/drop.hpp> #include <range/v3/view/enumerate.hpp> #include <range/v3/view/reverse.hpp> #include <range/v3/view/transform.hpp> #include <deque> #include <vector> #include <set> namespace { template <typename, typename = void> struct has_id : std::false_type {}; template <typename T> struct has_id<T, std::void_t<decltype(std::declval<T>().id)>> : std::true_type {}; } namespace solidity::util { /// DominatorFinder computes the dominator tree of a directed graph. /// V is the type of the vertex and it is assumed to have a unique identifier. /// ForEachSuccessor is a visitor that visits the successors of a vertex. /// /// The graph must contain at least one vertex (the entry point) and is assumed to not be disconnected. /// Only vertices reachable from the entry vertex are visited. template<typename V, typename ForEachSuccessor> class DominatorFinder { public: static_assert(has_id<V>::value, "vertex must define id member"); using VId = typename V::Id; using DfsIndex = size_t; DominatorFinder(V const& _entry): m_immediateDominators(findDominators(_entry)) { buildDominatorTree(); } std::vector<VId> const& verticesIdsInDFSOrder() const { return m_verticesInDFSOrder; } std::map<VId, DfsIndex> const& dfsIndexById() const { return m_dfsIndexByVertexId; } std::map<VId, std::optional<VId>> const immediateDominators() const { return m_immediateDominators | ranges::views::enumerate | ranges::views::transform([&](auto const& _v) { std::optional<VId> idomId = (_v.second.has_value()) ? std::optional<VId>(m_verticesInDFSOrder[_v.second.value()]) : std::nullopt; return std::make_pair(m_verticesInDFSOrder[_v.first], idomId); }) | ranges::to<std::map<VId, std::optional<VId>>>; } std::vector<std::optional<DfsIndex>> const& immediateDominatorsByDfsIndex() const { return m_immediateDominators; } std::map<VId, std::vector<VId>> const& dominatorTree() const { return m_dominatorTree; } bool dominates(VId const& _dominatorId, VId const& _dominatedId) const { solAssert(!m_dfsIndexByVertexId.empty()); solAssert(!m_immediateDominators.empty()); solAssert(m_dfsIndexByVertexId.count(_dominatorId) && m_dfsIndexByVertexId.count(_dominatedId)); DfsIndex dominatorIdx = m_dfsIndexByVertexId.at(_dominatorId); DfsIndex dominatedIdx = m_dfsIndexByVertexId.at(_dominatedId); if (dominatorIdx == dominatedIdx) return true; DfsIndex idomIdx = m_immediateDominators.at(dominatedIdx).value_or(0); while (idomIdx != 0) { solAssert(idomIdx < m_immediateDominators.size()); if (idomIdx == dominatorIdx) return true; // The index of the immediate dominator of a vertex is always less than the index of the vertex itself. solAssert(m_immediateDominators.at(idomIdx).has_value() && m_immediateDominators.at(idomIdx).value() < idomIdx); idomIdx = m_immediateDominators[idomIdx].value(); } // Now that we reached the entry node (i.e. idomIdx = 0), // either ``dominatorIdx == 0`` or it does not dominate the other node. solAssert(idomIdx == 0); return dominatorIdx == 0; } /// Checks whether vertex ``_dominator`` dominates ``_dominated`` by going /// through the path from ``_dominated`` to the entry node. /// If ``_dominator`` is found, then it dominates ``_dominated`` /// otherwise it doesn't. bool dominates(V const& _dominator, V const& _dominated) const { return dominates(_dominator.id, _dominated.id); } std::vector<VId> dominatorsOf(VId const& _vId) const { solAssert(!m_verticesInDFSOrder.empty()); solAssert(!m_dfsIndexByVertexId.empty()); solAssert(!m_immediateDominators.empty()); solAssert(m_dfsIndexByVertexId.count(_vId)); // No one dominates the entry vertex and we consider self-dominance implicit // i.e. every node already dominates itself. if (m_dfsIndexByVertexId.at(_vId) == 0) return {}; solAssert(m_dfsIndexByVertexId.at(_vId) < m_immediateDominators.size()); DfsIndex idomIdx = m_immediateDominators.at(m_dfsIndexByVertexId.at(_vId)).value_or(0); solAssert(idomIdx < m_immediateDominators.size()); std::vector<VId> dominators; while (idomIdx != 0) { solAssert(m_immediateDominators.at(idomIdx).has_value() && m_immediateDominators.at(idomIdx).value() < idomIdx); dominators.emplace_back(m_verticesInDFSOrder.at(idomIdx)); idomIdx = m_immediateDominators[idomIdx].value(); } // The loop above discovers the dominators in the reverse order // i.e. from the given vertex upwards to the entry node (the root of the dominator tree). // And the entry vertex always dominates all other vertices. dominators.emplace_back(m_verticesInDFSOrder[0]); return dominators; } /// Find all dominators of a node _v /// @note for a vertex ``_v``, the _v’s inclusion in the set of dominators of ``_v`` is implicit. std::vector<VId> dominatorsOf(V const& _v) const { return dominatorsOf(_v.id); } private: std::vector<std::optional<DfsIndex>> findDominators(V const& _entry) { solAssert(m_verticesInDFSOrder.empty()); solAssert(m_dfsIndexByVertexId.empty()); // parent(w): The index of the vertex which is the parent of ``w`` in the spanning // tree generated by the DFS. std::vector<DfsIndex> parent; // step 1 // The vertices are assigned indices in DFS order. std::set<VId> visited; DfsIndex nextUnusedDFSIndex = 0; auto dfs = [&](V const& _v, auto _dfs) -> void { auto [_, inserted] = visited.insert(_v.id); if (!inserted) return; m_verticesInDFSOrder.emplace_back(_v.id); m_dfsIndexByVertexId[_v.id] = nextUnusedDFSIndex; nextUnusedDFSIndex++; ForEachSuccessor{}(_v, [&](V const& _successor) { if (visited.count(_successor.id) == 0) { parent.push_back(m_dfsIndexByVertexId[_v.id]); m_predecessors.push_back({m_dfsIndexByVertexId[_v.id]}); _dfs(_successor, _dfs); } else { solAssert(m_dfsIndexByVertexId[_successor.id] < m_predecessors.size()); m_predecessors[m_dfsIndexByVertexId[_successor.id]].insert(m_dfsIndexByVertexId[_v.id]); } }); }; parent.emplace_back(std::numeric_limits<DfsIndex>::max()); m_predecessors.emplace_back(); dfs(_entry, dfs); size_t numVertices = visited.size(); solAssert(nextUnusedDFSIndex == numVertices); solAssert(m_verticesInDFSOrder.size() == numVertices); solAssert(visited.size() == numVertices); solAssert(m_predecessors.size() == numVertices); solAssert(parent.size() == numVertices); // ancestor(w): Parent of vertex ``w`` in the virtual forest traversed by eval(). // The forest consists of disjoint subtrees of the spanning tree and the parent of ``w`` is // always one of its ancestors in that spanning tree. // Initially each subtree consists of a single vertex. As the algorithm iterates over the // graph, each processed vertex gets connected to its parent from the spanning tree using // link(). Later on, the path compression performed by eval() may move it up in the subtree. std::vector<DfsIndex> ancestor(numVertices, std::numeric_limits<DfsIndex>::max()); // label(w): The index of a vertex with the smallest semidominator, on the path between ``w`` // and the root of its subtree. The value is not updated immediately by link(), but // only during path compression performed by eval(). std::vector<DfsIndex> label; // bucket(w): The set of all vertices having ``w`` as their semidominator. // The index of the array represents the vertex' DFS index. std::vector<std::deque<DfsIndex>> bucket(numVertices); // semi(w): The DFS index of the semidominator of ``w``. std::vector<DfsIndex> semi; // idom(w): The DFS index of the immediate dominator of ``w``. std::vector<std::optional<DfsIndex>> idom(numVertices, std::nullopt); // ``link(v, w)`` adds an edge from ``w`` to ``v`` in the virtual forest. // It is meant to initially attach vertex ``w`` to its parent from the spanning tree, // but path compression can later limit the search path upwards. // TODO: implement sophisticated link-eval algorithm as shown in pg 132 // See: https://www.cs.princeton.edu/courses/archive/spr03/cs423/download/dominators.pdf auto link = [&](DfsIndex _parentIdx, DfsIndex _wIdx) { solAssert(ancestor[_wIdx] == std::numeric_limits<DfsIndex>::max()); ancestor[_wIdx] = _parentIdx; }; // ``eval(v)`` returns a vertex with the smallest semidominator index on the path between // vertex ``v`` and the root of its subtree in the virtual forest, i.e. the label of ``v``. // Performs path compression in the process, updating labels and ancestors on the path to // the subtree root. auto eval = [&](DfsIndex _vIdx) -> DfsIndex { if (ancestor[_vIdx] == std::numeric_limits<DfsIndex>::max()) return _vIdx; compressPath(ancestor, label, semi, _vIdx); return label[_vIdx]; }; auto toDfsIndex = [&](VId const& _vId) { return m_dfsIndexByVertexId[_vId]; }; for (DfsIndex wIdx = 0; wIdx < m_verticesInDFSOrder.size(); ++wIdx) { semi.push_back(wIdx); label.push_back(wIdx); } // Process the vertices in decreasing order of the DFS number for (DfsIndex wIdx: m_verticesInDFSOrder | ranges::views::reverse | ranges::views::transform(toDfsIndex)) { // step 3 // NOTE: this is an optimization, i.e. performing the step 3 before step 2. // The goal is to process the bucket at the beginning of the loop for the vertex ``w`` // instead of ``parent[w]`` at the end of the loop as described in the original paper. // Inverting those steps ensures that a bucket is only processed once and // it does not need to be erased. // The optimization proposal is available here: https://jgaa.info/index.php/jgaa/article/view/paper119/2847 pg.77 for (DfsIndex vIdx: bucket[wIdx]) { DfsIndex uIdx = eval(vIdx); solAssert(uIdx <= vIdx); idom[vIdx] = (semi[uIdx] < semi[vIdx]) ? uIdx : wIdx; } // step 2 for (DfsIndex vIdx: m_predecessors[wIdx]) { DfsIndex uIdx = eval(vIdx); solAssert(uIdx <= vIdx); if (semi[uIdx] < semi[wIdx]) semi[wIdx] = semi[uIdx]; } solAssert(semi[wIdx] < wIdx || wIdx == 0); bucket[semi[wIdx]].emplace_back(wIdx); link(parent[wIdx], wIdx); solAssert(ancestor[wIdx] == parent[wIdx]); } // step 4 // Compute idom in DFS order // The entry vertex does not have an immediate dominator. solAssert(idom[0] == std::nullopt); for (DfsIndex wIdx: m_verticesInDFSOrder | ranges::views::drop(1) | ranges::views::transform(toDfsIndex)) { // All the other vertices must have an immediate dominator. solAssert(idom[wIdx].has_value()); if (idom[wIdx].value() != semi[wIdx]) idom[wIdx] = idom[idom[wIdx].value()]; } return idom; } /// Path compression updates the ancestors of vertices along /// the path to the ancestor with the minimum label value. static void compressPath( std::vector<DfsIndex>& _ancestor, std::vector<DfsIndex>& _label, std::vector<DfsIndex> const& _semi, DfsIndex _vIdx ) { solAssert(_vIdx < _ancestor.size() && _vIdx < _semi.size() && _vIdx < _label.size()); solAssert(_ancestor[_vIdx] != std::numeric_limits<size_t>::max()); solAssert(_ancestor[_vIdx] < _vIdx); if (_ancestor[_ancestor[_vIdx]] != std::numeric_limits<DfsIndex>::max()) { solAssert(_ancestor[_ancestor[_vIdx]] < _ancestor[_vIdx]); compressPath(_ancestor, _label, _semi, _ancestor[_vIdx]); if (_semi[_label[_ancestor[_vIdx]]] < _semi[_label[_vIdx]]) _label[_vIdx] = _label[_ancestor[_vIdx]]; _ancestor[_vIdx] = _ancestor[_ancestor[_vIdx]]; } solAssert(_label[_ancestor[_vIdx]] <= _label[_vIdx]); } /// Build dominator tree from the immediate dominators set. /// The function groups all the vertex IDs that are immediately dominated by a vertex. void buildDominatorTree() { // m_immediateDominators is guaranteed to have at least one element after findingDominators() is executed. solAssert(m_immediateDominators.size() > 0); solAssert(m_immediateDominators.size() == m_verticesInDFSOrder.size()); solAssert(m_immediateDominators[0] == std::nullopt); // Ignoring the entry node since no one dominates it. for (DfsIndex dominatedIdx = 1; dominatedIdx < m_verticesInDFSOrder.size(); ++dominatedIdx) { VId dominatedId = m_verticesInDFSOrder[dominatedIdx]; solAssert(m_dfsIndexByVertexId.count(dominatedId)); solAssert(dominatedIdx == m_dfsIndexByVertexId.at(dominatedId)); // If the vertex does not have an immediate dominator, it is the entry vertex (i.e. index 0). // NOTE: `dominatedIdx` will never be 0 since the loop starts from 1. solAssert(m_immediateDominators[dominatedIdx].has_value()); DfsIndex dominatorIdx = m_immediateDominators[dominatedIdx].value(); solAssert(dominatorIdx < dominatedIdx); VId dominatorId = m_verticesInDFSOrder[dominatorIdx]; m_dominatorTree[dominatorId].emplace_back(dominatedId); } } // predecessors(w): The set of vertices ``v`` such that (``v``, ``w``) is an edge of the graph. std::vector<std::set<DfsIndex>> m_predecessors; /// Keeps the list of vertex IDs in the DFS order. /// The entry vertex is the first element of the vector. /// The indices of the other vertices are assigned in the order they are visited during the DFS. /// I.e. m_verticesInDFSOrder[i] is the ID of the vertex whose DFS index is i. /// /// DFS index -> vertex ID std::vector<VId> m_verticesInDFSOrder; /// Maps a vertex ID to its DFS order index. /// /// Vertex ID -> DFS index std::map<VId, DfsIndex> m_dfsIndexByVertexId; /// Maps a vertex to all vertices that it dominates. /// If the vertex does not dominate any other vertex it has no entry in the map. /// The value is a set of IDs of vertices dominated by the vertex whose ID is the map key. /// /// Vertex id -> dominates set {vertex ID} std::map<VId, std::vector<VId>> m_dominatorTree; /// Immediate dominators by DFS index. /// Maps a vertex' DFS index (i.e. array index) to its immediate dominator DFS index. /// As the entry vertex does not have immediate dominator, its idom is always set to `std::nullopt`. /// However note that the DFS index of the entry vertex is 0, since it is the first element of the vector. /// /// E.g. to get the immediate dominator of a Vertex w: /// idomIdx = m_immediateDominators[m_dfsIndexByVertexId[w.id]] /// idomVertexId = m_verticesInDFSOrder[domIdx] /// /// DFS index -> dominates DFS index std::vector<std::optional<DfsIndex>> m_immediateDominators; }; }
15,507
C++
.h
354
40.782486
133
0.720503
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,630
StringUtils.h
ethereum_solidity/libsolutil/StringUtils.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 /** @file StringUtils.h * @author Balajiganapathi S <balajiganapathi.s@gmail.com> * @date 2017 * * String routines */ #pragma once #include <libsolutil/CommonData.h> #include <libsolutil/Numeric.h> #include <fmt/format.h> #include <algorithm> #include <limits> #include <locale> #include <string> #include <vector> namespace solidity::util { // Calculates the Damerau–Levenshtein distance between _str1 and _str2 and returns true if that distance is not greater than _maxDistance // if _lenThreshold > 0 and the product of the strings length is greater than _lenThreshold, the function will return false bool stringWithinDistance(std::string const& _str1, std::string const& _str2, size_t _maxDistance, size_t _lenThreshold = 0); // Calculates the Damerau–Levenshtein distance between _str1 and _str2 size_t stringDistance(std::string const& _str1, std::string const& _str2); // Return a string having elements of suggestions as quoted, alternative suggestions. e.g. "a", "b" or "c" std::string quotedAlternativesList(std::vector<std::string> const& suggestions); /// @returns a string containing a comma-separated list of variable names consisting of @a _baseName suffixed /// with increasing integers in the range [@a _startSuffix, @a _endSuffix), if @a _startSuffix < @a _endSuffix, /// and with decreasing integers in the range [@a _endSuffix, @a _startSuffix), if @a _endSuffix < @a _startSuffix. /// If @a _startSuffix == @a _endSuffix, the empty string is returned. std::string suffixedVariableNameList(std::string const& _baseName, size_t _startSuffix, size_t _endSuffix); /// Joins collection of strings into one string with separators between, last separator can be different. /// @param _list collection of strings to join /// @param _separator defaults to ", " /// @param _lastSeparator (optional) will be used to separate last two strings instead of _separator /// @example join(vector<string>{"a", "b", "c"}, "; ", " or ") == "a; b or c" template<class T> std::string joinHumanReadable ( T const& _list, std::string const& _separator = ", ", std::string const& _lastSeparator = "" ) { auto const itEnd = end(_list); std::string result; for (auto it = begin(_list); it != itEnd; ) { std::string element = *it; bool first = (it == begin(_list)); ++it; if (!first) { if (it == itEnd && !_lastSeparator.empty()) result += _lastSeparator; // last iteration else result += _separator; } result += std::move(element); } return result; } /// Joins collection of strings just like joinHumanReadable, but prepends the separator /// unless the collection is empty. template<class T> std::string joinHumanReadablePrefixed ( T const& _list, std::string const& _separator = ", ", std::string const& _lastSeparator = "" ) { if (begin(_list) == end(_list)) return {}; else return _separator + joinHumanReadable(_list, _separator, _lastSeparator); } /// Formats large numbers to be easily readable by humans. /// Returns decimal representation for smaller numbers; hex for large numbers. /// "Special" numbers, powers-of-two and powers-of-two minus 1, are returned in /// formulaic form like 0x01 * 2**24 - 1. /// @a T can be any integer type, will typically be u160, u256 or bigint. /// @param _value to be formatted /// @param _useTruncation if true, internal truncation is also applied, /// like 0x5555...{+56 more}...5555 /// @example formatNumberReadable((u256)0x7ffffff) = "2**27 - 1" /// @example formatNumberReadable(-57896044618658097711785492504343953926634992332820282019728792003956564819968) = -2**255 std::string formatNumberReadable(bigint const& _value, bool _useTruncation = false); /// Safely converts an unsigned integer as string into an unsigned int type. /// /// @return the converted number or nullopt in case of an failure (including if it would not fit). inline std::optional<unsigned> toUnsignedInt(std::string const& _value) { try { auto const ulong = stoul(_value); if (ulong > std::numeric_limits<unsigned>::max()) return std::nullopt; return static_cast<unsigned>(ulong); } catch (...) { return std::nullopt; } } /// Converts parameter _c to its lowercase equivalent if c is an uppercase letter and has a lowercase equivalent. It uses the classic "C" locale semantics. /// @param _c value to be converted /// @return the converted value inline char toLower(char _c) { return tolower(_c, std::locale::classic()); } /// Converts parameter _c to its uppercase equivalent if c is an lowercase letter and has a uppercase equivalent. It uses the classic "C" locale semantics. /// @param _c value to be converted /// @return the converted value inline char toUpper(char _c) { return toupper(_c, std::locale::classic()); } /// Converts parameter _s to its lowercase equivalent. It uses the classic "C" locale semantics. /// @param _s value to be converted /// @return the converted value inline std::string toLower(std::string _s) { std::transform(_s.begin(), _s.end(), _s.begin(), [](char _c) { return toLower(_c); }); return _s; } /// Checks whether _c is a decimal digit character. It uses the classic "C" locale semantics. /// @param _c character to be checked /// @return true if _c is a decimal digit character, false otherwise inline bool isDigit(char _c) { return isdigit(_c, std::locale::classic()); } /// Checks if character is printable using classic "C" locale /// @param _c character to be checked /// @return true if _c is a printable character, false otherwise. inline bool isPrint(char _c) { return isprint(_c, std::locale::classic()); } /// Adds a prefix to every line in the input. /// @see printPrefixed() std::string prefixLines( std::string const& _input, std::string const& _prefix, bool _trimPrefix = true ); /// Prints to a stream, adding a prefix to every line in the input. /// Assumes \n as the line separator. /// @param _trimPrefix If true, the function avoids introducing trailing whitespace on empty lines. /// This is achieved by removing trailing spaces from the prefix on such lines. /// Note that tabs and newlines are not removed, only spaces are. /// @param _finalNewline If true, an extra \n will be printed at the end of @a _input if it does /// not already end with one. void printPrefixed( std::ostream& _output, std::string const& _input, std::string const& _prefix, bool _trimPrefix = true, bool _ensureFinalNewline = true ); /// Adds a standard indent of 4 spaces to every line in the input. /// Assumes \n as the line separator. /// @param _indentEmptyLines If true, the indent will be applied to empty lines as well, resulting /// such lines containing trailing whitespace. inline std::string indent(std::string const& _input, bool _indentEmptyLines = false) { return prefixLines(_input, " ", !_indentEmptyLines); } }
7,501
C++
.h
185
38.859459
155
0.736206
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,632
Common.h
ethereum_solidity/libsolutil/Common.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 /** @file Common.h * @author Gav Wood <i@gavwood.com> * @date 2014 * * Very common stuff (i.e. that every other header needs except vector_ref.h). */ #pragma once // way too many unsigned to size_t warnings in 32 bit build #ifdef _M_IX86 #pragma warning(disable:4244) #endif #if _MSC_VER && _MSC_VER < 1900 #define _ALLOW_KEYWORD_MACROS #define noexcept throw() #endif #ifdef __INTEL_COMPILER #pragma warning(disable:3682) //call through incomplete class #endif #include <libsolutil/vector_ref.h> #include <boost/version.hpp> #include <cstdint> #include <functional> #include <map> #include <string> #include <utility> #include <vector> namespace solidity { // Binary data types. using bytes = std::vector<uint8_t>; using bytesRef = util::vector_ref<uint8_t>; using bytesConstRef = util::vector_ref<uint8_t const>; // Map types. using StringMap = std::map<std::string, std::string>; // String types. using strings = std::vector<std::string>; /// RAII utility class whose destructor calls a given function. class ScopeGuard { public: explicit ScopeGuard(std::function<void(void)> _f): m_f(std::move(_f)) {} ~ScopeGuard() { m_f(); } private: std::function<void(void)> m_f; }; /// RAII utility class that sets the value of a variable for the current scope and restores it to its old value /// during its destructor. template<typename V> class ScopedSaveAndRestore { public: explicit ScopedSaveAndRestore(V& _variable, V&& _value): m_variable(_variable), m_oldValue(std::move(_value)) { std::swap(m_variable, m_oldValue); } ScopedSaveAndRestore(ScopedSaveAndRestore const&) = delete; ~ScopedSaveAndRestore() { std::swap(m_variable, m_oldValue); } ScopedSaveAndRestore& operator=(ScopedSaveAndRestore const&) = delete; private: V& m_variable; V m_oldValue; }; template<typename V, typename... Args> ScopedSaveAndRestore(V, Args...) -> ScopedSaveAndRestore<V>; }
2,577
C++
.h
79
31
111
0.760694
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,635
SetOnce.h
ethereum_solidity/libsolutil/SetOnce.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/>. */ #pragma once #include <libsolutil/Assertions.h> #include <libsolutil/Exceptions.h> #include <memory> #include <optional> #include <utility> namespace solidity::util { DEV_SIMPLE_EXCEPTION(BadSetOnceReassignment); DEV_SIMPLE_EXCEPTION(BadSetOnceAccess); /// A class that stores a value that can only be set once /// \tparam T the type of the stored value template<typename T> class SetOnce { public: /// Initializes the class to have no stored value. SetOnce() = default; // Not copiable SetOnce(SetOnce const&) = delete; SetOnce(SetOnce&&) = delete; // Not movable SetOnce& operator=(SetOnce const&) = delete; SetOnce& operator=(SetOnce&&) = delete; /// @brief Sets the stored value to \p _newValue /// @throws BadSetOnceReassignment when the stored value has already been set /// @return `*this` constexpr SetOnce& operator=(T _newValue) & { assertThrow( !m_value.has_value(), BadSetOnceReassignment, "Attempt to reassign to a SetOnce that already has a value." ); m_value.emplace(std::move(_newValue)); return *this; } /// @return A reference to the stored value. The returned reference has the same lifetime as `*this`. /// @throws BadSetOnceAccess when the stored value has not yet been set T const& operator*() const { assertThrow( m_value.has_value(), BadSetOnceAccess, "Attempt to access the value of a SetOnce that does not have a value." ); return m_value.value(); } /// @return A reference to the stored value. The referent of the returned pointer has the same lifetime as `*this`. /// @throws BadSetOnceAccess when the stored value has not yet been set T const* operator->() const { return std::addressof(**this); } /// @return true if a value was assigned bool set() const { return m_value.has_value(); } private: std::optional<T> m_value = std::nullopt; }; }
2,493
C++
.h
70
33.385714
116
0.75052
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,639
LEB128.h
ethereum_solidity/libsolutil/LEB128.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 #pragma once #include <libsolutil/Common.h> namespace solidity::util { inline bytes lebEncode(uint64_t _n) { bytes encoded; while (_n > 0x7f) { encoded.emplace_back(uint8_t(0x80 | (_n & 0x7f))); _n >>= 7; } encoded.emplace_back(_n); return encoded; } // signed right shift is an arithmetic right shift static_assert((-1 >> 1) == -1, "Arithmetic shift not supported."); inline bytes lebEncodeSigned(int64_t _n) { // Based on https://github.com/llvm/llvm-project/blob/master/llvm/include/llvm/Support/LEB128.h bytes result; bool more; do { uint8_t v = _n & 0x7f; _n >>= 7; more = !((((_n == 0) && ((v & 0x40) == 0)) || ((_n == -1) && ((v & 0x40) != 0)))); if (more) v |= 0x80; // Mark this byte to show that more bytes will follow. result.emplace_back(v); } while (more); return result; } }
1,512
C++
.h
49
28.795918
96
0.712319
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,641
StackTooDeepString.h
ethereum_solidity/libsolutil/StackTooDeepString.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 #pragma once #include <string> namespace solidity::util { static std::string stackTooDeepString = "Stack too deep. " "Try compiling with `--via-ir` (cli) or the equivalent `viaIR: true` (standard JSON) " "while enabling the optimizer. Otherwise, try removing local variables."; }
974
C++
.h
23
40.347826
88
0.776956
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,643
JSON.h
ethereum_solidity/libsolutil/JSON.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 /** @file JSON.h * @date 2016 * * JSON related helpers */ #pragma once #include <libsolutil/Assertions.h> #include <nlohmann/json.hpp> #include <string> #include <string_view> #include <optional> #include <limits> namespace solidity { using Json = nlohmann::json; } // namespace solidity namespace solidity::util { /// Removes members with null value recursively from (@a _json). Json removeNullMembers(Json _json); /// JSON printing format. struct JsonFormat { enum Format { Compact, // No unnecessary whitespace (including new lines and indentation) Pretty, // Nicely indented, with new lines }; static constexpr uint32_t defaultIndent = 2; bool operator==(JsonFormat const& _other) const noexcept { return (format == _other.format) && (indent == _other.indent); } bool operator!=(JsonFormat const& _other) const noexcept { return !(*this == _other); } Format format = Compact; uint32_t indent = defaultIndent; }; /// Serialise the JSON object (@a _input) with indentation std::string jsonPrettyPrint(Json const& _input); /// Serialise the JSON object (@a _input) without indentation std::string jsonCompactPrint(Json const& _input); /// Serialise the JSON object (@a _input) using specified format (@a _format) std::string jsonPrint(Json const& _input, JsonFormat const& _format); /// Parse a JSON string (@a _input) with enabled strict-mode and writes resulting JSON object to (@a _json) /// \param _input JSON input string /// \param _json [out] resulting JSON object /// \param _errs [out] Formatted error messages /// \return \c true if the document was successfully parsed, \c false if an error occurred. bool jsonParseStrict(std::string const& _input, Json& _json, std::string* _errs = nullptr); /// Retrieves the value specified by @p _jsonPath by from a series of nested JSON dictionaries. /// @param _jsonPath A dot-separated series of dictionary keys. /// @param _node The node representing the start of the path. /// @returns The value of the last key on the path. @a nullptr if any node on the path descends /// into something that is not a dictionary or the key is not present. std::optional<Json> jsonValueByPath(Json const& _node, std::string_view _jsonPath); std::string removeNlohmannInternalErrorIdentifier(std::string const& _input); namespace detail { template<typename T> struct helper; template<typename T, bool(Json::*checkMember)() const, T(Json::*convertMember)() const> struct helper_impl { static bool isOfType(Json const& _input) { return (_input.*checkMember)(); } static T get(Json const& _input) { assertThrow(isOfType(_input), InvalidType, ""); return (_input.*convertMember)(); } static T getOrDefault(Json const& _input, std::string const& _name, T _default = {}) { T result = _default; if (_input.contains(_name) && isOfType(_input[_name])) result = (_input[_name].*convertMember)(); return result; } }; template<typename T, typename RT, bool(Json::*checkMember)() const, T(Json::*convertMember)() const> struct helper_impl_with_range_check { static bool isOfType(Json const& _input) { if ( (_input.*checkMember)()) { T value = (_input.*convertMember)(); return (value >= std::numeric_limits<RT>::min() && value <= std::numeric_limits<RT>::max()); } return false; } static RT get(Json const& _input) { assertThrow(isOfType(_input), InvalidType, ""); return static_cast<RT>((_input.*convertMember)()); } static RT getOrDefault(Json const& _input, std::string const& _name, RT _default = {}) { RT value = _default; if (_input.contains(_name) && isOfType(_input[_name])) value = static_cast<RT>((_input[_name].*convertMember)()); return value; } }; template<> struct helper<Json::string_t>: helper_impl<Json::string_t, &Json::is_string, &Json::get<Json::string_t>> {}; template<> struct helper<Json::number_integer_t>: helper_impl<Json::number_integer_t, &Json::is_number_integer, &Json::get<Json::number_integer_t>> {}; template<> struct helper<Json::number_unsigned_t>: helper_impl<Json::number_unsigned_t, &Json::is_number_integer, &Json::get<Json::number_unsigned_t>> {}; template<> struct helper<Json::number_float_t>: helper_impl<Json::number_float_t, &Json::is_number, &Json::get<Json::number_float_t>> {}; template<> struct helper<Json::boolean_t>: helper_impl<Json::boolean_t, &Json::is_boolean, &Json::get<Json::boolean_t>> {}; template<> struct helper<int32_t>: helper_impl_with_range_check<Json::number_integer_t, int32_t, &Json::is_number_integer, &Json::get<Json::number_integer_t>> {}; template<> struct helper<int16_t>: helper_impl_with_range_check<Json::number_integer_t, int16_t, &Json::is_number_integer, &Json::get<Json::number_integer_t>> {}; template<> struct helper<int8_t>: helper_impl_with_range_check<Json::number_integer_t, int8_t, &Json::is_number_integer, &Json::get<Json::number_integer_t>> {}; template<> struct helper<uint32_t>: helper_impl_with_range_check<Json::number_unsigned_t, uint32_t, &Json::is_number_integer, &Json::get<Json::number_unsigned_t>> {}; template<> struct helper<uint16_t>: helper_impl_with_range_check<Json::number_unsigned_t, uint16_t, &Json::is_number_integer, &Json::get<Json::number_unsigned_t>> {}; template<> struct helper<uint8_t>: helper_impl_with_range_check<Json::number_integer_t, uint8_t, &Json::is_number_integer, &Json::get<Json::number_integer_t>> {}; template<> struct helper<float>: helper_impl_with_range_check<Json::number_float_t, float, &Json::is_number, &Json::get<Json::number_float_t>> {}; } // namespace detail template<typename T> bool isOfType(Json const& _input) { return detail::helper<T>::isOfType(_input); } template<typename T> bool isOfTypeIfExists(Json const& _input, std::string const& _name) { if (_input.contains(_name)) return isOfType<T>(_input[_name]); return true; } template<typename T> T get(Json const& _input) { return detail::helper<T>::get(_input); } template<typename T> T getOrDefault(Json const& _input, std::string const& _name, T _default = {}) { return detail::helper<T>::getOrDefault(_input, _name, _default); } } // namespace solidity::util
6,789
C++
.h
152
42.815789
166
0.730536
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,644
CharStream.h
ethereum_solidity/liblangutil/CharStream.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/>. * * This file is derived from the file "scanner.h", 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. */ #pragma once #include <cstdint> #include <optional> #include <string> #include <tuple> #include <utility> namespace solidity::langutil { struct SourceLocation; struct LineColumn; /** * Bidirectional stream of characters. * * This CharStream is used by lexical analyzers as the source. */ class CharStream { public: CharStream() = default; CharStream(std::string _source, std::string _name): m_source(std::move(_source)), m_name(std::move(_name)) {} CharStream(std::string _source, std::string _name, bool _importedFromAST): m_source(std::move(_source)), m_name(std::move(_name)), m_importedFromAST(_importedFromAST) { } size_t position() const { return m_position; } bool isPastEndOfInput(size_t _charsForward = 0) const { return (m_position + _charsForward) >= m_source.size(); } bool isImportedFromAST() const { return m_importedFromAST; } char get(size_t _charsForward = 0) const { return m_source[m_position + _charsForward]; } char advanceAndGet(size_t _chars = 1); /// Sets scanner position to @ _amount characters backwards in source text. /// @returns The character of the current location after update is returned. char rollback(size_t _amount); /// Sets scanner position to @ _location if it refers a valid offset in m_source. /// If not, nothing is done. /// @returns The character of the current location after update is returned. char setPosition(size_t _location); void reset() { m_position = 0; } std::string const& source() const noexcept { return m_source; } std::string const& name() const noexcept { return m_name; } size_t size() const { return m_source.size(); } ///@{ ///@name Error printing helper functions /// Functions that help pretty-printing parse errors /// Do only use in error cases, they are quite expensive. std::string lineAtPosition(int _position) const; LineColumn translatePositionToLineColumn(int _position) const; ///@} /// Translates a line:column to the absolute position. std::optional<int> translateLineColumnToPosition(LineColumn const& _lineColumn) const; /// Translates a line:column to the absolute position for the given input text. static std::optional<int> translateLineColumnToPosition(std::string const& _text, LineColumn const& _input); /// Tests whether or not given octet sequence is present at the current position in stream. /// @returns true if the sequence could be found, false otherwise. bool prefixMatch(std::string_view _sequence) { if (isPastEndOfInput(_sequence.size())) return false; for (size_t i = 0; i < _sequence.size(); ++i) if (_sequence[i] != get(i)) return false; return true; } /// @returns the substring of the source that the source location references. /// Returns an empty string view if the source location does not `hasText()`. std::string_view text(SourceLocation const& _location) const; /// @returns the first line of the referenced source fragment. If the fragment is longer than /// one line, appends an ellipsis to indicate that. std::string singleLineSnippet(SourceLocation const& _location) const { return singleLineSnippet(m_source, _location); } static std::string singleLineSnippet(std::string const& _sourceCode, SourceLocation const& _location); private: std::string m_source; std::string m_name; bool m_importedFromAST{false}; size_t m_position{0}; }; }
5,769
C++
.h
130
42.253846
114
0.756675
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,645
DebugInfoSelection.h
ethereum_solidity/liblangutil/DebugInfoSelection.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 /** * Handles selections of debug info components. */ #pragma once #include <map> #include <optional> #include <ostream> #include <string> #include <string_view> #include <vector> namespace solidity::langutil { /** * Represents a set of flags corresponding to components of debug info selected for some purpose. * * Provides extra functionality for enumerating the components and serializing/deserializing the * selection to/from a comma-separated string. */ struct DebugInfoSelection { static DebugInfoSelection const All(bool _value = true) noexcept; static DebugInfoSelection const None() noexcept { return All(false); } static DebugInfoSelection const Only(bool DebugInfoSelection::* _member) noexcept; static DebugInfoSelection const Default() noexcept { return All(); } static std::optional<DebugInfoSelection> fromString(std::string_view _input); static std::optional<DebugInfoSelection> fromComponents( std::vector<std::string> const& _componentNames, bool _acceptWildcards = false ); bool enable(std::string const& _component); bool all() const noexcept; bool any() const noexcept; bool none() const noexcept { return !any(); } bool only(bool DebugInfoSelection::* _member) const noexcept { return *this == Only(_member); } DebugInfoSelection& operator&=(DebugInfoSelection const& _other); DebugInfoSelection& operator|=(DebugInfoSelection const& _other); DebugInfoSelection operator&(DebugInfoSelection _other) const noexcept; DebugInfoSelection operator|(DebugInfoSelection _other) const noexcept; bool operator!=(DebugInfoSelection const& _other) const noexcept { return !(*this == _other); } bool operator==(DebugInfoSelection const& _other) const noexcept; friend std::ostream& operator<<(std::ostream& _stream, DebugInfoSelection const& _selection); static auto const& componentMap() { static std::map<std::string, bool DebugInfoSelection::*> const components = { {"location", &DebugInfoSelection::location}, {"snippet", &DebugInfoSelection::snippet}, {"ast-id", &DebugInfoSelection::astID}, }; return components; } bool location = false; ///< Include source location. E.g. `@src 3:50:100` bool snippet = false; ///< Include source code snippet next to location. E.g. `@src 3:50:100 "contract C {..."` bool astID = false; ///< Include ID of the Solidity AST node. E.g. `@ast-id 15` }; std::ostream& operator<<(std::ostream& _stream, DebugInfoSelection const& _selection); }
3,142
C++
.h
70
42.771429
113
0.765707
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,646
CharStreamProvider.h
ethereum_solidity/liblangutil/CharStreamProvider.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 /** * Interface to retrieve the character stream by a source name. */ #pragma once #include <liblangutil/CharStream.h> #include <liblangutil/Exceptions.h> #include <string> namespace solidity::langutil { /** * Interface to retrieve a CharStream (source) from a source name. * Used especially for printing error information. */ class CharStreamProvider { public: virtual ~CharStreamProvider() = default; virtual CharStream const& charStream(std::string const& _sourceName) const = 0; }; class SingletonCharStreamProvider: public CharStreamProvider { public: explicit SingletonCharStreamProvider(CharStream const& _charStream): m_charStream(_charStream) {} CharStream const& charStream(std::string const& _sourceName) const override { solAssert(m_charStream.name() == _sourceName, ""); return m_charStream; } private: CharStream const& m_charStream; }; }
1,563
C++
.h
47
31.425532
80
0.788181
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,647
Exceptions.h
ethereum_solidity/liblangutil/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 /** * @author Christian <c@ethdev.com> * @date 2014 * Solidity exception hierarchy. */ #pragma once #include <libsolutil/Exceptions.h> #include <libsolutil/Assertions.h> #include <libsolutil/CommonData.h> #include <liblangutil/SourceLocation.h> #include <boost/preprocessor/cat.hpp> #include <boost/preprocessor/facilities/empty.hpp> #include <boost/preprocessor/facilities/overload.hpp> #include <boost/algorithm/string/case_conv.hpp> #include <optional> #include <string> #include <utility> #include <variant> #include <vector> namespace solidity::langutil { class Error; using ErrorList = std::vector<std::shared_ptr<Error const>>; struct CompilerError: virtual util::Exception {}; struct StackTooDeepError: virtual CompilerError {}; struct InternalCompilerError: virtual util::Exception {}; struct FatalError: virtual util::Exception {}; struct UnimplementedFeatureError: virtual util::Exception {}; struct InvalidAstError: virtual util::Exception {}; /// Assertion that throws an InternalCompilerError containing the given description if it is not met. #if !BOOST_PP_VARIADICS_MSVC #define solAssert(...) BOOST_PP_OVERLOAD(solAssert_,__VA_ARGS__)(__VA_ARGS__) #else #define solAssert(...) BOOST_PP_CAT(BOOST_PP_OVERLOAD(solAssert_,__VA_ARGS__)(__VA_ARGS__),BOOST_PP_EMPTY()) #endif #define solAssert_1(CONDITION) \ solAssert_2((CONDITION), "") #define solAssert_2(CONDITION, DESCRIPTION) \ assertThrowWithDefaultDescription( \ (CONDITION), \ ::solidity::langutil::InternalCompilerError, \ (DESCRIPTION), \ "Solidity assertion failed" \ ) /// Assertion that throws an UnimplementedFeatureError containing the given description if it is not met. #if !BOOST_PP_VARIADICS_MSVC #define solUnimplementedAssert(...) BOOST_PP_OVERLOAD(solUnimplementedAssert_,__VA_ARGS__)(__VA_ARGS__) #else #define solUnimplementedAssert(...) BOOST_PP_CAT(BOOST_PP_OVERLOAD(solUnimplementedAssert_,__VA_ARGS__)(__VA_ARGS__),BOOST_PP_EMPTY()) #endif #define solUnimplementedAssert_1(CONDITION) \ solUnimplementedAssert_2((CONDITION), "") #define solUnimplementedAssert_2(CONDITION, DESCRIPTION) \ assertThrowWithDefaultDescription( \ (CONDITION), \ ::solidity::langutil::UnimplementedFeatureError, \ (DESCRIPTION), \ "Unimplemented feature" \ ) /// Helper that unconditionally reports an unimplemented feature. #define solUnimplemented(DESCRIPTION) \ solUnimplementedAssert(false, DESCRIPTION) /// Assertion that throws an InvalidAstError containing the given description if it is not met. #if !BOOST_PP_VARIADICS_MSVC #define astAssert(...) BOOST_PP_OVERLOAD(astAssert_,__VA_ARGS__)(__VA_ARGS__) #else #define astAssert(...) BOOST_PP_CAT(BOOST_PP_OVERLOAD(astAssert_,__VA_ARGS__)(__VA_ARGS__),BOOST_PP_EMPTY()) #endif #define astAssert_1(CONDITION) \ astAssert_2(CONDITION, "") #define astAssert_2(CONDITION, DESCRIPTION) \ assertThrowWithDefaultDescription( \ (CONDITION), \ ::solidity::langutil::InvalidAstError, \ (DESCRIPTION), \ "AST assertion failed" \ ) using errorSourceLocationInfo = std::pair<std::string, SourceLocation>; class SecondarySourceLocation { public: SecondarySourceLocation& append(std::string const& _errMsg, SourceLocation const& _sourceLocation) { infos.emplace_back(_errMsg, _sourceLocation); return *this; } SecondarySourceLocation& append(SecondarySourceLocation&& _other) { infos += std::move(_other.infos); return *this; } /// Limits the number of secondary source locations to 32 and appends a notice to the /// error message. void limitSize(std::string& _message) { size_t occurrences = infos.size(); if (occurrences > 32) { infos.resize(32); _message += " Truncated from " + std::to_string(occurrences) + " to the first 32 occurrences."; } } std::vector<errorSourceLocationInfo> infos; }; using errinfo_sourceLocation = boost::error_info<struct tag_sourceLocation, SourceLocation>; using errinfo_secondarySourceLocation = boost::error_info<struct tag_secondarySourceLocation, SecondarySourceLocation>; /** * Unique identifiers are used to tag and track individual error cases. * They are passed as the first parameter of error reporting functions. * Suffix _error helps to find them in the sources. * The struct ErrorId prevents incidental calls like typeError(3141) instead of typeError(3141_error). * To create a new ID, one can add 0000_error and then run "python ./scripts/error_codes.py --fix" * from the root of the repo. */ struct ErrorId { unsigned long long error = 0; bool operator==(ErrorId const& _rhs) const { return error == _rhs.error; } bool operator!=(ErrorId const& _rhs) const { return !(*this == _rhs); } bool operator<(ErrorId const& _rhs) const { return error < _rhs.error; } }; constexpr ErrorId operator"" _error(unsigned long long _error) { return ErrorId{ _error }; } class Error: virtual public util::Exception { public: enum class Type { Info, Warning, CodeGenerationError, DeclarationError, DocstringParsingError, ParserError, TypeError, SyntaxError, IOError, FatalError, JSONError, InternalCompilerError, CompilerError, Exception, UnimplementedFeatureError, YulException, SMTLogicException, }; enum class Severity { // NOTE: We rely on these being ordered from least to most severe. Info, Warning, Error, }; Error( ErrorId _errorId, Type _type, std::string const& _description, SourceLocation const& _location = SourceLocation(), SecondarySourceLocation const& _secondaryLocation = SecondarySourceLocation() ); ErrorId errorId() const { return m_errorId; } Type type() const { return m_type; } Severity severity() const { return errorSeverity(m_type); } SourceLocation const* sourceLocation() const noexcept; SecondarySourceLocation const* secondarySourceLocation() const noexcept; /// helper functions static Error const* containsErrorOfType(ErrorList const& _list, Error::Type _type) { for (auto e: _list) if (e->type() == _type) return e.get(); return nullptr; } static constexpr Severity errorSeverity(Type _type) { switch (_type) { case Type::Info: return Severity::Info; case Type::Warning: return Severity::Warning; default: return Severity::Error; } } static constexpr Severity errorSeverityOrType(std::variant<Error::Type, Error::Severity> _typeOrSeverity) { if (std::holds_alternative<Error::Type>(_typeOrSeverity)) return errorSeverity(std::get<Error::Type>(_typeOrSeverity)); return std::get<Error::Severity>(_typeOrSeverity); } static bool isError(Severity _severity) { return _severity == Severity::Error; } static bool isError(Type _type) { return isError(errorSeverity(_type)); } static bool containsErrors(ErrorList const& _list) { for (auto e: _list) if (isError(e->type())) return true; return false; } static bool hasErrorsWarningsOrInfos(ErrorList const& _list) { return !_list.empty(); } static std::string formatErrorSeverity(Severity _severity) { switch (_severity) { case Severity::Info: return "Info"; case Severity::Warning: return "Warning"; case Severity::Error: return "Error"; } util::unreachable(); } static std::string formatErrorType(Type _type) { return m_errorTypeNames.at(_type); } static std::optional<Type> parseErrorType(std::string _name) { static std::map<std::string, Error::Type> const m_errorTypesByName = util::invertMap(m_errorTypeNames); if (m_errorTypesByName.count(_name) == 0) return std::nullopt; return m_errorTypesByName.at(_name); } static std::string formatTypeOrSeverity(std::variant<Error::Type, Error::Severity> _typeOrSeverity) { if (std::holds_alternative<Error::Type>(_typeOrSeverity)) return formatErrorType(std::get<Error::Type>(_typeOrSeverity)); return formatErrorSeverity(std::get<Error::Severity>(_typeOrSeverity)); } static std::string formatErrorSeverityLowercase(Severity _severity) { std::string severityValue = formatErrorSeverity(_severity); boost::algorithm::to_lower(severityValue); return severityValue; } private: ErrorId m_errorId; Type m_type; static std::map<Type, std::string> const m_errorTypeNames; }; }
8,843
C++
.h
259
31.833977
134
0.761369
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,648
SourceReferenceExtractor.h
ethereum_solidity/liblangutil/SourceReferenceExtractor.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 #pragma once #include <liblangutil/Exceptions.h> #include <iosfwd> #include <optional> #include <string> #include <tuple> #include <vector> #include <variant> namespace solidity::langutil { class CharStreamProvider; struct SourceReference { std::string message; ///< A message that relates to this source reference (such as a warning, info or an error message). std::string sourceName; ///< Underlying source name (for example the filename). LineColumn position; ///< Actual (error) position this source reference is surrounding. bool multiline = {false}; ///< Indicates whether the actual SourceReference is truncated to one line. std::string text; ///< Extracted source code text (potentially truncated if multiline or too long). int startColumn = {-1}; ///< Highlighting range-start of text field. int endColumn = {-1}; ///< Highlighting range-end of text field. /// Constructs a SourceReference containing a message only. static SourceReference MessageOnly(std::string _msg, std::string _sourceName = {}) { SourceReference sref; sref.message = std::move(_msg); sref.sourceName = std::move(_sourceName); return sref; } }; namespace SourceReferenceExtractor { struct Message { SourceReference primary; std::variant<Error::Type, Error::Severity> _typeOrSeverity; std::vector<SourceReference> secondary; std::optional<ErrorId> errorId; }; Message extract( CharStreamProvider const& _charStreamProvider, util::Exception const& _exception, std::variant<Error::Type, Error::Severity> _typeOrSeverity ); Message extract( CharStreamProvider const& _charStreamProvider, Error const& _error, std::variant<Error::Type, Error::Severity> _typeOrSeverity ); Message extract(CharStreamProvider const& _charStreamProvider, Error const& _error); SourceReference extract(CharStreamProvider const& _charStreamProvider, SourceLocation const* _location, std::string message = ""); } }
2,635
C++
.h
66
37.848485
131
0.768088
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,650
SourceReferenceFormatter.h
ethereum_solidity/liblangutil/SourceReferenceFormatter.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 /** * Formatting functions for errors referencing positions and locations in the source. */ #pragma once #include <liblangutil/Exceptions.h> #include <liblangutil/SourceReferenceExtractor.h> #include <libsolutil/AnsiColorized.h> #include <ostream> #include <sstream> #include <functional> namespace solidity::langutil { class CharStream; class CharStreamProvider; struct SourceLocation; class SourceReferenceFormatter { public: SourceReferenceFormatter( std::ostream& _stream, CharStreamProvider const& _charStreamProvider, bool _colored, bool _withErrorIds ): m_stream(_stream), m_charStreamProvider(_charStreamProvider), m_colored(_colored), m_withErrorIds(_withErrorIds) {} // WARNING: Use the xyzErrorInformation() variants over xyzExceptionInformation() when you // do have access to an Error instance. Error is implicitly convertible to util::Exception // but the conversion loses the error ID. /// Prints source location if it is given. void printSourceLocation(SourceReference const& _ref); void printExceptionInformation(SourceReferenceExtractor::Message const& _msg); void printExceptionInformation(util::Exception const& _exception, Error::Type _type); void printExceptionInformation(util::Exception const& _exception, Error::Severity _severity); void printErrorInformation(langutil::ErrorList const& _errors); void printErrorInformation(Error const& _error); static std::string formatExceptionInformation( util::Exception const& _exception, Error::Type _type, CharStreamProvider const& _charStreamProvider, bool _colored = false ) { std::ostringstream errorOutput; SourceReferenceFormatter formatter(errorOutput, _charStreamProvider, _colored, false /* _withErrorIds */); formatter.printExceptionInformation(_exception, _type); return errorOutput.str(); } static std::string formatExceptionInformation( util::Exception const& _exception, Error::Severity _severity, CharStreamProvider const& _charStreamProvider, bool _colored = false ) { std::ostringstream errorOutput; SourceReferenceFormatter formatter(errorOutput, _charStreamProvider, _colored, false /* _withErrorIds */); formatter.printExceptionInformation(_exception, _severity); return errorOutput.str(); } static std::string formatErrorInformation( Error const& _error, CharStreamProvider const& _charStreamProvider, bool _colored = false, bool _withErrorIds = false ) { std::ostringstream errorOutput; SourceReferenceFormatter formatter(errorOutput, _charStreamProvider, _colored, _withErrorIds); formatter.printErrorInformation(_error); return errorOutput.str(); } static std::string formatErrorInformation( langutil::ErrorList const& _errors, CharStreamProvider const& _charStreamProvider, bool _colored = false, bool _withErrorIds = false ) { std::ostringstream errorOutput; SourceReferenceFormatter formatter(errorOutput, _charStreamProvider, _colored, _withErrorIds); formatter.printErrorInformation(_errors); return errorOutput.str(); } static std::string formatErrorInformation(Error const& _error, CharStream const& _charStream); static void printPrimaryMessage( std::ostream& _stream, std::string _message, std::variant<Error::Type, Error::Severity> _typeOrSeverity, std::optional<ErrorId> _errorId = std::nullopt, bool _colored = false, bool _withErrorIds = false ); /// The default text color for printing error messages of a given severity in the terminal. /// Assumes a dark background color. static char const* errorTextColor(Error::Severity _severity); /// The default background color for highlighting source fragments corresponding to an error /// of a given severity in the terminal. Assumes a light text color. /// @note This is *not* meant to be used for the same text in combination with @a errorTextColor(). /// It's an alternative way to highlight it, while preserving the original text color. static char const* errorHighlightColor(Error::Severity _severity); private: util::AnsiColorized normalColored() const; util::AnsiColorized frameColored() const; util::AnsiColorized errorColored(Error::Severity _severity) const { return errorColored(m_stream, m_colored, _severity); } util::AnsiColorized messageColored() const { return messageColored(m_stream, m_colored); } util::AnsiColorized secondaryColored() const; util::AnsiColorized highlightColored() const; util::AnsiColorized diagColored() const; static util::AnsiColorized errorColored(std::ostream& _stream, bool _colored, langutil::Error::Severity _severity); static util::AnsiColorized messageColored(std::ostream& _stream, bool _colored); private: std::ostream& m_stream; CharStreamProvider const& m_charStreamProvider; bool m_colored; bool m_withErrorIds; }; }
5,476
C++
.h
135
38.214815
123
0.7918
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,651
UniqueErrorReporter.h
ethereum_solidity/liblangutil/UniqueErrorReporter.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 #pragma once #include <liblangutil/ErrorReporter.h> #include <liblangutil/Exceptions.h> namespace solidity::langutil { /* * Wrapper for ErrorReporter that removes duplicates. * Two errors are considered the same if their error ID and location are the same. */ class UniqueErrorReporter { public: UniqueErrorReporter(): m_errorReporter(m_uniqueErrors) {} void append(UniqueErrorReporter const& _other) { m_errorReporter.append(_other.m_errorReporter.errors()); } void warning(ErrorId _error, SourceLocation const& _location, std::string const& _description) { if (!seen(_error, _location, _description)) { m_errorReporter.warning(_error, _location, _description); markAsSeen(_error, _location, _description); } } void warning( ErrorId _error, SourceLocation const& _location, std::string const& _description, SecondarySourceLocation const& _secondaryLocation ) { if (!seen(_error, _location, _description)) { m_errorReporter.warning(_error, _location, _description, _secondaryLocation); markAsSeen(_error, _location, _description); } } void warning(ErrorId _error, std::string const& _description) { m_errorReporter.warning(_error, _description); } void info(ErrorId _error, SourceLocation const& _location, std::string const& _description) { if (!seen(_error, _location, _description)) { m_errorReporter.info(_error, _location, _description); markAsSeen(_error, _location, _description); } } void info(ErrorId _error, std::string const& _description) { m_errorReporter.info(_error, _description); } bool seen(ErrorId _error, SourceLocation const& _location, std::string const& _description) const { if (m_seenErrors.count({_error, _location})) { solAssert(m_seenErrors.at({_error, _location}) == _description, ""); return true; } return false; } void markAsSeen(ErrorId _error, SourceLocation const& _location, std::string const& _description) { if (_location != SourceLocation{}) m_seenErrors[{_error, _location}] = _description; } ErrorList const& errors() const { return m_errorReporter.errors(); } void clear() { m_errorReporter.clear(); } private: ErrorList m_uniqueErrors; ErrorReporter m_errorReporter; std::map<std::pair<ErrorId, SourceLocation>, std::string> m_seenErrors; }; }
2,991
C++
.h
90
30.755556
98
0.750867
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