Bug 1882714 [wpt PR 44850] - Update wpt metadata, a=testonly
[gecko.git] / third_party / wasm2c / src / token.cc
blob576fadd185295207a7e21275f7818f752ac62c0b
1 /*
2 * Copyright 2017 WebAssembly Community Group participants
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #include "wabt/token.h"
19 namespace wabt {
21 const char* GetTokenTypeName(TokenType token_type) {
22 static const char* s_names[] = {
23 #define WABT_TOKEN(name, string) string,
24 #define WABT_TOKEN_FIRST(name, string)
25 #define WABT_TOKEN_LAST(name, string)
26 #include "wabt/token.def"
27 #undef WABT_TOKEN
28 #undef WABT_TOKEN_FIRST
29 #undef WABT_TOKEN_LAST
32 static_assert(
33 WABT_ARRAY_SIZE(s_names) == WABT_ENUM_COUNT(TokenType),
34 "Expected TokenType names list length to match number of TokenTypes.");
36 int x = static_cast<int>(token_type);
37 if (x < WABT_ENUM_COUNT(TokenType)) {
38 return s_names[x];
41 return "Invalid";
44 Token::Token(Location loc, TokenType token_type)
45 : loc(loc), token_type_(token_type) {
46 assert(IsTokenTypeBare(token_type_));
49 Token::Token(Location loc, TokenType token_type, Type type)
50 : loc(loc), token_type_(token_type) {
51 assert(HasType());
52 Construct(type_, type);
55 Token::Token(Location loc, TokenType token_type, std::string_view text)
56 : loc(loc), token_type_(token_type) {
57 assert(HasText());
58 Construct(text_, text);
61 Token::Token(Location loc, TokenType token_type, Opcode opcode)
62 : loc(loc), token_type_(token_type) {
63 assert(HasOpcode());
64 Construct(opcode_, opcode);
67 Token::Token(Location loc, TokenType token_type, const Literal& literal)
68 : loc(loc), token_type_(token_type) {
69 assert(HasLiteral());
70 Construct(literal_, literal);
73 std::string Token::to_string() const {
74 if (IsTokenTypeBare(token_type_)) {
75 return GetTokenTypeName(token_type_);
76 } else if (HasLiteral()) {
77 return std::string(literal_.text);
78 } else if (HasOpcode()) {
79 return opcode_.GetName();
80 } else if (HasText()) {
81 return std::string(text_);
82 } else if (IsTokenTypeRefKind(token_type_)) {
83 return type_.GetRefKindName();
84 } else {
85 assert(HasType());
86 return type_.GetName();
90 std::string Token::to_string_clamp(size_t max_length) const {
91 std::string s = to_string();
92 if (s.length() > max_length) {
93 return s.substr(0, max_length - 3) + "...";
94 } else {
95 return s;
99 } // namespace wabt