• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2021 The Tint Authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "fuzzers/tint_ast_fuzzer/node_id_map.h"
16 
17 #include <cassert>
18 
19 namespace tint {
20 namespace fuzzers {
21 namespace ast_fuzzer {
22 
23 NodeIdMap::NodeIdMap() = default;
24 
NodeIdMap(const Program & program)25 NodeIdMap::NodeIdMap(const Program& program) : NodeIdMap() {
26   for (const auto* node : program.ASTNodes().Objects()) {
27     Add(node, TakeFreshId());
28   }
29 }
30 
GetId(const ast::Node * node) const31 NodeIdMap::IdType NodeIdMap::GetId(const ast::Node* node) const {
32   auto it = node_to_id_.find(node);
33   return it == node_to_id_.end() ? 0 : it->second;
34 }
35 
GetNode(IdType id) const36 const ast::Node* NodeIdMap::GetNode(IdType id) const {
37   auto it = id_to_node_.find(id);
38   return it == id_to_node_.end() ? nullptr : it->second;
39 }
40 
Add(const ast::Node * node,IdType id)41 void NodeIdMap::Add(const ast::Node* node, IdType id) {
42   assert(!node_to_id_.count(node) && "The node already exists in the map");
43   assert(IdIsFreshAndValid(id) && "Id already exists in the map or Id is zero");
44   assert(node && "`node` can't be a nullptr");
45 
46   node_to_id_[node] = id;
47   id_to_node_[id] = node;
48 
49   if (id >= fresh_id_) {
50     fresh_id_ = id + 1;
51   }
52 }
53 
IdIsFreshAndValid(IdType id)54 bool NodeIdMap::IdIsFreshAndValid(IdType id) {
55   return id && !id_to_node_.count(id);
56 }
57 
TakeFreshId()58 NodeIdMap::IdType NodeIdMap::TakeFreshId() {
59   assert(fresh_id_ != 0 && "`NodeIdMap` id has overflowed");
60   return fresh_id_++;
61 }
62 
63 }  // namespace ast_fuzzer
64 }  // namespace fuzzers
65 }  // namespace tint
66