Skip to content

Support local vars in C/C++ function blocks#707

Open
manux81 wants to merge 6 commits into
Autonomy-Logic:developmentfrom
manux81:fix/cpp-fb-local-vars
Open

Support local vars in C/C++ function blocks#707
manux81 wants to merge 6 commits into
Autonomy-Logic:developmentfrom
manux81:fix/cpp-fb-local-vars

Conversation

@manux81
Copy link
Copy Markdown

@manux81 manux81 commented Mar 31, 2026

Pull request info

References

If applicable substitute the issue reference to the one that this PR refers

This PR resolve the N/A.

Link to Jira task

N/A

Description of the changes proposed

  • expose user-defined local variables in the generated C/C++ FB bridge
  • keep runtime-only helper locals such as hasBeenInitialized out of the exposed bridge
  • preserve local arrays through the __flat_* staging/copy-back path in the generated ST wrapper
  • add a regression test covering local array staging in the generated ST/header/code bridge
  • allow local as a selectable class for cpp variables in the table editor
  • default newly created cpp variables to local

DOD checklist

  • The code is complete and according to developers’ standards.
  • I have performed a self-review of my code.
  • Meet the acceptance criteria.
  • Unit tests are written and green.
  • Test coverage: N/A %.
  • Integration tests are written and green.
  • Changes were communicated and updated in the ticket description.
  • Reviewed and accepted by the Product Owner.
  • End-to-end test are successful.

Summary by CodeRabbit

  • Bug Fixes

    • Generated C outputs now include user-defined local variables in struct and macro sections while still excluding runtime-only locals.
  • User Interface

    • When creating a new variable, defaults now map Python variables to "input" and other languages to "local" (previous cpp special-case removed).
  • Tests

    • Updated tests to validate inclusion of user-defined locals and exclusion of runtime-only locals.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Mar 31, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 16997033-30db-40b7-ba64-1c64f004fbda

📥 Commits

Reviewing files that changed from the base of the PR and between 232b0a3 and 86e6906.

📒 Files selected for processing (1)
  • src/frontend/components/_organisms/variables-editor/index.tsx

Walkthrough

The PR changes which PLC variables are exposed to generated C/C++ blocks by replacing class-based filtering with getExposedCppVariables(...). Tests and test helpers were updated to allow and assert inclusion of user-defined local variables (while excluding runtime-only locals). The variables-editor default for new variables now favors local (except for Python).

Changes

C/C++ Variable Exposure

Layer / File(s) Summary
Data Selection
src/backend/shared/utils/cpp/...getExposedCppVariables (used), src/backend/shared/utils/cpp/generateCBlocksCode.ts
Replaced ad-hoc `v.class === 'input'
Header Generation
src/backend/shared/utils/cpp/generateCBlocksHeader.ts
Struct member emission now iterates getExposedCppVariables(...) rather than separate input/output filters.
Code Emission
src/backend/shared/utils/cpp/generateCBlocksCode.ts
#define macros, rewritten user code insertion, and #undef directives are emitted for the variables returned by getExposedCppVariables(...).
UI Defaulting
src/frontend/components/_organisms/variables-editor/index.tsx
defaultClass for newly created variables: python'input', all other languages (including cpp) → 'local'.
Tests
src/backend/shared/utils/cpp/__tests__/generateCBlocksCode.test.ts, src/backend/shared/utils/cpp/__tests__/generateCBlocksHeader.test.ts
Test helpers widened to allow class: 'local'. Tests rewritten to assert user-defined local variables appear in generated struct/#define/#undef output and that runtime-only locals (e.g., hasBeenInitialized) are excluded.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • Autonomy-Logic/openplc-editor#386: Directly modifies the same C/C++ blocks generation logic around variable inclusion, with parallel changes to generateCBlocksCode/generateCBlocksHeader and their test suites.

Suggested labels

enhancement

Suggested reviewers

  • DanielBorgesDev
  • JoaoGSP

Poem

🐰 I nibble names that once were hid,
I tuck in locals now not forbid;
Some runtime seeds must stay unseen,
But user vars can hop between—
A tiny hop for codegen bliss.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Support local vars in C/C++ function blocks' clearly and concisely summarizes the main change: enabling local variables in C/C++ function blocks.
Description check ✅ Passed The description provides a clear list of changes but lacks issue references, test coverage percentage, and several DOD items are unchecked (unit/integration tests, E2E tests, PO approval).
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/utils/cpp/generateSTCode.ts (1)

77-102: ⚠️ Potential issue | 🔴 Critical

Copy local arrays back to data__ after the C/C++ call.

local arrays now go through the __flat_* staging path, but the copy-back still runs only for output variables. Any mutation to a local array inside setup() or loop() is discarded at the end of the cycle, so FB state is not actually preserved for that class of variable.

💡 Minimal fix
   const inputVariables = exposedVariables.filter((v) => v.class === 'input')
   const outputVariables = exposedVariables.filter((v) => v.class === 'output')
   const localVariables = exposedVariables.filter((v) => v.class === 'local')
+  const statefulVariables = [...outputVariables, ...localVariables]
@@
-  const outputCopyBack = generateOutputArrayCopyBack(outputVariables)
+  const outputCopyBack = generateOutputArrayCopyBack(statefulVariables)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/utils/cpp/generateSTCode.ts` around lines 77 - 102, Local arrays that go
through the __flat_* staging path are not being copied back into data__ after
the C/C++ call because only outputVariables are passed to
generateOutputArrayCopyBack; as a result mutations to local arrays are lost.
Update the code that builds outputCopyBack (the variable named outputCopyBack)
to include localVariables as well (e.g., pass [...outputVariables,
...localVariables] into generateOutputArrayCopyBack or call a helper that merges
both sets) so that local array contents are copied back into data__ after
setup() / loop().
🧹 Nitpick comments (1)
src/utils/cpp/generateCppBridge.test.ts (1)

53-88: Add a local-array regression case.

These assertions only exercise scalar local variables. Array locals take the separate __flat_* path in generateSTCode, so a dedicated case is needed to catch state-persistence regressions there.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/utils/cpp/generateCppBridge.test.ts` around lines 53 - 88, The tests only
cover scalar locals; add a regression test that defines a local array variable
(similar to localVar but with an array dimension) and include it in the inputs
to generateSTCode, generateCBlocksHeader, and generateCBlocksCode to exercise
the __flat_* array handling path. In that new test assert that the ST output
contains the array-flat mapping pattern used by generateSTCode (search for the
generated __flat_ symbol that maps the array into vars), and assert the
header/code outputs include the array pointer/define forms (the __flat_* symbol
and array-specific declarations) and still do not include scalar-only names like
HASBEENINITIALIZED or hasBeenInitialized; add this case alongside the existing
scalar tests to catch regressions in array local persistence handling.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@src/utils/cpp/generateSTCode.ts`:
- Around line 77-102: Local arrays that go through the __flat_* staging path are
not being copied back into data__ after the C/C++ call because only
outputVariables are passed to generateOutputArrayCopyBack; as a result mutations
to local arrays are lost. Update the code that builds outputCopyBack (the
variable named outputCopyBack) to include localVariables as well (e.g., pass
[...outputVariables, ...localVariables] into generateOutputArrayCopyBack or call
a helper that merges both sets) so that local array contents are copied back
into data__ after setup() / loop().

---

Nitpick comments:
In `@src/utils/cpp/generateCppBridge.test.ts`:
- Around line 53-88: The tests only cover scalar locals; add a regression test
that defines a local array variable (similar to localVar but with an array
dimension) and include it in the inputs to generateSTCode,
generateCBlocksHeader, and generateCBlocksCode to exercise the __flat_* array
handling path. In that new test assert that the ST output contains the
array-flat mapping pattern used by generateSTCode (search for the generated
__flat_ symbol that maps the array into vars), and assert the header/code
outputs include the array pointer/define forms (the __flat_* symbol and
array-specific declarations) and still do not include scalar-only names like
HASBEENINITIALIZED or hasBeenInitialized; add this case alongside the existing
scalar tests to catch regressions in array local persistence handling.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: ea9156d2-b7af-42aa-9423-0ca49a8306dd

📥 Commits

Reviewing files that changed from the base of the PR and between d5d5bc4 and 2a6b7a3.

📒 Files selected for processing (7)
  • src/renderer/components/_molecules/variables-table/selectable-cell.tsx
  • src/renderer/components/_organisms/variables-editor/index.tsx
  • src/utils/cpp/generateCBlocksCode.ts
  • src/utils/cpp/generateCBlocksHeader.ts
  • src/utils/cpp/generateCppBridge.test.ts
  • src/utils/cpp/generateSTCode.ts
  • src/utils/cpp/shared.ts

@manux81
Copy link
Copy Markdown
Author

manux81 commented Apr 6, 2026

Quick follow-up on the CodeRabbit findings: both points are already covered in the current PR head fbd9891.

  • src/utils/cpp/generateSTCode.ts now copies staged local arrays back into data__ by passing both output and local variables to the array copy-back path.
  • src/utils/cpp/generateCppBridge.test.ts now includes a dedicated regression test for local arrays through the __flat_* staging flow.

So the remaining visible CodeRabbit notes look historical relative to the current head, not pending code changes.

@manux81
Copy link
Copy Markdown
Author

manux81 commented Apr 16, 2026

I updated PR #707 by merging the latest development branch and resolving the merge conflicts. The branch is now mergeable again from a code/conflict standpoint. At this point, the remaining blockers are approval for the pending GitHub Actions workflows and 2 approving reviews from reviewers with write access.

Could a maintainer please approve the pending workflows and review the PR?

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.

1 participant