forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Dimname.cpp
77 lines (67 loc) · 1.96 KB
/
Dimname.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include <ATen/core/Dimname.h>
#include <c10/util/Exception.h>
#include <cctype>
namespace at {
static Symbol kWildcard = Symbol::dimname("*");
std::ostream& operator<<(std::ostream& out, const Dimname& dimname) {
if (dimname.type() == NameType::WILDCARD) {
out << "None";
} else {
out << "'" << dimname.symbol().toUnqualString() << "'";
}
return out;
}
bool Dimname::isValidName(const std::string& name) {
// allow valid ASCII python identifiers: "uppercase and lowercase
// letters A through Z, the underscore _ and, except for the first
// character, the digits 0 through 9" (at least length 1)
// https://docs.python.org/3/reference/lexical_analysis.html#identifiers
if (name.empty()) {
return false;
}
for (auto it = name.begin(); it != name.end(); ++it) {
// NOLINTNEXTLINE(bugprone-branch-clone)
if (std::isalpha(*it) || *it == '_') {
continue;
} else if (it != name.begin() && std::isdigit(*it)) {
continue;
}
return false;
}
return true;
}
static void check_valid_identifier(const std::string& name) {
TORCH_CHECK(
Dimname::isValidName(name),
"Invalid name: a valid identifier contains only digits, alphabetical "
"characters, and/or underscore and starts with a non-digit. got: '",
name, "'.");
}
Dimname Dimname::fromSymbol(Symbol name) {
TORCH_INTERNAL_ASSERT(name.is_dimname());
if (name == kWildcard) {
return Dimname::wildcard();
}
check_valid_identifier(name.toUnqualString());
return Dimname(name);
}
Dimname Dimname::wildcard() {
static Dimname result(kWildcard, NameType::WILDCARD);
return result;
}
std::optional<Dimname> Dimname::unify(Dimname other) const {
if (other.type() == NameType::WILDCARD) {
return *this;
}
if (type_ == NameType::WILDCARD) {
return other;
}
if (name_ == other.symbol()) {
return *this;
}
return std::nullopt;
}
bool Dimname::matches(Dimname other) const {
return unify(other).has_value();
}
} // namespace at