From 47c33d19a9a6112cd28b52d0350ad5830d4476ea Mon Sep 17 00:00:00 2001 From: Yingchi Long Date: Wed, 24 Jan 2024 00:00:28 +0800 Subject: [PATCH] libnixf: parse variable --- libnixf/include/nixf/Parse/Nodes.h | 10 ++++++++++ libnixf/src/Parse/Parser.cpp | 7 +++++++ libnixf/test/Parse/Parser.cpp | 14 ++++++++++++++ 3 files changed, 31 insertions(+) diff --git a/libnixf/include/nixf/Parse/Nodes.h b/libnixf/include/nixf/Parse/Nodes.h index f9eab5814..f060a048e 100644 --- a/libnixf/include/nixf/Parse/Nodes.h +++ b/libnixf/include/nixf/Parse/Nodes.h @@ -35,6 +35,7 @@ class Node { NK_BeginExpr, NK_ExprInt, NK_ExprFloat, + NK_ExprVar, NK_ExprString, NK_ExprPath, NK_ExprParen, @@ -188,6 +189,15 @@ class Identifier : public Node { [[nodiscard]] const std::string &name() const { return Name; } }; +class ExprVar : public Expr { + std::shared_ptr ID; + +public: + ExprVar(RangeTy Range, std::shared_ptr ID) + : Expr(NK_ExprVar, Range), ID(std::move(ID)) {} + [[nodiscard]] const std::shared_ptr &id() const { return ID; } +}; + class AttrName : public Node { public: enum AttrNameKind { ANK_ID, ANK_String, ANK_Interpolation }; diff --git a/libnixf/src/Parse/Parser.cpp b/libnixf/src/Parse/Parser.cpp index b767b404b..acb25d1cb 100644 --- a/libnixf/src/Parse/Parser.cpp +++ b/libnixf/src/Parse/Parser.cpp @@ -468,6 +468,7 @@ class Parser { } /// expr_simple : INT + /// | ID /// | FLOAT /// | string /// | indented_string @@ -481,6 +482,12 @@ class Parser { std::shared_ptr parseExprSimple() { Token Tok = peek(); switch (Tok.kind()) { + case tok_id: { + consume(); + auto ID = + std::make_shared(Tok.range(), std::string(Tok.view())); + return std::make_shared(Tok.range(), std::move(ID)); + } case tok_int: { consume(); NixInt N; diff --git a/libnixf/test/Parse/Parser.cpp b/libnixf/test/Parse/Parser.cpp index d0dbf7882..4a714a148 100644 --- a/libnixf/test/Parse/Parser.cpp +++ b/libnixf/test/Parse/Parser.cpp @@ -546,4 +546,18 @@ TEST(Parser, AttrsExtraDot) { ASSERT_EQ(F2.newText(), "\"dummy\""); } +TEST(Parser, ExprVar) { + auto Src = R"(a)"sv; + + std::vector Diags; + auto AST = nixf::parse(Src, Diags); + + ASSERT_TRUE(AST); + ASSERT_EQ(AST->kind(), Node::NK_ExprVar); + ASSERT_TRUE(AST->range().begin().isAt(0, 0, 0)); + ASSERT_TRUE(AST->range().end().isAt(0, 1, 1)); + + ASSERT_EQ(Diags.size(), 0); +} + } // namespace