From a7612ce8736b57ca3469e272ecc74eb016ca9462 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kamil=20=C5=9Aliwak?= Date: Mon, 30 Aug 2021 20:06:39 +0200 Subject: [PATCH] Move the function for creating code snippets used next to source locations in assembly to liblangutil --- libevmasm/Assembly.cpp | 12 ++---------- liblangutil/CharStream.cpp | 16 ++++++++++++++++ liblangutil/CharStream.h | 9 +++++++++ 3 files changed, 27 insertions(+), 10 deletions(-) diff --git a/libevmasm/Assembly.cpp b/libevmasm/Assembly.cpp index dad9635d7..c1e171221 100644 --- a/libevmasm/Assembly.cpp +++ b/libevmasm/Assembly.cpp @@ -31,6 +31,7 @@ #include #include +#include #include #include @@ -82,16 +83,7 @@ string locationFromSources(StringMap const& _sourceCodes, SourceLocation const& if (it == _sourceCodes.end()) return {}; - string const& source = it->second; - if (static_cast(_location.start) >= source.size()) - return {}; - - string cut = source.substr(static_cast(_location.start), static_cast(_location.end - _location.start)); - auto newLinePos = cut.find_first_of("\n"); - if (newLinePos != string::npos) - cut = cut.substr(0, newLinePos) + "..."; - - return cut; + return CharStream::singleLineSnippet(it->second, _location); } class Functionalizer diff --git a/liblangutil/CharStream.cpp b/liblangutil/CharStream.cpp index 8ab99fca8..748a4a99c 100644 --- a/liblangutil/CharStream.cpp +++ b/liblangutil/CharStream.cpp @@ -128,3 +128,19 @@ string_view CharStream::text(SourceLocation const& _location) const static_cast(_location.end - _location.start) ); } + +string CharStream::singleLineSnippet(string const& _sourceCode, SourceLocation const& _location) +{ + if (!_location.hasText()) + return {}; + + if (static_cast(_location.start) >= _sourceCode.size()) + return {}; + + string cut = _sourceCode.substr(static_cast(_location.start), static_cast(_location.end - _location.start)); + auto newLinePos = cut.find_first_of("\n"); + if (newLinePos != string::npos) + cut = cut.substr(0, newLinePos) + "..."; + + return cut; +} diff --git a/liblangutil/CharStream.h b/liblangutil/CharStream.h index 4b729771f..761cece31 100644 --- a/liblangutil/CharStream.h +++ b/liblangutil/CharStream.h @@ -118,6 +118,15 @@ public: /// 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;