Merge pull request #11912 from ethereum/refactorSourcePrinting

Refactor source printing
This commit is contained in:
chriseth 2021-09-08 14:07:07 +02:00 committed by GitHub
commit 55bb53c9de
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 27 additions and 10 deletions

View File

@ -31,6 +31,7 @@
#include <libevmasm/ConstantOptimiser.h>
#include <libevmasm/GasMeter.h>
#include <liblangutil/CharStream.h>
#include <liblangutil/Exceptions.h>
#include <json/json.h>
@ -82,16 +83,7 @@ string locationFromSources(StringMap const& _sourceCodes, SourceLocation const&
if (it == _sourceCodes.end())
return {};
string const& source = it->second;
if (static_cast<size_t>(_location.start) >= source.size())
return {};
string cut = source.substr(static_cast<size_t>(_location.start), static_cast<size_t>(_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

View File

@ -128,3 +128,19 @@ string_view CharStream::text(SourceLocation const& _location) const
static_cast<size_t>(_location.end - _location.start)
);
}
string CharStream::singleLineSnippet(string const& _sourceCode, SourceLocation const& _location)
{
if (!_location.hasText())
return {};
if (static_cast<size_t>(_location.start) >= _sourceCode.size())
return {};
string cut = _sourceCode.substr(static_cast<size_t>(_location.start), static_cast<size_t>(_location.end - _location.start));
auto newLinePos = cut.find_first_of("\n\r");
if (newLinePos != string::npos)
cut = cut.substr(0, newLinePos) + "...";
return cut;
}

View File

@ -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;