Skip to content

Add enum parameter type - #446

Merged
christophfroehlich merged 2 commits into
ros-tooling:mainfrom
jjohnnystwsss:feat/392-enum-type
Nov 25, 2026
Merged

christophfroehlich merged 2 commits into
ros-tooling:mainfrom
jjohnnystwsss:feat/392-enum-type

Conversation

@jjohnnystwsss

Copy link
Copy Markdown
Contributor

Closes #392. Implements the design from #392 (comment).

control_mode:
  type: enum
  enum_values: [position, velocity, effort]
  default_value: position

The ROS parameter stays a string. The generator adds one_of<> with the listed values (before any user validators), so unknown strings are rejected before conversion.

  • C++: enum class ControlMode {position, velocity, effort,}; inside the owning struct, the field defaults to Params::ControlMode::position, and update_parameter assigns from_string<Params::ControlMode>(param.as_string()). The namespace gets to_string(Params::ControlMode) (found by ADL), a from_string specialization that throws std::invalid_argument, and a to_parameter_value overload. No new dependency; headers without enums only gain the <stdexcept> and <string_view> includes.
  • Python: class ControlMode(str, enum.Enum) inside the owning struct, so string comparisons keep working; updates assign ControlMode(param.value) and declare/set pass .value.
  • Generation-time checks: enum_values non-empty and unique; default in the list; an explicit one_of<> on type: enum is rejected; enumerators verbatim, rejecting non-identifiers and C++/Python keywords, plus names starting with _ and mro (Python's enum fails on those); the PascalCase type name may not equal the enclosing struct's name, or a sibling field or sub-struct.
  • README and the four example READMEs document the type; the shared example parameters.yaml has an enum parameter, covered by the consistency tests.

Not included:

Tests:

  • test/test_enum_parameters.py: 52 tests (each error case, generated C++ and Python snippets, markdown output, validate_config).
  • In a ros:rolling container (Ubuntu 26.04): colcon build of all six packages and colcon test: 449 tests, 0 failures, 1 skipped (existing "pip is not installed"). New consistency tests cover the default, string conversions, runtime update, rejection of an invalid value and reading at declare time, in the C++, Python and CMake-module examples.
  • git merge-tree against Add runtime packages for generated code #441, Support bool_array_fixed_XX parameters #414 and Erase stale mapped entries in refresh_dynamic_parameters #415 shows no conflicts.
  • pre-commit passes on the changed files, including the ament hooks run in the container.

Not run: Lyrical, Humble and Windows.

Written with help from Claude Code.

@christophfroehlich
christophfroehlich requested a balanced review from Copilot November 25, 2026 16:54
@christophfroehlich

Copy link
Copy Markdown
Collaborator

Thanks, this covers everything agreed in #392. Nothing blocking from my side; three small points:

  1. YAML booleans in enum_values: unquoted on/off/yes/no are parsed as True/False, so enum_values: [off, on] fails with "Enum value True … is not a valid identifier", which is confusing. Could validate_enum_values add a hint for bool values, e.g. "quote it: 'on'"?
  2. Enum named params inside a group: pid: { params: {type: enum, ...} } declares enum class Params inside struct Pid, which then shadows Params there, so Params::Pid::Params doesn't compile. check_enum_names doesn't catch it; seeding taken with 'Params' would.
  3. Macro names: values are verbatim, so e.g. ERROR breaks on Windows and NULL/EOF everywhere. A README line recommending lowercase names would be enough.

Also, the DCO check is failing, please sign off your commit (git commit --amend -s and force-push).

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Changes recommended

Enum name validation still permits keywords and naming collisions that cause Python import or runtime failures and prevent generated C++ headers from compiling.

3 open issues
What changed in this PR

Adds type: enum to the parameter generator, providing typed C++ and Python fields while keeping ROS parameters as strings, addressing #392.

Changes:

  • Generates enum declarations, string conversions, and automatic allowed-value validation.
  • Adds generation-time checks for enum definitions and naming conflicts; mapped enums remain unsupported.
  • Documents the feature and adds generator and example consistency tests.
File Description
README.md Documents enum syntax, conversions, and limitations.
generate_parameter_library_py/​setup.py Packages the new enum templates.
generate_parameter_library_py/​generate_parameter_library_py/​test/​test_enum_parameters.py Tests generation, validation, and documentation.
generate_parameter_library_py/​generate_parameter_library_py/​python_conversions.py Adds Python enum conversion expressions.
generate_parameter_library_py/​generate_parameter_library_py/​parse_yaml.py Parses enums, validates definitions, and coordinates generation.
generate_parameter_library_py/​generate_parameter_library_py/​jinja_templates/​python/​update_parameter Converts updated values into enum members.
generate_parameter_library_py/​generate_parameter_library_py/​jinja_templates/​python/​set_parameter Converts initial parameter values into enum members.
generate_parameter_library_py/​generate_parameter_library_py/​jinja_templates/​python/​parameter_library_header Imports enum support and emits root enum classes.
generate_parameter_library_py/​generate_parameter_library_py/​jinja_templates/​python/​declare_struct Emits nested enum classes.
generate_parameter_library_py/​generate_parameter_library_py/​jinja_templates/​python/​declare_enum Defines string-backed Python enums.
generate_parameter_library_py/​generate_parameter_library_py/​jinja_templates/​cpp/​update_parameter Converts updated strings into typed enum values.
generate_parameter_library_py/​generate_parameter_library_py/​jinja_templates/​cpp/​set_parameter Converts initial strings into typed enum values.
generate_parameter_library_py/​generate_parameter_library_py/​jinja_templates/​cpp/​parameter_library_header Emits root enums and conversion helpers.
generate_parameter_library_py/​generate_parameter_library_py/​jinja_templates/​cpp/​declare_struct Emits nested enum declarations.
generate_parameter_library_py/​generate_parameter_library_py/​jinja_templates/​cpp/​declare_enum Defines scoped C++ enums.
generate_parameter_library_py/​generate_parameter_library_py/​cpp_conversions.py Adds C++ enum type and conversion expressions.
example/​test/​test_params_consistency.cpp Tests enum defaults, conversions, updates, and rejection.
example/​README.md Lists the new example parameter.
example_python/​test/​test_params_consistency.py Tests Python enum behavior against node values.
example_python/​README.md Lists the new example parameter.
example_python/​generate_parameter_module_example/​parameters.yaml Adds the shared control_mode enum example.
example_external/​README.md Lists the new example parameter.
example_cmake_python/​test/​test_params_consistency.py Tests enum behavior in the CMake Python example.
example_cmake_python/​README.md Lists the new example parameter.

Review effort: Balanced

jjohnnystwsss and others added 2 commits November 26, 2026 03:45
`type: enum` declares a string parameter whose value is one of
`enum_values`. The generator adds the one_of<> validation from the list
before any other validator, and the generated code holds the value as
an enum:

- C++: an `enum class` in the struct that holds the field, with
  to_string(), from_string<T>() and a to_parameter_value() overload in
  the namespace, so StackParams can hold it too.
- Python: a `(str, enum.Enum)` class in the struct class, so members
  still compare equal to their strings. declare_parameter gets the
  string value.

The definition is checked at generation time: the list must be
non-empty and unique, its values must be identifiers that are not C++
or Python keywords or names Python's enum reserves, the default must be
listed, an explicit one_of<> is rejected, and the enum type must not
clash with its struct or another member of it. Mapped parameters
cannot have type enum yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: jjohnnystwsss <33243683+jjohnnystwsss@users.noreply.github.com>
- Explain YAML booleans in enum_values and default_value: unquoted
  on/off, yes/no and true/false need quotes.
- Name the C++ enum types from the global namespace
  (::ns::Params::...), so that no nested group or enum called params
  can hide the Params struct, and reserve Params as an enum name.
- Reject an enum next to a group whose attribute has the enum's type
  name, which masked the Python enum class.
- Reject enum type names that are keywords, such as None for a
  parameter called none.
- README: recommend lowercase values, which avoid macros such as
  ERROR, NULL and EOF, and quoting YAML boolean words.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: jjohnnystwsss <33243683+jjohnnystwsss@users.noreply.github.com>
@jjohnnystwsss

Copy link
Copy Markdown
Contributor Author

Thanks for the review! Addressed in b6e1406:

  1. A boolean in enum_values (or default_value) now gets its own error: "Enum value True of parameter mode is a boolean. YAML reads unquoted on/off, yes/no and true/false as booleans: quote it, e.g. 'on'." The README mentions quoting as well.
  2. check_enum_names now reserves Params. While testing it I noticed that a group named params breaks the same qualification (Params::Pid::Mode inside struct Pid resolves to Pid::Params), which a name check on enums can't catch. So the C++ types are now also named from the global namespace, e.g. ::admittance_controller::Params::Pid::Mode, as Copilot suggested; there is a generator test for the group case, and I built and ran it against rclcpp.
  3. Added a README line recommending lowercase values (ERROR, NULL, EOF).

I also fixed the two other Copilot findings (a group named like the enum type masking the Python enum class, and enum names whose PascalCase form is a keyword, such as none → None).

Both commits are now signed off for DCO. Checks: 67 enum generator tests, and colcon test in ros:rolling: 464 tests, 0 failures (1 existing skip).

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟢 Approval recommended

No active review issues block approval of the enum parameter support change.

No open issues 🎉

3 resolved since last review

Review effort: Balanced

@christophfroehlich christophfroehlich left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks, LGTM

@christophfroehlich christophfroehlich added the backport-humble Triggers PR backport to ROS 2 humble. label Nov 25, 2026
@christophfroehlich
christophfroehlich merged commit 3f8586d into ros-tooling:main Nov 25, 2026
20 checks passed
@Timple

Timple commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Thank you for picking this up! I wasn't fast enough with the review I see 😄

Might be a nitpick, but we really prefer capitals for enums. It's quite common for c++ as well as python.

  // Set initial velocity
  using enum Params::InitVelMethod;
  switch (config_.init_vel_method) {
    case zero:
      reset();
      break;
    case odom:
      reset();
      controller_state_.current_x_vel = odom_twist.linear.x;
      controller_state_.current_yaw_vel = odom_twist.angular.z;
      break;

VS

  // Set initial velocity
  using enum Params::InitVelMethod;
  switch (config_.init_vel_method) {
    case ZERO:
      reset();
      break;
    case ODOM:
      reset();
      controller_state_.current_x_vel = odom_twist.linear.x;
      controller_state_.current_yaw_vel = odom_twist.angular.z;
      break;

In the second case it's much more clear they are constants. (See how the github codestyle even picks it up?)

Could we make the enums capitals and the comparison to parameter values case insensitive?

@Timple

Timple commented Nov 27, 2026

Copy link
Copy Markdown
Contributor

I could put in a PR which makes the code part upper_case.

Or a PR that would keep the enum to whatever is specified in the yaml. But do case-insensitive matching on it. (As parameters are typically lower-cased again).

@jjohnnystwsss

Copy link
Copy Markdown
Contributor Author

Thanks! Upper-case constants make sense to me. One thing to watch with case-insensitive matching: values that differ only in case (like fast and FAST) would collide, so the generator should reject those. @christophfroehlich, which way would you prefer? @Timple, feel free to open the PR since you offered.

@christophfroehlich

Copy link
Copy Markdown
Collaborator

Agreed on upper-case constants.

I'd split the request in two:

Upper-case enumerators: yes. The values are used exactly as written, so enum_values: [ZERO, ODOM] already gives ZERO/ODOM today, but then the parameter string has to be "ZERO" too. To keep lower-case configs working, the follow-up could generate the enumerator as the upper-cased value and keep the string as listed:

init_vel_method:
  type: enum
  enum_values: [zero, odom]
  default_value: zero
enum class InitVelMethod { ZERO, ODOM };  // to_string/from_string map to "zero"/"odom"
class InitVelMethod(str, enum.Enum):
    ZERO = "zero"
    ODOM = "odom"

This needs one extra build-time check: reject values that are the same once upper-cased (fast and FAST).

Case-insensitive matching: I'd rather not. one_of<> is an exact compare, so this would need a new validator or normalizing the string first. Then the node holds "Zero", the struct holds ZERO and to_string() returns "zero", so three spellings of one value. It would also make type: enum behave differently from type: string + one_of. The upper-casing above already keeps lower-case configs working.

One thing to keep in mind with upper case: these names can clash with C macros, e.g. EOF, NAN and INFINITY from standard headers, or ERROR and DELETE from <windows.h>. The result is a confusing compile error. We could reject a few well-known ones at generation time and document the rest.

@Timple

Timple commented Nov 30, 2026

Copy link
Copy Markdown
Contributor

To keep lower-case configs working

I wasn't aware this was important as it was released just days ago without a version bump. But we can make this happen!

I already had the case insensitive PR ready in case you want to take a peek.

But now the other PR is also almost ready taking your proposal!

@christophfroehlich

Copy link
Copy Markdown
Collaborator

I wasn't aware this was important as it was released just days ago without a version bump. But we can make this happen!

True: we don't have to take care of broken builds since the merge as we haven't released it yet. But this is a design decision: Should the strings in the declarative yaml as well the parameters be upper or lower cased?

@Timple

Timple commented Nov 30, 2026

Copy link
Copy Markdown
Contributor

Got it, I misunderstood

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backport-humble Triggers PR backport to ROS 2 humble.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Feature: Enum support

4 participants