Skip to content

feat(tdl): Add StructSpec AST node. - #190

Merged
LinZhihao-723 merged 4 commits into
y-scope:mainfrom
LinZhihao-723:struct-spec
Aug 13, 2025
Merged

feat(tdl): Add StructSpec AST node.#190
LinZhihao-723 merged 4 commits into
y-scope:mainfrom
LinZhihao-723:struct-spec

Conversation

@LinZhihao-723

@LinZhihao-723 LinZhihao-723 commented Aug 11, 2025

Copy link
Copy Markdown
Member

Description

This PR introduces StructSpec AST node, which represents the specification of a struct defined in TDL. A struct should have an ID (Identifier) and a list of fields (NamedVar), where the fields should be uniquely identified by the name.

Notice that despite StructSpec is implemented as an AST node, it is not a Type object. The actual struct type should have a reference to such a StructSpec object, as the specification might be shared by multiple uses of a struct type. Thus, the factory function of StructSpec returns a shared pointer for reference sharing, instead of a unique pointer.

Checklist

  • The PR satisfies the contribution guidelines.
  • This is a breaking change and that has been indicated in the PR title, OR this isn't a
    breaking change.
  • Necessary docs have been updated, OR no docs need to be updated.

Validation performed

  • Ensure all workflows pass.
  • Add unit tests to cover the basic behavior of StructSpec.

Summary by CodeRabbit

  • New Features

    • Added support for struct specifications in the TDL AST with creation, validation and readable serialization.
    • Public API exposes a new StructSpec node and clear error codes for duplicate fields and empty structs.
  • Tests

    • Added tests covering creation, name/field handling, serialization and error scenarios (duplicates, empty).
  • Chores

    • Build configuration updated to include the new node and to add an additional public dependency.
    • Minor compilation fix to enable template constraints.

@LinZhihao-723
LinZhihao-723 requested review from a team and sitaowang1998 as code owners August 11, 2025 02:13
@coderabbitai

coderabbitai Bot commented Aug 11, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

Adds a new StructSpec AST node (header + source) to the TDL parser, wires it into spider_tdl's CMake exports and public linkage, updates Node.hpp include, and adds unit tests validating creation, duplicate/empty errors, and serialization.

Changes

Cohort / File(s) Summary of changes
Build integration
src/spider/CMakeLists.txt
Adds .../StructSpec.hpp to SPIDER_TDL_SHARED_HEADERS and .../StructSpec.cpp to SPIDER_TDL_SHARED_SOURCES; adds absl::flat_hash_set to spider_tdl PUBLIC link libraries.
AST node: StructSpec
src/spider/tdl/parser/ast/node_impl/StructSpec.hpp, src/spider/tdl/parser/ast/node_impl/StructSpec.cpp
New StructSpec class with factory create(std::unique_ptr<Node>, std::vector<std::unique_ptr<Node>>) returning error codes DuplicatedFieldName/EmptyStruct; serialize_to_str method; field visitation template; accessors get_name, get_num_fields; error-category specialization and validation of Identifier/NamedVar children.
Node header fix
src/spider/tdl/parser/ast/Node.hpp
Added #include <type_traits> to support std::is_invocable_r_v used in visit template constraints.
Tests
tests/tdl/test-parser-ast.cpp
Adds tests for StructSpec: successful creation/serialization, duplicate-field error, and empty-struct error; includes new header and uses NamedVar/Identifier test fixtures.

Sequence Diagram(s)

sequenceDiagram
    participant Test as Client/Test
    participant StructSpec
    participant NodeValidation as Validator
    participant NamedVar
    participant Identifier

    Test->>StructSpec: create(name: Node, fields: vector<Node>)
    StructSpec->>Identifier: validate name is Identifier
    StructSpec->>NamedVar: validate each field is NamedVar
    StructSpec->>NodeValidation: check duplicate names / empty list
    alt invalid
        StructSpec-->>Test: Error (DuplicatedFieldName | EmptyStruct | type error)
    else valid
        StructSpec-->>Test: shared_ptr<StructSpec>
    end

    Test->>StructSpec: serialize_to_str(indent)
    StructSpec->>NamedVar: visit_fields(serialize each field)
    StructSpec-->>Test: formatted string
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested reviewers

  • sitaowang1998

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between dcfb364 and 4abdda7.

📒 Files selected for processing (4)
  • src/spider/CMakeLists.txt (3 hunks)
  • src/spider/tdl/parser/ast/Node.hpp (1 hunks)
  • src/spider/tdl/parser/ast/node_impl/StructSpec.cpp (1 hunks)
  • src/spider/tdl/parser/ast/node_impl/StructSpec.hpp (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/spider/tdl/parser/ast/node_impl/StructSpec.cpp
  • src/spider/CMakeLists.txt
  • src/spider/tdl/parser/ast/node_impl/StructSpec.hpp
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-08-07T14:54:20.267Z
Learnt from: LinZhihao-723
PR: y-scope/spider#182
File: src/spider/tdl/parser/ast/Node.hpp:0-0
Timestamp: 2025-08-07T14:54:20.267Z
Learning: In the spider TDL AST Node class, derived classes should use the `add_child` method in their factory functions rather than passing children directly to a constructor, to ensure proper parent-child relationship management and error handling.

Applied to files:

  • src/spider/tdl/parser/ast/Node.hpp
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: lint
  • GitHub Check: non-storage-unit-tests (ubuntu-22.04)
  • GitHub Check: non-storage-unit-tests (ubuntu-24.04)
🔇 Additional comments (1)
src/spider/tdl/parser/ast/Node.hpp (1)

8-8: Unblocks the C++20 requires-constraint usage — LGTM

Including <type_traits> is necessary for std::is_invocable_r_v used in visit_children (and supports the new StructSpec visitors). Purely a compile-time fix with no runtime effect.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (4)
tests/tdl/test-parser-ast.cpp (1)

262-274: Strengthen assertions for StructSpec in “Basic” section

Add checks for get_num_fields() and exercise visit_fields to validate iteration order. This improves coverage of the new API.

             REQUIRE(nullptr != struct_spec_node);

-            REQUIRE(struct_spec_node->get_num_children() == 4);
+            REQUIRE(struct_spec_node->get_num_children() == 4);
+            REQUIRE(struct_spec_node->get_num_fields() == 3);
+            // Optionally, verify visit_fields iterates all fields in order.
+            size_t seen = 0;
+            auto visit_result = struct_spec_node->visit_fields([&](NamedVar const& nv)
+                    -> Result<void> {
+                // Sanity check that field Id exists; order is implied by visit order.
+                REQUIRE(nv.get_id() != nullptr);
+                ++seen;
+                return ystdlib::error_handling::success();
+            });
+            REQUIRE_FALSE(visit_result.has_error());
+            REQUIRE(seen == 3);
src/spider/tdl/parser/ast/node_impl/StructSpec.cpp (2)

52-61: Reserve capacity for duplicate-check set

A small perf win: reserve to avoid rehashing when there are many fields.

-    std::unordered_set<std::string_view> field_names;
+    std::unordered_set<std::string_view> field_names;
+    field_names.reserve(fields.size());

71-96: Reserve serialisation buffer and minor micro-optimisation

Pre-sizing the vector avoids reallocations, especially for larger structs. No behaviour change.

-    std::vector<std::string> serialized_fields;
+    std::vector<std::string> serialized_fields;
+    serialized_fields.reserve(get_num_fields());
src/spider/tdl/parser/ast/node_impl/StructSpec.hpp (1)

58-59: Optional: mark simple accessors noexcept

get_num_fields() and get_name() are non-throwing given factory invariants. Marking them noexcept can help callers and tooling.

-    [[nodiscard]] auto get_name() const -> std::string_view {
+    [[nodiscard]] auto get_name() const noexcept -> std::string_view {
...
-    [[nodiscard]] auto get_num_fields() const -> size_t { return get_num_children() - 1; }
+    [[nodiscard]] auto get_num_fields() const noexcept -> size_t { return get_num_children() - 1; }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a373dfd and 45cc1e8.

📒 Files selected for processing (4)
  • src/spider/CMakeLists.txt (2 hunks)
  • src/spider/tdl/parser/ast/node_impl/StructSpec.cpp (1 hunks)
  • src/spider/tdl/parser/ast/node_impl/StructSpec.hpp (1 hunks)
  • tests/tdl/test-parser-ast.cpp (4 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
src/spider/tdl/parser/ast/node_impl/StructSpec.hpp (1)
src/spider/tdl/parser/ast/node_impl/StructSpec.cpp (2)
  • name (26-28)
  • name (26-26)
src/spider/tdl/parser/ast/node_impl/StructSpec.cpp (2)
src/spider/tdl/parser/ast/node_impl/StructSpec.hpp (4)
  • StructSpec (87-87)
  • name (44-45)
  • indentation_level (48-49)
  • visit_fields (72-73)
src/spider/tdl/parser/ast/Node.hpp (1)
  • child (103-104)
tests/tdl/test-parser-ast.cpp (4)
src/spider/tdl/parser/ast/node_impl/StructSpec.hpp (1)
  • StructSpec (87-87)
src/spider/tdl/parser/ast/node_impl/StructSpec.cpp (2)
  • create (44-69)
  • create (44-45)
src/spider/tdl/parser/ast/node_impl/NamedVar.cpp (2)
  • create (17-26)
  • create (17-18)
src/spider/tdl/parser/ast/node_impl/type_impl/container_impl/Map.cpp (2)
  • create (69-84)
  • create (69-70)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: non-storage-unit-tests (ubuntu-24.04)
  • GitHub Check: non-storage-unit-tests (ubuntu-22.04)
  • GitHub Check: lint
🔇 Additional comments (5)
src/spider/CMakeLists.txt (1)

202-203: Wiring StructSpec into spider_tdl looks correct

StructSpec.cpp/StructSpec.hpp are properly added alongside Identifier/NamedVar. Public visibility via target_sources(spider_tdl PUBLIC …) is consistent. No build-system concerns.

Also applies to: 219-219

tests/tdl/test-parser-ast.cpp (2)

306-322: Duplicate-field-name error-path test looks solid

Asserts the intended DuplicatedFieldName error. The SECTION note about moved fields is correct for Catch2’s branching model.


324-331: Empty-struct error-path test is appropriate

Correctly validates EmptyStruct. Nice coverage for both major error cases.

src/spider/tdl/parser/ast/node_impl/StructSpec.cpp (1)

43-69: Use of string_view for duplicate detection is safe here

You collect names before moving fields into the StructSpec, so the string_views remain valid during the check. The approach is sound.

src/spider/tdl/parser/ast/node_impl/StructSpec.hpp (1)

67-83: visit_fields API is clean and consistent

Constraint on FieldVisitor and error propagation via Result align with existing patterns. Implementation looks correct.

Comment thread src/spider/tdl/parser/ast/node_impl/StructSpec.hpp
Comment thread src/spider/tdl/parser/ast/node_impl/StructSpec.cpp Outdated
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants