Skip to content

Conversation

@kolipakakondal
Copy link
Collaborator

@kolipakakondal kolipakakondal commented Jun 6, 2025

Description

Write a script to remove -m and -f arguments from compile_commands.json so that we can avoid errors when navigating the ESP-IDF internal component source code

Why? Those arguments are applicable to the GCC compiler, but when Clangd uses the compile_commands.json file, it throws errors saying the arguments are invalid.

This PR includes the script and the steps required to use it, so we can recommend it to users. Going forward, we can consider implementing it by default as part of project creation, along with updating the CMakeLists.txt.

Fixes # (IEP-1550)
Triggered by https://esp32.com/viewtopic.php?t=45824

Type of change

  • This change requires a documentation update

How has this been tested?

Please describe the tests that you ran to verify your changes. Provide instructions so we can reproduce. Please also list any relevant details for your test configuration

  • Test A
  • Test B

Test Configuration:

  • ESP-IDF Version:
  • OS (Windows,Linux and macOS):

Dependent components impacted by this PR:

  • Component 1
  • Component 2

Checklist

  • PR Self Reviewed
  • Applied Code formatting
  • Added Documentation
  • Added Unit Test
  • Verified on all platforms - Windows,Linux and macOS

Summary by CodeRabbit

  • New Features

    • Added a script and build integration to automatically clean problematic compiler flags from compile_commands.json, improving navigation in LSP-based C/C++ editors for ESP-IDF projects.
  • Documentation

    • Updated documentation with detailed instructions for resolving "Unknown argument" errors in clangd, including usage of the new script and build integration steps.

Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

Adds a helper script to strip unsupported GCC flags from compile_commands.json, integrates it into the CMake build, and documents the workflow for ESP-IDF users.

  • Introduce fix_compile_commands.py to remove -m* and -f* flags.
  • Add a CMake custom target (fix_clangd) to run the script post-build.
  • Extend the RST documentation with setup steps and example links.

Reviewed Changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 2 comments.

File Description
resources/fix_compile_commands/fix_compile_commands.py New Python script to filter out -m* and -f* flags
resources/fix_compile_commands/CMakeLists.txt Custom CMake target to invoke the cleanup script after build
docs/en/additionalfeatures/clangd_cdt_support.rst Added instructions and example links for running the cleanup tool
Comments suppressed due to low confidence (3)

resources/fix_compile_commands/fix_compile_commands.py:20

  • The remove_mf_flags function currently lacks unit tests. Add tests covering both the 'arguments' array and the 'command' string cases, including edge cases with quoted flags.
def remove_mf_flags(compile_commands):

docs/en/additionalfeatures/clangd_cdt_support.rst:62

  • The URL includes a duplicated 'resources/resources' segment. Update the link to point to resources/fix_compile_commands/fix_compile_commands.py.
Download the script from `here <https://github.com/espressif/idf-eclipse-plugin/tree/master/resources/resources/fix_compile_commands/fix_compile_commands.py>`_.

docs/en/additionalfeatures/clangd_cdt_support.rst:64

  • The example link path also contains 'resources/resources'. Correct it to resources/fix_compile_commands/CMakeLists.txt.
Invoke the script from the project post build step. Here is example for `CMakeLists.txt <https://github.com/espressif/idf-eclipse-plugin/blob/master/resources/resources/fix_compile_commands/CMakeLists.txt>`_.


def remove_mf_flags(compile_commands):
for entry in compile_commands:
args = entry.get("arguments") or entry.get("command", "").split()
Copy link

Copilot AI Jun 6, 2025

Choose a reason for hiding this comment

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

Use shlex.split on the command string instead of str.split() to correctly handle quoted arguments and paths with spaces.

Copilot uses AI. Check for mistakes.
Comment on lines +6 to +10
if(EXISTS "${CMAKE_SOURCE_DIR}/fix_compile_commands.py")
add_custom_target(
fix_clangd ALL
COMMAND ${CMAKE_COMMAND} -E echo "Running fix_compile_commands.py..."
COMMAND ${CMAKE_COMMAND} -E env python3 ${CMAKE_SOURCE_DIR}/fix_compile_commands.py
Copy link

Copilot AI Jun 6, 2025

Choose a reason for hiding this comment

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

CMakeLists resides in a subdirectory, so ${CMAKE_SOURCE_DIR} may not resolve to this folder. Use ${CMAKE_CURRENT_SOURCE_DIR} to reference the script path correctly.

Suggested change
if(EXISTS "${CMAKE_SOURCE_DIR}/fix_compile_commands.py")
add_custom_target(
fix_clangd ALL
COMMAND ${CMAKE_COMMAND} -E echo "Running fix_compile_commands.py..."
COMMAND ${CMAKE_COMMAND} -E env python3 ${CMAKE_SOURCE_DIR}/fix_compile_commands.py
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/fix_compile_commands.py")
add_custom_target(
fix_clangd ALL
COMMAND ${CMAKE_COMMAND} -E echo "Running fix_compile_commands.py..."
COMMAND ${CMAKE_COMMAND} -E env python3 ${CMAKE_CURRENT_SOURCE_DIR}/fix_compile_commands.py

Copilot uses AI. Check for mistakes.
@espressif espressif deleted a comment from coderabbitai bot Jun 6, 2025
coderabbitai[bot]

This comment was marked as off-topic.

@coderabbitai
Copy link

coderabbitai bot commented Jun 6, 2025

Walkthrough

A new documentation section was added to address "Unknown argument" errors in clangd when working with ESP-IDF projects. A Python script and CMake integration were introduced to automatically clean problematic compiler flags from compile_commands.json, ensuring smoother navigation in LSP-based C/C++ editors.

Changes

File(s) Change Summary
docs/en/additionalfeatures/clangd_cdt_support.rst Updated documentation; added section on resolving clangd "Unknown argument" errors with ESP-IDF projects.
resources/fix_compile_commands/fix_compile_commands.py New script to remove -m* and -f* flags from compile_commands.json for clangd compatibility.
resources/fix_compile_commands/CMakeLists.txt New CMake file adding a custom target to run the script automatically after builds.

Sequence Diagram(s)

sequenceDiagram
    participant Developer
    participant CMake
    participant fix_compile_commands.py
    participant compile_commands.json

    Developer->>CMake: Build project
    CMake->>fix_compile_commands.py: Run as custom target after build
    fix_compile_commands.py->>compile_commands.json: Locate and read file
    fix_compile_commands.py->>compile_commands.json: Remove -m* and -f* flags
    fix_compile_commands.py->>compile_commands.json: Overwrite with cleaned content
    fix_compile_commands.py-->>Developer: Print confirmation message
Loading

Suggested reviewers

  • AndriiFilippov
  • alirana01

Poem

In the warren where code bunnies dwell,
A clangd error once rang a bell—
With flags that start with -m or -f,
Our script now hops in, quite deft!
CMake calls, the fix is run,
Now ESP-IDF coding is much more fun!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

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 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: 3

♻️ Duplicate comments (5)
resources/fix_compile_commands/fix_compile_commands.py (2)

22-22: 🛠️ Refactor suggestion

Use shlex.split() for proper command parsing.

Using str.split() on command strings can incorrectly split quoted arguments and paths containing spaces, leading to malformed compilation commands.

Apply this diff to use proper shell-aware parsing:

+import shlex
-        args = entry.get("arguments") or entry.get("command", "").split()
+        args = entry.get("arguments") or shlex.split(entry.get("command", ""))

39-46: 🛠️ Refactor suggestion

Add error handling for JSON operations and file I/O.

The script lacks error handling for JSON parsing and file operations, which could cause cryptic failures if the file is corrupted or has permission issues.

Apply this diff to add proper error handling:

-    with open(cc_path, "r") as f:
-        compile_commands = json.load(f)
-
-    cleaned_commands = remove_mf_flags(compile_commands)
-
-    with open(cc_path, "w") as f:
-        json.dump(cleaned_commands, f, indent=2)
+    try:
+        with open(cc_path, "r") as f:
+            compile_commands = json.load(f)
+        
+        if not isinstance(compile_commands, list):
+            print(f"Error: Expected list in {cc_path}, got {type(compile_commands)}")
+            return
+
+        cleaned_commands = remove_mf_flags(compile_commands)
+
+        with open(cc_path, "w") as f:
+            json.dump(cleaned_commands, f, indent=2)
+    except (json.JSONDecodeError, IOError) as e:
+        print(f"Error processing {cc_path}: {e}")
+        return
resources/fix_compile_commands/CMakeLists.txt (3)

6-6: 🛠️ Refactor suggestion

Use CMAKE_CURRENT_SOURCE_DIR for correct script path resolution.

CMakeLists.txt resides in a subdirectory, so CMAKE_SOURCE_DIR may not resolve to this folder correctly.

Apply this diff to reference the script path correctly:

-if(EXISTS "${CMAKE_SOURCE_DIR}/fix_compile_commands.py")
+if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/fix_compile_commands.py")

7-13: 🛠️ Refactor suggestion

Add dependency to ensure compile_commands.json exists before cleaning.

The custom target runs with ALL but doesn't depend on the main build target. This could cause the script to run before compile_commands.json is generated.

Apply this diff to add proper dependency:

     add_custom_target(
         fix_clangd ALL
         COMMAND ${CMAKE_COMMAND} -E echo "Running fix_compile_commands.py..."
         COMMAND ${CMAKE_COMMAND} -E env python3 ${CMAKE_CURRENT_SOURCE_DIR}/fix_compile_commands.py
         COMMENT "Cleaning compile_commands.json for clangd"
         VERBATIM
+        DEPENDS ${CMAKE_PROJECT_NAME}.elf
     )

10-10: 🛠️ Refactor suggestion

Use CMAKE_CURRENT_SOURCE_DIR for script execution path.

Consistent with the existence check, the script execution should also use the correct path variable.

Apply this diff:

-        COMMAND ${CMAKE_COMMAND} -E env python3 ${CMAKE_SOURCE_DIR}/fix_compile_commands.py
+        COMMAND ${CMAKE_COMMAND} -E env python3 ${CMAKE_CURRENT_SOURCE_DIR}/fix_compile_commands.py
🧹 Nitpick comments (3)
resources/fix_compile_commands/fix_compile_commands.py (2)

15-15: Fix unused variable in directory traversal.

The dirs variable from os.walk() is not used within the loop body.

Apply this diff to rename the unused variable:

-    for root, dirs, files in os.walk(start_dir):
+    for root, _dirs, files in os.walk(start_dir):
🧰 Tools
🪛 Ruff (0.11.9)

15-15: Loop control variable dirs not used within loop body

Rename unused dirs to _dirs

(B007)


32-32: Improve build directory location logic.

The script assumes the build directory is relative to the script location, which may not always be correct in different project structures.

Consider making the build directory configurable:

+import sys
+
 def main():
-    build_dir = os.path.join(os.path.dirname(__file__), "build")
+    build_dir = sys.argv[1] if len(sys.argv) > 1 else os.path.join(os.path.dirname(__file__), "build")
docs/en/additionalfeatures/clangd_cdt_support.rst (1)

48-81: Enhance the troubleshooting section with additional context.

The section effectively addresses the core issue but could benefit from explaining why these flags cause problems and when users might encounter this issue.

Consider adding this explanatory text after line 60:

+The root cause of these errors is that clangd (LLVM-based language server) doesn't recognize certain GCC-specific compiler flags like ``-fno-tree-switch-conversion``, ``-fno-shrink-wrap``, and ``-fstrict-volatile-bitfields``. These flags are automatically added by ESP-IDF's build system but are not understood by clangd's parser.
+
 Please follow the steps below to fix it:
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 70a0ae5 and 478a407.

📒 Files selected for processing (3)
  • docs/en/additionalfeatures/clangd_cdt_support.rst (2 hunks)
  • resources/fix_compile_commands/CMakeLists.txt (1 hunks)
  • resources/fix_compile_commands/fix_compile_commands.py (1 hunks)
🧰 Additional context used
🪛 Ruff (0.11.9)
resources/fix_compile_commands/fix_compile_commands.py

15-15: Loop control variable dirs not used within loop body

Rename unused dirs to _dirs

(B007)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build_macos


1. Download the script for `fix_compile_commands.py <https://github.com/espressif/idf-eclipse-plugin/tree/master/resources/resources/fix_compile_commands/fix_compile_commands.py>`_.

2. Invoke the script from the project post build step. Here is example for `CMakeLists.txt <https://github.com/espressif/idf-eclipse-plugin/blob/master/resources/resources/fix_compile_commands/CMakeLists.txt>`_:
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix broken link path to the CMakeLists.txt file.

Similar to the Python script link, this also contains a duplicate /resources/ segment.

Apply this diff to fix the link:

-2. Invoke the script from the project post build step. Here is example for `CMakeLists.txt <https://github.com/espressif/idf-eclipse-plugin/blob/master/resources/resources/fix_compile_commands/CMakeLists.txt>`_:
+2. Invoke the script from the project post build step. Here is example for `CMakeLists.txt <https://github.com/espressif/idf-eclipse-plugin/blob/master/resources/fix_compile_commands/CMakeLists.txt>`_:
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
2. Invoke the script from the project post build step. Here is example for `CMakeLists.txt <https://github.com/espressif/idf-eclipse-plugin/blob/master/resources/resources/fix_compile_commands/CMakeLists.txt>`_:
2. Invoke the script from the project post build step. Here is example for `CMakeLists.txt <https://github.com/espressif/idf-eclipse-plugin/blob/master/resources/fix_compile_commands/CMakeLists.txt>`_:
🤖 Prompt for AI Agents
In docs/en/additionalfeatures/clangd_cdt_support.rst at line 64, the link to the
CMakeLists.txt file contains a duplicated /resources/ segment in its path. Fix
this by correcting the URL to remove the extra /resources/ so it matches the
correct path structure, similar to the Python script link.

Comment on lines +68 to +76
if(EXISTS "${CMAKE_SOURCE_DIR}/fix_compile_commands.py")
add_custom_target(
fix_clangd ALL
COMMAND ${CMAKE_COMMAND} -E echo "Running fix_compile_commands.py..."
COMMAND ${CMAKE_COMMAND} -E env python3 ${CMAKE_SOURCE_DIR}/fix_compile_commands.py
COMMENT "Cleaning compile_commands.json for clangd"
VERBATIM
)
endif()
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Update CMake example to match the corrected implementation.

The documentation should reflect the fixes needed in the actual CMakeLists.txt file to ensure users get working code.

Apply this diff to show the corrected CMake code:

-     if(EXISTS "${CMAKE_SOURCE_DIR}/fix_compile_commands.py")
+     if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/fix_compile_commands.py")
        add_custom_target(
            fix_clangd ALL
            COMMAND ${CMAKE_COMMAND} -E echo "Running fix_compile_commands.py..."
-           COMMAND ${CMAKE_COMMAND} -E env python3 ${CMAKE_SOURCE_DIR}/fix_compile_commands.py
+           COMMAND ${CMAKE_COMMAND} -E env python3 ${CMAKE_CURRENT_SOURCE_DIR}/fix_compile_commands.py
            COMMENT "Cleaning compile_commands.json for clangd"
            VERBATIM
+           DEPENDS ${CMAKE_PROJECT_NAME}.elf
        )
      endif()
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if(EXISTS "${CMAKE_SOURCE_DIR}/fix_compile_commands.py")
add_custom_target(
fix_clangd ALL
COMMAND ${CMAKE_COMMAND} -E echo "Running fix_compile_commands.py..."
COMMAND ${CMAKE_COMMAND} -E env python3 ${CMAKE_SOURCE_DIR}/fix_compile_commands.py
COMMENT "Cleaning compile_commands.json for clangd"
VERBATIM
)
endif()
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/fix_compile_commands.py")
add_custom_target(
fix_clangd ALL
COMMAND ${CMAKE_COMMAND} -E echo "Running fix_compile_commands.py..."
COMMAND ${CMAKE_COMMAND} -E env python3 ${CMAKE_CURRENT_SOURCE_DIR}/fix_compile_commands.py
COMMENT "Cleaning compile_commands.json for clangd"
VERBATIM
DEPENDS ${CMAKE_PROJECT_NAME}.elf
)
endif()
🤖 Prompt for AI Agents
In docs/en/additionalfeatures/clangd_cdt_support.rst around lines 68 to 76,
update the CMake example to match the corrected implementation by replacing the
existing snippet with the provided diff. This involves ensuring the
add_custom_target named fix_clangd runs the fix_compile_commands.py script
correctly with proper commands and comments, reflecting the actual fixed
CMakeLists.txt usage for users.

Please follow the steps below to fix it:

1. Download the script for `fix_compile_commands.py <https://github.com/espressif/idf-eclipse-plugin/tree/master/resources/resources/fix_compile_commands/fix_compile_commands.py>`_.
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix broken link path to the Python script.

The link contains a duplicate /resources/ segment in the path, making it incorrect.

Apply this diff to fix the link:

-1. Download the script for `fix_compile_commands.py <https://github.com/espressif/idf-eclipse-plugin/tree/master/resources/resources/fix_compile_commands/fix_compile_commands.py>`_.
+1. Download the script for `fix_compile_commands.py <https://github.com/espressif/idf-eclipse-plugin/tree/master/resources/fix_compile_commands/fix_compile_commands.py>`_.
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
1. Download the script for `fix_compile_commands.py <https://github.com/espressif/idf-eclipse-plugin/tree/master/resources/resources/fix_compile_commands/fix_compile_commands.py>`_.
1. Download the script for `fix_compile_commands.py <https://github.com/espressif/idf-eclipse-plugin/tree/master/resources/fix_compile_commands/fix_compile_commands.py>`_.
🤖 Prompt for AI Agents
In docs/en/additionalfeatures/clangd_cdt_support.rst at line 62, the hyperlink
to the Python script fix_compile_commands.py contains a duplicated /resources/
segment in the URL path. Correct the link by removing the extra /resources/ so
that the URL points to
https://github.com/espressif/idf-eclipse-plugin/tree/master/resources/fix_compile_commands/fix_compile_commands.py,
ensuring the link is valid and directs to the intended script.

@kolipakakondal kolipakakondal added this to the v3.5.0 milestone Jun 10, 2025
@kolipakakondal kolipakakondal merged commit 0d94c4b into master Jun 10, 2025
5 of 6 checks passed
@kolipakakondal kolipakakondal deleted the IEP-1550 branch June 10, 2025 08:09
@alirana01
Copy link
Collaborator

alirana01 commented Jun 11, 2025

@kolipakakondal @AndriiFilippov found some issues related to clangd syntax highlighting from this PR's builds after merge to the master. Can it be something related to the added CMake file or python script.

@AndriiFilippov please share your original bug and findings here. Although this is not directly impacting but it might help you in fixing the issue

@kolipakakondal
Copy link
Collaborator Author

Hi @alirana01 The script was only for documentation purposes and wasn’t called anywhere from the code. We can suggest this approach to users who has errors when they navigate the esp-idf source files — it won’t have any impact on the build as such.

@kolipakakondal
Copy link
Collaborator Author

As mentioned in the PR description, here is the plan

This PR includes the script and the steps required to use it, so we can recommend it to users. Going forward, we can consider implementing it by default as part of project creation, along with updating the CMakeLists.txt.

@alirana01
Copy link
Collaborator

Hi @alirana01 The script was only for documentation purposes and wasn’t called anywhere from the code. We can suggest this approach to users who has errors when they navigate the esp-idf source files — it won’t have any impact on the build as such.

Yes sorry I just saw it now

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.

3 participants