loading...

Debug Crystal in VSCode via CodeLLDB

bcardiff profile image Brian J. Cardiff ・2 min read

This post mentions features that will be released in 0.35.0, or that will require you to compile Crystal master branch ;-)

Crystal uses LLVM under the hood. To allow a more comfortable debugging experience it is required to instruct lldb how to understand the values stored in memory. Recently this story got a lot of effort and it finally got merged. You can read more at #8538.

Let me share with you the configurations that will let you use the CodeLLDB
extension to debug Crystal programs.

Create a task that will compile the current file and leave it in bin/ folder. In your project’s .vscode/tasks.json add:

{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "crystal: build current file (debug)",
      "type": "shell",
      "command": "crystal build --debug ${relativeFile} -o bin/${fileBasenameNoExtension}"
    }
  ]
}

You might need to set the Crystal binary path in "command" field depending on your environment.

Check you have the CodeLLDB extension installed.

Create a launch configuration that will run the previous task and start debugging the binary left in bin/. It will also set up lldb with the appropriate formatters. In your project’s .vscode/launch.json add:

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "lldb",
      "request": "launch",
      "name": "crystal: debug current file",
      "preLaunchTask": "crystal: build current file (debug)",
      "program": "${workspaceFolder}/bin/${fileBasenameNoExtension}",
      "args": [],
      "cwd": "${workspaceFolder}",
      "initCommands": [
        "command script import /path/to/crystal/etc/lldb/crystal_formatters.py"
      ]
    }
  ]
}

You will need to set the crystal_formatters.py path in "initCommands" field accordingly to your environment. The file is located in the compiler’s repo at etc/lldb/crystal_formatters.py

You are all set, have fun!

GIF Video debugging a hello world program

Keep in mind we are still in the early days for these improvements. Debug information metadata and more formatters are still pending. But the recent effort to improve their current state sets the scaffolding to move steadily forward.

Happy Crystalling!

Posted on Apr 17 by:

bcardiff profile

Brian J. Cardiff

@bcardiff

In the CS fields I am interested in programming languages, UX, Visualizations & AI. I've spent more than 10 years teaching CS.I love to social dance to swing & blues music.

Discussion

markdown guide