Debugging scripts

Introduction

When a script gives the wrong answer, echo will often tell you why. When it doesn’t, the debugger lets you watch the script run. You pause it on a line, move through it one statement at a time, and see the value of every variable as it changes. Nothing needs to be added to the script, and nothing needs to be installed: the KScript extension for VS Code and kscript itself have everything.

Here is a script that totals a basket:

// basket.kscript
fn line_total(price: number, quantity: int) {
  $total = $price * $quantity
  return $total
}

$prices = [2.5, 4, 1.25]
$quantities = [2, 1, 4]
$basket_total = 0
for price at index in $prices {
  $basket_total += @line_total($price, quantity: $quantities[$index])
}
echo "Basket: {$basket_total}"

Click in the margin to the left of line 11 to put a breakpoint (a red dot) there, then press F5. The script runs until it reaches line 11 and pauses there. The Variables view now shows $price = 2.5, $index = 0 and $basket_total = 0. Press F11 to step into line_total(): the Call Stack shows line_total() on top of basket.kscript, and Locals shows $price = 2.5 and $quantity = 2. Press F10 and $total = 5 appears, because the line that sets it has now run.

Starting the debugger

In VS Code, you may start the debugger in three ways. Each one saves the script first, so the breakpoints sit on the lines you see:

  • Press F5 with a script open.
  • Click Debug above the script’s first line, next to Run.
  • Choose Debug Script from the run button’s menu at the top right of the editor, or from the Command Palette.

The script’s output goes to the Debug Console, a line at a time, as it would to the terminal. When the script ends, the debugger stops by itself. Pressing Shift+F5 stops it early: the script ends where it is, and runs nothing more.

The debugger runs scripts. A test file (*.test.kscript) runs with Run Tests instead, which shows each test’s result in the Testing view.

Breakpoints

A breakpoint pauses the script just before its line runs. Click in the margin next to a line number to add one, and click the red dot again to remove it. F9 does the same on the line the cursor is on.

A breakpoint on a line with no statement, such as a blank line, a comment or a closing }, moves down to the next line that has one. The script would never stop on the line you picked, so VS Code shows the dot where it will stop.

When a statement and its body share a line, the line is one stop. Here the debugger pauses on line 2 once, not again for the echo inside it:

$ready = true
if $ready { echo 'ready to go' }
echo 'done'

Conditional breakpoints

A breakpoint inside a loop pauses on every pass. To pause only on the pass you care about, right-click the red dot, choose Edit Breakpoint, and give it a condition. The condition is any KScript expression, worked out each time the line is reached with the variables the line sees:

// orders.kscript
$orders = [
  { id: 101, total: 25 },
  { id: 102, total: 0 },
  { id: 103, total: 40 },
]
for order in $orders {
  // A breakpoint here with the condition $order.total == 0 pauses on order 102 only.
  echo "Order {$order.id}: {$order.total}"
}

A condition that has a mistake in it, such as a variable the line can’t see, pauses the script, so you can see what went wrong rather than miss the stop.

Hit counts

A hit count pauses the script when the line has been reached a number of times. Choose Hit Count in the same box. 3 (or >= 3) pauses on the third time and every time after it, == 3 pauses on the third time only, > 3 from the fourth time on, and % 3 on every third time. A breakpoint with a condition and a hit count counts only the times its condition holds.

Log points

A log point writes a message to the Debug Console instead of pausing. It is an echo you don’t have to add to the script, and remove again afterwards. Right-click in the margin, choose Add Logpoint, and write the message. Each {expression} in it is filled in, as in a double-quoted string:

// stock.kscript
$stock = { apples: 12, pears: 0, plums: 5 }
for item, count in $stock {
  // A log point here with the message "checking {$item}: {$count} left" writes
  // checking apples: 12 left, checking pears: 0 left and checking plums: 5 left.
  if $count == 0 => echo "{$item} sold out"
}

Stepping through a script

While the script is paused, the buttons at the top of the editor (and their keys) move it on:

Button Key What it does
Continue F5 Runs until the next breakpoint, or the end.
Step Over F10 Runs the line and pauses on the next one. A function the line calls runs whole.
Step Into F11 Pauses on the first line inside the function the line calls. On a line with no call, the same as Step Over.
Step Out Shift+F11 Runs the rest of the function and pauses on the line after the call.
Pause F6 Pauses a running script wherever it has got to, such as in a loop that never ends.

Take this script, paused on line 6:

fn greeting(name: string) {
  $message = "Hello, {$name}!"
  return $message
}

$text = @greeting('Ada')
echo $text

Step Into pauses on line 2, inside greeting(), where Locals shows $name = 'Ada'. Step Over runs line 2 and pauses on line 3, where $message = 'Hello, Ada!' has appeared. Step Out runs the return and pauses on line 7, back at the top level, where Globals shows $text = 'Hello, Ada!'.

Stepping into a block function, such as the one ->map() calls, works the same way. It gets its own place on the Call Stack, named fn():

$prices = [3, 8]
$with_tax = $prices->map(fn(price) {
  // Paused here, Locals shows $price = 3 the first time and $price = 8 the second.
  $taxed = $price * 1.2
  return $taxed
})
echo $with_tax

A one-line function written with =>, such as fn(price) => $price * 1.2, has no lines of its own to pause on, so stepping runs it whole.

The Variables view

When the script pauses, the Variables view shows what each variable holds at that moment. They are split into scopes:

  • Locals: the variables of the function the script is paused in: its parameters and what it sets. Inside a loop, the loop’s own variables (such as $price and $index) are here too, even at the script’s top level. Outside any function or loop there are no Locals.
  • Globals: the variables the script sets at its top level. Functions and types aren’t listed, since they don’t change.
  • Built-in: what the script’s packages give every script, such as $args. It is left out when there is nothing in it.

Text is shown in quotes, so '7' is text and 7 is a number. The type is shown when you hover over a value. A list, a map or a record opens with the arrow next to it, so you may look inside it. A record shows its type’s name:

type Point {
  x: int
  y: int
}

$corner = Point(x: 3, y: 4)
$tags = ['red', 'blue']
$sizes = { small: 1, large: 9 }
// Paused here, Globals shows
//   $corner = Point { x: 3, y: 4 }
//   $tags = ['red', 'blue']
//   $sizes = { small: 1, large: 9 }
// and opening $tags shows [0] = 'red' and [1] = 'blue'.
echo 'done'

Click a different line in the Call Stack to see the variables of a function further up: the Variables view, the Debug Console and hovers all follow the line you pick.

Hovers, watches and the Debug Console

While the script is paused, hover over a variable in the editor to see its value. The Watch view keeps an expression’s value in sight as you step, such as $basket_total or $prices->count(). The Debug Console works out any expression you type, using the variables of the paused line:

> $prices->sum()
7.75
> $quantities[2] * 2
8

An expression may call functions and methods, so the debug console can try a fix before you write it into the script. Be careful with functions that change things, such as writing a file: they really run.

Pausing on errors

When a script throws an error, the debugger pauses where it was thrown, before anything catches it, with every function the error came through still on the Call Stack. The message shows in the editor, under the line, and the Variables view shows what each variable held when it went wrong:

fn share(total: number, people: int) {
  if $people == 0 {
    throw Validation "There is nobody to share {$total} between."
  }
  return $total / $people
}

$each = @share(30, people: 0)
echo $each

Here the debugger pauses on line 3, inside share(), where Locals shows $people = 0. Continue lets the error go on: a catch that handles it runs as usual, and an error nothing catches ends the script, with its message in the Debug Console.

A script that throws and catches errors on purpose pauses each time. Untick Errors in the Breakpoints view to stop pausing on them.

launch.json

F5 with no launch.json debugs the script that is open. To give the script arguments, or always debug the same script, add a launch.json: open the Run and Debug view, click create a launch.json file and choose KScript. You may add as many configurations as you like:

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "kscript",
      "request": "launch",
      "name": "Debug script",
      "program": "${file}"
    },
    {
      "type": "kscript",
      "request": "launch",
      "name": "Import this week's orders",
      "program": "${workspaceFolder}/main.kscript",
      "args": ["--week", "48"],
      "environment": "staging",
      "stopOnEntry": true
    }
  ]
}

A configuration may have:

Setting What it does
program The script to debug. ${file} is the one open in the editor.
args The script’s $args, as after kscript run script.kscript.
cwd The folder the script runs in. The script’s own folder when it is left out.
env Environment variables to set for the script, such as { "API_URL": "http://localhost:8080" }.
environment The environment for $config, as kscript --env staging picks it.
stopOnEntry true pauses before the script’s first statement, without a breakpoint.

The script runs with its project’s packages and config, from the nearest kscript.json, as kscript run runs it.

Debugging in the terminal

You don’t need an editor to debug a script. kscript --debug runs it in the terminal and pauses before its first statement. It shows where it is, with the lines around it, and waits for a command:

$ kscript --debug basket.kscript

Paused before the first line in basket.kscript:7
  5 │ }
  6 │
→ 7 │ $prices = [2.5, 4, 1.25]
  8 │ $quantities = [2, 1, 4]
  9 │ $basket_total = 0
  Type h for the commands, n to run a line.
debug>

--debug goes before the script’s name, as kscript run --debug basket.kscript or just kscript --debug basket.kscript, because what follows the name is the script’s $args. kscript run --debug on its own debugs the project’s main script.

To pause further on instead, give --break with a line number. The script runs until it reaches that line. Give --break once for each line, and write file:line for a line in another script, such as one the script imports:

$ kscript --break 11 --break lib/prices.kscript:4 basket.kscript

These are the commands. Each has a one-letter short form:

Command What it does
n, next Runs the line and pauses on the next one. A function the line calls runs whole. Enter on its own repeats the last step.
s, step Pauses on the first line inside the function the line calls. On a line with no call, the same as n.
o, out Runs the rest of the function and pauses on the line after the call.
c, continue Runs until the next breakpoint, or the end.
p, print Prints a variable or works out an expression with the paused line’s variables: p $basket_total, p $prices->sum().
v, vars Lists the variables the line sees: Locals, then Globals.
w, where Shows the call stack: each function the script is inside, innermost first.
l, list Shows the lines around the paused line again.
b, break b 12 adds a breakpoint at line 12 (or b lib/prices.kscript:4). On its own, lists them.
d, delete d 12 removes the breakpoint at line 12.
q, quit Stops the script where it is. Nothing more runs.
h, help Lists the commands.

Here is the basket script, run with --break 11, stepping into line_total() and printing what it worked out:

Paused at a breakpoint in basket.kscript:11
   9 │ $basket_total = 0
  10 │ for price at index in $prices {
→ 11 │   $basket_total += @line_total($price, quantity: $quantities[$index])
  12 │ }
  13 │ echo "Basket: {$basket_total}"
debug> s

Paused in line_total(), basket.kscript:3
  1 │ // basket.kscript
  2 │ fn line_total(price: number, quantity: int) {
→ 3 │   $total = $price * $quantity
  4 │   return $total
  5 │ }
debug> n

Paused in line_total(), basket.kscript:4
debug> p $total
5  number
debug> w
→ line_total(), basket.kscript:4
  basket.kscript:11

A breakpoint on a blank line or a comment moves down to the next statement, as in the editor. An error pauses the script where it is thrown, with its message, so you can print the variables that led to it. The script’s own output prints in the terminal between the stops. Since the terminal’s input is for the debugger’s commands, the script reads none: @ask() gets nothing back.

To see the .NET exception and stack trace behind an error, which --debug showed before it ran the debugger, use --stack-trace.

Other editors

The debugger is kscript debug, which speaks the Debug Adapter Protocol on its stdin and stdout. VS Code starts it for you. Any editor with a Debug Adapter Protocol client may start it too, such as Neovim with nvim-dap:

local dap = require('dap')
dap.adapters.kscript = { type = 'executable', command = 'kscript', args = { 'debug' } }
dap.configurations.kscript = {
  { type = 'kscript', request = 'launch', name = 'Debug script', program = '${file}' },
}

It takes the launch settings above, and supports breakpoints with conditions, hit counts and log messages, the Errors filter, stepping, pausing, and evaluating expressions for hovers, watches and the console.

What the debugger doesn’t do yet

  • Test files run with Run Tests (or kscript test), not the debugger.
  • A script reads no input while it is debugged: @ask() and the like get nothing back, as when input comes from a file that is empty.
  • Functions started with spawn run without pausing. Only the script’s own thread stops at breakpoints.
  • Values can be looked at, not changed: the Variables view doesn’t edit them, and the Debug Console works out expressions rather than running statements such as $count = 5.

Edit this page on GitHub