Add reader::spv::Namer::FindUnusedDerivedName

Bug: tint:3
Change-Id: I0a0e5646d7bcdc89fdaaf8b956dd61ed6148c7e9
Reviewed-on: https://dawn-review.googlesource.com/c/tint/+/17421
Reviewed-by: dan sinclair <dsinclair@google.com>
This commit is contained in:
David Neto 2020-03-23 16:43:41 +00:00 committed by dan sinclair
parent bd1d142134
commit 8af12f7503
3 changed files with 46 additions and 0 deletions

View File

@ -15,6 +15,7 @@
#include "src/reader/spirv/namer.h"
#include <algorithm>
#include <sstream>
namespace tint {
namespace reader {
@ -48,12 +49,30 @@ std::string Namer::Sanitize(const std::string& suggested_name) {
return result;
}
std::string Namer::FindUnusedDerivedName(const std::string& base_name) const {
// Ensure uniqueness among names.
std::string derived_name;
for (int i = 0;; i++) {
std::stringstream new_name_stream;
new_name_stream << base_name;
if (i > 0) {
new_name_stream << "_" << i;
}
derived_name = new_name_stream.str();
if (name_to_id_.count(derived_name) == 0) {
break;
}
}
return derived_name;
}
bool Namer::SaveName(uint32_t id, const std::string& name) {
if (HasName(id)) {
return Fail() << "internal error: ID " << id
<< " already has registered name: " << id_to_name_[id];
}
id_to_name_[id] = name;
name_to_id_[name] = id;
return true;
}

View File

@ -63,6 +63,11 @@ class Namer {
return id_to_name_.find(id)->second;
}
/// Returns an unregistered name based on a given base name.
/// @param base_name the base name
/// @returns a new name
std::string FindUnusedDerivedName(const std::string& base_name) const;
/// Records a mapping from the given ID to a name. Emits a failure
/// if the ID already has a registered name.
/// @param id the SPIR-V ID
@ -75,6 +80,8 @@ class Namer {
// Maps an ID to its registered name.
std::unordered_map<uint32_t, std::string> id_to_name_;
// Maps a name to a SPIR-V ID, or 0 (the case for derived names).
std::unordered_map<std::string, uint32_t> name_to_id_;
};
} // namespace spirv

View File

@ -83,6 +83,26 @@ TEST_F(SpvNamerTest, NoNameRecorded) {
EXPECT_TRUE(error().empty());
}
TEST_F(SpvNamerTest, FindUnusedDerivedName_NoRecordedName) {
Namer namer(fail_stream_);
EXPECT_THAT(namer.FindUnusedDerivedName("eleanor"), Eq("eleanor"));
}
TEST_F(SpvNamerTest, FindUnusedDerivedName_HasRecordedName) {
Namer namer(fail_stream_);
namer.SaveName(12, "rigby");
EXPECT_THAT(namer.FindUnusedDerivedName("rigby"), Eq("rigby_1"));
}
TEST_F(SpvNamerTest, FindUnusedDerivedName_HasMultipleConflicts) {
Namer namer(fail_stream_);
namer.SaveName(12, "rigby");
namer.SaveName(13, "rigby_1");
namer.SaveName(14, "rigby_3");
// It picks the first non-conflicting suffix.
EXPECT_THAT(namer.FindUnusedDerivedName("rigby"), Eq("rigby_2"));
}
TEST_F(SpvNamerTest, SaveNameOnce) {
Namer namer(fail_stream_);