Add Tree::TryAs to cast to a typed parse node id (#3565)

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
This commit is contained in:
josh11b
2024-01-04 21:51:19 +00:00
committed by GitHub
co-authored by Richard Smith
parent facf6eea04
commit 82179bc903
2 changed files with 84 additions and 0 deletions
+41
View File
@@ -56,6 +56,47 @@ TEST_F(TreeTest, IsValid) {
EXPECT_TRUE((*tree.postorder().begin()).is_valid());
}
TEST_F(TreeTest, AsAndTryAs) {
Lex::TokenizedBuffer& tokens = GetTokenizedBuffer("fn F();");
Tree tree = Parse(tokens, consumer_, /*vlog_stream=*/nullptr);
ASSERT_FALSE(tree.has_errors());
auto it = tree.roots().begin();
// A FileEnd node, so won't match.
NodeId n = *it;
// NodeIdForKind
std::optional<FunctionDeclId> fn_decl_id = tree.TryAs<FunctionDeclId>(n);
EXPECT_FALSE(fn_decl_id.has_value());
// NodeIdOneOf
std::optional<AnyFunctionDeclId> any_fn_decl_id =
tree.TryAs<AnyFunctionDeclId>(n);
EXPECT_FALSE(any_fn_decl_id.has_value());
// NodeIdInCategory
std::optional<AnyDeclId> any_decl_id = tree.TryAs<AnyDeclId>(n);
EXPECT_FALSE(any_decl_id.has_value());
++it;
n = *it;
// A FunctionDecl node, so will match.
fn_decl_id = tree.TryAs<FunctionDeclId>(n);
ASSERT_TRUE(fn_decl_id.has_value());
EXPECT_TRUE(*fn_decl_id == n);
FunctionDeclId fn_decl_id2 = tree.As<FunctionDeclId>(n);
EXPECT_TRUE(*fn_decl_id == fn_decl_id2);
any_fn_decl_id = tree.TryAs<AnyFunctionDeclId>(n);
ASSERT_TRUE(any_fn_decl_id.has_value());
EXPECT_TRUE(*any_fn_decl_id == n);
AnyFunctionDeclId any_fn_decl_id2 = tree.As<AnyFunctionDeclId>(n);
EXPECT_TRUE(*any_fn_decl_id == any_fn_decl_id2);
any_decl_id = tree.TryAs<AnyDeclId>(n);
ASSERT_TRUE(any_decl_id.has_value());
EXPECT_TRUE(*any_decl_id == n);
AnyDeclId any_decl_id2 = tree.As<AnyDeclId>(n);
EXPECT_TRUE(*any_decl_id == any_decl_id2);
}
TEST_F(TreeTest, PrintPostorderAsYAML) {
Lex::TokenizedBuffer& tokens = GetTokenizedBuffer("fn F();");
Tree tree = Parse(tokens, consumer_, /*vlog_stream=*/nullptr);