DEV Community

Cover image for The KingCobra REPL: a tour, from calculator to scratchpad
Divyanshu Sinha
Divyanshu Sinha

Posted on

The KingCobra REPL: a tour, from calculator to scratchpad

The fastest way to learn a language is to type at it. KingCobra's REPL is a read-eval-print loop that keeps your definitions, type-checks every line, and never dies on an error. This is a tour of what it does. Every transcript below was run on KingCobra 1.0.0.

Start it

kingcobra repl              # start a session
kingcobra                   # no arguments in a terminal also starts it
kingcobra repl file.kc      # run file.kc into the session first, then prompt
kingcobra -i file.kc        # same thing
kingcobra --no-typecheck repl   # start with the static type checker off
Enter fullscreen mode Exit fullscreen mode

Leave with Ctrl-D, or with exit, quit or :quit. Inside the REPL, :help lists every command.

Tip for Windows: if the banner shows garbled characters in cmd.exe, run chcp 65001 first or use Windows Terminal, which uses UTF-8 by default.

The basics

Type an expression and its value is echoed. Strings are shown quoted, and assignments and null results print nothing:

>>> 1 + 2
3
>>> "hi" + " there"
"hi there"
>>> let xs = [1, "a", 2.5]
>>> xs
[1, "a", 2.5]
>>> _
[1, "a", 2.5]
Enter fullscreen mode Exit fullscreen mode
  • _ is the value of the last expression that was echoed.
  • The trailing ; is optional for a single statement. count = 5 and count = 5; are the same. Several statements on one line still need separators: let a = 1; let b = 2;.
  • Assignment needs a declaration first. x = 5 on a name you never declared is an error, so use var x = 5 and then x = 6.

Definitions persist

let, var, fn, struct, extern and import all land in one global scope that lives for the whole session. Redefining a name, even a function or a struct, replaces it:

>>> fn sq(n: int) -> int { return n * n; }
>>> sq(12)
144
>>> fn sq(n: int) -> int { return n * n * n; }
>>> sq(3)
27
>>> struct P { x: int, y: int }
>>> let p = P { x: 1, y: 2 }
>>> p
P { x: 1, y: 2 }
Enter fullscreen mode Exit fullscreen mode

Multi-line input

If a (, [, {, string or /* */ comment is still open, the prompt changes to ... and input continues until it balances. It also keeps reading when a statement is obviously unfinished: a try waits for its catch, and an input that ends in an operator (1 +, a &&) waits for its operand.

>>> fn fact(n: int) -> int {
...     if (n < 2) { return 1; }
...     return n * fact(n - 1);
... }
>>> fact(10)
3628800
>>> try {
...     print([1, 2, 3][9]);
... } catch (e) {
...     print("caught:", e.message);
... }
caught: index 9 out of bounds (len 3)
Enter fullscreen mode Exit fullscreen mode

Pasting a block? Use :paste, enter the lines, and finish with :end or Ctrl-D. Ctrl-C abandons the input you were typing.

Every line is type-checked

The static type checker runs on each input against everything declared so far in the session. A rejected input leaves no trace:

>>> fn sq(n: int) -> int { return n * n; }
>>> sq("oops")
<repl:2>:1:4: error: 'sq' argument 1: expected int, got string
    1 | sq("oops")
      |    ^
Enter fullscreen mode Exit fullscreen mode

Turn the checker off with :typecheck off (and back on with :typecheck on), or start with --no-typecheck.

Errors never end the session

Parse errors, type errors and runtime errors, including ones raised inside std.* modules, print a normal diagnostic and return you to the prompt. The label <repl:N> numbers your inputs, and you get the source line and a caret, even for a function defined many inputs ago:

>>> [1, 2, 3][10]
<repl:3>:1:8: error: index 10 out of bounds (len 3)
    1 | [1,2,3][10]
      |        ^
>>> let ok = 41 + 1
>>> ok
42
Enter fullscreen mode Exit fullscreen mode

Runaway recursion is reported instead of crashing:

>>> fn r(n: int) -> int { return r(n + 1) + 1; }
>>> r(0)
error: stack overflow (recursion too deep)
>>> 1 + 1
2
Enter fullscreen mode Exit fullscreen mode

Look around: variables, types and signatures

>>> var count = 15
>>> let name = "Ada"
>>> :vars
  sq               fn         (n)
  count            int        15
  name             string     "Ada"
>>> :type 3.5
float
>>> :type [1, 2]
array
>>> :info sq
fn sq(n: int) -> int
>>> :info P
struct P { x: int, y: int }
>>> import std.json;
>>> :info json
module json: parse try_parse is_valid error parse_file stringify pretty minify ...
Enter fullscreen mode Exit fullscreen mode

:info is the quickest way to see what a module offers, with no documentation lookup, and :del name forgets a variable or function.

Help without leaving

help(...), ?name and :help name show the language's own documentation for builtins, keywords, methods and modules. A /// doc comment typed at the prompt waits for the declaration after it, so your own functions get documented too:

>>> ?len
len(x) -> int  —  core
    Length of a string (in BYTES), array, buffer or object. Arrays also have
    the property a.len.
>>> /// Add two numbers.
>>> fn add(a: int, b: int) -> int { return a + b; }
>>> help(add)
fn add(a: int, b: int) -> int

    Add two numbers.

    defined at <repl:1>:2
Enter fullscreen mode Exit fullscreen mode

History, redo and saving your work

The REPL numbers the inputs that ran. :redo n runs one again, and :save writes the whole session to a file, so something you explored can become a real program:

>>> let a = 10
>>> let b = 20
>>> a * b
200
>>> :history
   1  let a = 10
   2  let b = 20
   3  a * b
>>> :redo 2
let b = 20
>>> :save session.kc
saved 4 input(s) to session.kc
Enter fullscreen mode Exit fullscreen mode

To bring code in, :load file.kc runs a file into the session (main() is not called), :reload runs the last :load again, and :reset throws everything away and starts fresh.

>>> :load lib.kc
>>> greet("REPL")
"Hello, REPL!"
>>> :reset
session reset
Enter fullscreen mode Exit fullscreen mode

Timing and memory

:time runs one input and reports how long it took. :timing on times every input. Your number will differ:

>>> fn fib(n: int) -> int { if (n < 2) { return n; } return fib(n - 1) + fib(n - 2); }
>>> :time fib(25)
75025
(986.7 us)
Enter fullscreen mode Exit fullscreen mode

Memory is explicit in a session, just like in a program. free(x) works on strings, arrays, structs and alloc() blocks, echoing a freed value is a recoverable use-after-free error, and :mem prints the live allocations:

>>> let s = "id-" + 42
>>> free(s)
>>> s
<repl>:1:1: error: use after free (this string was freed)
>>> :vars
  s                string     <freed string>
Enter fullscreen mode Exit fullscreen mode

The preprocessor works here too

>>> #define SQ(x) ((x)*(x))
>>> SQ(7)
49
Enter fullscreen mode Exit fullscreen mode

Macros persist for the session, :macros lists them and #undef removes one.

Display options

Long arrays, structs and objects wrap one element or field per line. Set the width with :set width n (default 80, minimum 20). On a terminal, values are coloured; :color off or the NO_COLOR=1 environment variable turns that off:

>>> let v = [100000, 200000, 300000, 400000]
>>> v
[100000, 200000, 300000, 400000]
>>> :set width 20
width is 20
>>> v
[
  100000,
  200000,
  300000,
  400000
]
Enter fullscreen mode Exit fullscreen mode

Line editing, history and Tab completion

If GNU readline is installed (libreadline-dev on Debian and Ubuntu, readline-devel on Fedora), the build detects it and you get arrow keys, Emacs and vi editing, and a history file in ~/.kingcobra_history that keeps the last 1,000 lines. Tab completes keywords, REPL commands, macros, and every name you've defined. After a dot it completes members, so system.<Tab> lists the module's functions and p.<Tab> lists a struct's fields. After :load or :save it completes file names. Without readline the REPL still works with plain line input.

A startup file

On a terminal, the REPL loads ~/.kingcobrarc if it exists, which is a good place for imports and helpers you always want. The environment variable KC_REPL_INIT names a file to load in any mode:

echo 'let motd = "welcome back";' > init.kc
echo 'motd' | KC_REPL_INIT=init.kc kingcobra repl
Enter fullscreen mode Exit fullscreen mode
"welcome back"
Enter fullscreen mode Exit fullscreen mode

A ./.kingcobrarc in the current directory is deliberately not run, so opening a project folder can't execute code on its own.

Use it from scripts

When stdin isn't a terminal, there is no banner and no prompt, but values are still echoed. That makes the REPL handy for one-line checks:

echo '2 * 10 == 20' | kingcobra repl
Enter fullscreen mode Exit fullscreen mode
true
Enter fullscreen mode Exit fullscreen mode
printf 'fn sq(n: int) -> int { return n*n; }\nsq(12)\n' | kingcobra repl
Enter fullscreen mode Exit fullscreen mode
144
Enter fullscreen mode Exit fullscreen mode

The exit status is 1 if any input failed and 0 otherwise.

Three ways I use it

  1. Explore a module. import std.json; then :info json shows every function, and ?name documents one.
  2. Try before you write. Test an expression, a string method or a regex in the REPL, then :save the good lines.
  3. Poke at your own code. kingcobra repl myprog.kc loads a file into the session, so you can call its functions with different arguments.

Limits worth knowing

  • Memory grows slowly. Parsed code is never freed, because closures defined in the session point into it, and :reset doesn't release it either. That's fine for interactive use, but it's not meant for a REPL embedded in a long-running server.
  • A recovered error skips pending defer statements. Put any cleanup you need on every path in code that can't raise an error, or free explicitly.
  • Ctrl-C and stack-overflow recovery are POSIX-only. On Windows, Ctrl-C ends the process, and runaway recursion is stopped by the 4,000-call depth limit instead.
  • After an interrupt inside heavy native code (for example std.http or std.nn training), treat the session as disposable.
  • A script can catch a stack overflow with try; the REPL just returns you to the prompt.
  • An if waits for one more line on a terminal, to catch an else. Press Enter to run it.
  • import "file.kc" in the REPL resolves relative to the current directory.

Try it

kingcobra repl
Enter fullscreen mode Exit fullscreen mode

If a REPL behaviour surprises you, open an issue. A star on the repo helps other people find it.

Top comments (0)