1 | /* |
2 | * Licensed to the Apache Software Foundation (ASF) under one |
3 | * or more contributor license agreements. See the NOTICE file |
4 | * distributed with this work for additional information |
5 | * regarding copyright ownership. The ASF licenses this file |
6 | * to you under the Apache License, Version 2.0 (the |
7 | * "License"); you may not use this file except in compliance |
8 | * with the License. You may obtain a copy of the License at |
9 | * |
10 | * http://www.apache.org/licenses/LICENSE-2.0 |
11 | * |
12 | * Unless required by applicable law or agreed to in writing, |
13 | * software distributed under the License is distributed on an |
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
15 | * KIND, either express or implied. See the License for the |
16 | * specific language governing permissions and limitations |
17 | * under the License. |
18 | */ |
19 | |
20 | /*! |
21 | * \file src/relay/collage/name_supply.cc |
22 | * \brief A source of fresh variable names. |
23 | */ |
24 | |
25 | #include "./name_supply.h" |
26 | |
27 | #include <algorithm> |
28 | #include <sstream> |
29 | |
30 | namespace tvm { |
31 | namespace relay { |
32 | namespace collage { |
33 | |
34 | namespace { |
35 | void AppendCSafe(bool* first, std::ostringstream& os, const std::string& str) { |
36 | for (size_t i = 0; i < str.size(); ++i) { |
37 | const char c = str[i]; |
38 | if (i == 0 && first && (!std::isalpha(c) && c != '_')) { |
39 | os << "_" ; |
40 | } |
41 | if (c == '_' || std::isalnum(c)) { |
42 | os << c; |
43 | } else { |
44 | os << "_" ; |
45 | } |
46 | *first = false; |
47 | } |
48 | } |
49 | } // namespace |
50 | |
51 | NameSupply NameSupply::MakeSubNameSupply() { |
52 | NameSupply result(prefix_); |
53 | for (const auto& kv : next_free_index_) { |
54 | result.next_free_index_.emplace(kv.first, kv.second); |
55 | } |
56 | return result; |
57 | } |
58 | |
59 | std::string NameSupply::Fresh(const std::initializer_list<std::string>& hints) { |
60 | std::ostringstream os; |
61 | bool first = true; |
62 | bool need_sep = false; |
63 | if (!prefix_.empty()) { |
64 | AppendCSafe(&first, os, prefix_); |
65 | need_sep = true; |
66 | } |
67 | for (const auto& hint : hints) { |
68 | if (hint.empty()) { |
69 | continue; |
70 | } |
71 | if (need_sep) { |
72 | os << "_" ; |
73 | } |
74 | AppendCSafe(&first, os, hint); |
75 | need_sep = true; |
76 | } |
77 | std::string name = os.str(); |
78 | auto itr = next_free_index_.find(name); |
79 | if (itr == next_free_index_.end()) { |
80 | next_free_index_.emplace(name, 1); |
81 | } else { |
82 | os << "_" << itr->second++; |
83 | name = os.str(); |
84 | } |
85 | return name; |
86 | } |
87 | |
88 | } // namespace collage |
89 | } // namespace relay |
90 | } // namespace tvm |
91 | |