Skip to content

Conversation

dcoutinho1328
Copy link

@dcoutinho1328 dcoutinho1328 commented Jul 21, 2025

Summary by CodeRabbit

  • New Features
    • Added support for parsing Structured Text (ST) files to extract complex variable declarations within TYPE and STRUCT blocks.
    • Introduced a new template for generating function block definitions with customizable input variables.
  • Chores
    • Updated the development environment to include a new Visual Studio Code extension for Structured Text.
  • Improvements
    • Enhanced template loading efficiency and code maintainability in project management features.
    • Improved error handling and file processing workflow for ST file generation and parsing.

Copy link

coderabbitai bot commented Jul 21, 2025

Warning

Rate limit exceeded

@dcoutinho1328 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 2 minutes and 18 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between a601391 and 649d72a.

📒 Files selected for processing (2)
  • ComplexParser.py (1 hunks)
  • xml2st.py (5 hunks)

Walkthrough

A new ComplexParser class is introduced for parsing Structured Text (ST) files to extract complex variable declarations within TYPE/STRUCT blocks, generating processed output using Jinja2 templates. The parser is integrated into the xml2st.py workflow. Template management in ProjectController.py is refactored to centralize the Jinja2 loader, and a new function block template is added. The development container configuration is updated to include a VS Code extension. Error and warning outputs in xml2st.py are redirected to stderr.

Changes

File(s) Change Summary
.devcontainer/devcontainer.json Added "Serhioromano.vscode-st" to the list of VS Code extensions.
ComplexParser.py Introduced ComplexParser class for parsing and rewriting ST files with Jinja2 templating.
ProjectController.py Centralized Jinja2 template loader setup in constructor; refactored template usage.
templates/function_block.st.j2 Added new Jinja2 template for generating function block code in ST.
xml2st.py Added parse_complex_variables() to invoke ComplexParser after ST generation; redirected error output to stderr; updated file saving logic.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant xml2st.py
    participant ComplexParser
    participant FileSystem
    participant Jinja2

    User->>xml2st.py: Run with --generate-st
    xml2st.py->>FileSystem: Save generated ST file
    xml2st.py->>ComplexParser: parse_complex_variables(st_file)
    ComplexParser->>FileSystem: Read ST file
    ComplexParser->>Jinja2: Render code blocks for complex variables
    ComplexParser->>FileSystem: Write processed ST file
    ComplexParser-->>xml2st.py: Return processed content
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~30 minutes

Poem

In the warren of code, a parser appears,
To untangle STRUCTs and calm our fears.
With templates anew and logic refined,
Complex variables are clearly defined.
Extensions installed, the toolbox grows—
A hop, a skip, and the project flows!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch RTOP-35-Add-support-for-complex-variables-on-debug.c

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.
    • Explain this complex logic.
    • 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. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • 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 src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

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

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

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

Documentation and Community

  • 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.

Copy link

@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.

Actionable comments posted: 2

🧹 Nitpick comments (1)
ComplexParser.py (1)

76-90: Consider more robust parsing for variable declarations.

The current parsing logic assumes specific formatting with colons and semicolons. This might break if the ST file has different formatting (e.g., extra spaces, different line breaks).

Consider using a more robust parsing approach, such as:

  • Regular expressions to handle varying whitespace
  • A proper ST parser library if available
  • More comprehensive error handling for malformed lines

Example improvement:

import re

# Pattern for variable declaration with optional initialization
var_pattern = re.compile(r'^\s*(\w+)\s*:\s*(\w+)(?:\s*:=\s*([^;]+))?\s*;?\s*$')
match = var_pattern.match(line)
if match:
    name, type_name, value = match.groups()
    complex_vars[-1][1][name] = {"type": type_name, "value": value}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2535fe5 and cbec3a0.

📒 Files selected for processing (5)
  • .devcontainer/devcontainer.json (1 hunks)
  • ComplexParser.py (1 hunks)
  • ProjectController.py (3 hunks)
  • templates/function_block.st.j2 (1 hunks)
  • xml2st.py (4 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
ProjectController.py (1)
util/paths.py (1)
  • AbsDir (36-37)
ComplexParser.py (1)
util/paths.py (1)
  • AbsDir (36-37)
🪛 Ruff (0.12.2)
ComplexParser.py

53-53: Ambiguous variable name: l

(E741)

🔇 Additional comments (6)
.devcontainer/devcontainer.json (1)

20-21: LGTM!

The addition of the Structured Text VS Code extension is appropriate for the new ST file parsing capabilities introduced in this PR.

ProjectController.py (2)

10-12: Good refactoring!

Centralizing the template loader initialization avoids redundant instantiation and improves performance.


164-164: LGTM!

Correctly reuses the pre-initialized loader instance.

xml2st.py (2)

60-72: LGTM!

The function properly validates the input file and handles errors appropriately.


123-125: Should complex variable parsing also apply to debug mode?

Complex variable parsing is performed after generating the ST file with --generate-st, but not with --generate-debug. Is this intentional, or should complex variables also be parsed when debug information is included?

templates/function_block.st.j2 (1)

11-15: Is the hardcoded local_temp variable intentional?

The template always declares and initializes a local_temp variable to 0. Is this a placeholder that should be parameterized, or is it intentionally hardcoded for a specific purpose?

Copy link

@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.

Actionable comments posted: 0

♻️ Duplicate comments (2)
ComplexParser.py (2)

38-39: Fix incomplete exception message.

The exception message is incomplete and ends with "Please ". This needs to be completed with specific instructions.


53-54: Rename ambiguous variable name.

The variable l is ambiguous and reduces code readability. This issue was previously identified and should be addressed.

Also applies to: 99-100, 102-102

🧹 Nitpick comments (2)
xml2st.py (2)

61-76: Well-structured function with good validation and error handling.

The function properly validates the ST file format and handles parsing exceptions appropriately. Consider whether the inconsistent behavior (returning None vs sys.exit) between file validation and parsing errors is intentional.


42-42: Remove unnecessary f-string prefix.

The f-string has no placeholders, so the f prefix is unnecessary and should be removed.

-        print(f"Error: Failed to load XML project file.", file=sys.stderr)
+        print("Error: Failed to load XML project file.", file=sys.stderr)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between cbec3a0 and 2ddd246.

📒 Files selected for processing (2)
  • ComplexParser.py (1 hunks)
  • xml2st.py (5 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
ComplexParser.py (1)
util/paths.py (1)
  • AbsDir (36-37)
xml2st.py (2)
ComplexParser.py (2)
  • ComplexParser (9-104)
  • ParseSTFile (33-104)
plcopen/plcopen.py (1)
  • LoadProject (325-329)
🪛 Ruff (0.12.2)
ComplexParser.py

53-53: Ambiguous variable name: l

(E741)

xml2st.py

42-42: f-string without any placeholders

Remove extraneous f prefix

(F541)

⏰ 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). (1)
  • GitHub Check: build-windows-arm
🔇 Additional comments (6)
ComplexParser.py (3)

11-14: Constructor implementation looks good.

The Jinja2 FileSystemLoader initialization is properly configured using the absolute directory path.


16-31: Template-based code generation implementation is solid.

The method correctly uses Jinja2 templating to generate function blocks and saves the processed output with an appropriate naming convention.


56-91: Parsing logic is well-designed and handles edge cases properly.

The state machine correctly tracks TYPE/STRUCT boundaries, prevents invalid nesting, and properly extracts variable information including optional initial values.

xml2st.py (3)

8-8: Import statement is properly placed.

The ComplexParser import follows the existing import structure and is correctly positioned.


14-16: Excellent improvement in error output handling.

Redirecting error messages to sys.stderr follows best practices and improves the separation of normal output from error output.

Also applies to: 30-30, 36-36, 42-42


126-132: Clean integration of complex variable parsing into the workflow.

The sequential flow from ST generation to file saving to complex variable parsing is logical and well-structured.

Copy link

@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.

Actionable comments posted: 1

♻️ Duplicate comments (2)
ComplexParser.py (2)

38-39: Fix incomplete exception message.

The exception message is incomplete and ends with "Please ".


53-54: Rename ambiguous variable name.

Using l as a variable name is ambiguous and reduces readability. Also update references on lines 85 and 88.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2ddd246 and 6f01bf6.

📒 Files selected for processing (2)
  • ComplexParser.py (1 hunks)
  • templates/function_block.st.j2 (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • templates/function_block.st.j2
🧰 Additional context used
🧬 Code Graph Analysis (1)
ComplexParser.py (1)
util/paths.py (1)
  • AbsDir (36-37)
🪛 Ruff (0.12.2)
ComplexParser.py

53-53: Ambiguous variable name: l

(E741)

⏰ 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). (1)
  • GitHub Check: build-windows-arm
🔇 Additional comments (3)
ComplexParser.py (3)

1-7: LGTM!

The imports are appropriate and the constants are well-defined to avoid magic strings throughout the code.


9-14: LGTM!

The initialization correctly sets up the Jinja2 FileSystemLoader with an absolute path, ensuring templates are found regardless of the current working directory.


16-31: LGTM!

The method correctly uses Jinja2 templating to generate code blocks for complex variables and properly handles file operations with context managers.

dcoutinho1328 and others added 2 commits July 24, 2025 14:58
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Copy link

@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.

Actionable comments posted: 0

♻️ Duplicate comments (1)
ComplexParser.py (1)

53-54: Fix ambiguous variable name as flagged in previous review.

The variable name l is still present and flagged by static analysis. This was identified in a previous review and should be addressed.

Apply this diff to fix the ambiguous variable name:

-        for l in lines:
-            line = l.strip()
+        for line_raw in lines:
+            line = line_raw.strip()

Also update the reference on line 88:

-            new_lines.append(l)
+            new_lines.append(line_raw)
🧹 Nitpick comments (1)
ComplexParser.py (1)

33-90: Consider adding input validation and error handling.

The parsing method could benefit from additional robustness:

  1. File existence check: Validate that the file exists before attempting to read it
  2. File reading error handling: Wrap file operations in try-catch blocks
  3. Template rendering error handling: Handle potential Jinja2 template errors
 def ParseSTFile(self, file):
     """
     Parse ST file to extract complex variables.
     """
     
     if not file:
         raise Exception("ST file not valid. Please provide a valid ST file path.")
+    
+    if not os.path.exists(file):
+        raise Exception(f"ST file does not exist: {file}")

     self.__stFile = file

     lines = []

-    with open(self.__stFile, "r") as f:
-        lines = f.readlines()
+    try:
+        with open(self.__stFile, "r") as f:
+            lines = f.readlines()
+    except IOError as e:
+        raise Exception(f"Error reading ST file: {e}")
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6f01bf6 and f36573a.

📒 Files selected for processing (1)
  • ComplexParser.py (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
ComplexParser.py (1)
util/paths.py (1)
  • AbsDir (36-37)
🪛 Ruff (0.12.2)
ComplexParser.py

53-53: Ambiguous variable name: l

(E741)

⏰ 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). (1)
  • GitHub Check: build-windows-arm
🔇 Additional comments (7)
ComplexParser.py (7)

1-7: LGTM! Clean imports and well-defined constants.

The imports are appropriate for the functionality, and the constants follow good practices by avoiding magic strings throughout the code.


9-14: LGTM! Proper template loader initialization.

The constructor correctly sets up the Jinja2 FileSystemLoader using the utility function to resolve the absolute path to the templates directory.


16-31: LGTM! Well-structured template rendering and file output.

The method correctly:

  • Renders Jinja2 templates for each complex variable
  • Appends remaining ST file content
  • Writes to a properly named output file
  • Returns the generated content for flexibility

The implementation is clean and follows good practices.


38-39: Exception message has been properly fixed.

The incomplete exception message from the previous review has been addressed with a clear and informative error message.


58-71: LGTM! Proper validation and parsing logic for STRUCT declarations.

The code correctly:

  • Validates that STRUCT declarations are not nested
  • Ensures STRUCTs appear within TYPE blocks
  • Extracts the variable name and initializes the complex variable structure

The validation logic prevents malformed ST files from being processed incorrectly.


79-83: Bounds checking has been properly implemented.

The previous review concern about accessing new_lines[-1] without bounds checking has been addressed. The code now properly checks if new_lines and TYPE_TOKEN in new_lines[-1]: before accessing the last element.


84-86: LGTM! Smart empty line handling.

The logic to skip consecutive empty lines is well-implemented and will help produce cleaner output by avoiding unnecessary blank lines.

@thiagoralves thiagoralves self-requested a review July 24, 2025 15:16
@thiagoralves thiagoralves merged commit 19bcba7 into development Jul 24, 2025
7 checks passed
@thiagoralves thiagoralves deleted the RTOP-35-Add-support-for-complex-variables-on-debug.c branch July 24, 2025 17:33
@coderabbitai coderabbitai bot mentioned this pull request Sep 22, 2025
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