Comment by shawn

Comment by shawn

Right! I've been waiting a couple years for Lumen to get some traction. cracks knuckles

Before I blather on about why it's worth paying attention to, why don't I just show you an implementation of the classic Trusting Trust paper:

https://www.archive.ece.cmu.edu/~ganger/712.fall02/papers/p7...

We'll implement this ourselves. Let's dive right in. Start off by cloning Lumen.

  $ git clone https://github.com/sctb/lumen
  $ cd lumen
  $ git checkout aedf2fd2c209bfc7926e0d4eae4becd8a647fb80
  $ vim main.l
(Commit aedf2fd is just the latest commit at the time of this writing. I make it explicit here so that anyone can follow along in the future.)

Now that main.l is open, we begin by defining a global function `read-file` that simply returns a file as a string:

  (define-global read-file (path)
    ((get system 'read-file) path))
If you run `make && bin/lumen`, you'll see the function is now defined when Lumen starts:

  > read-file
  function

  > (read-file "README.md")
  "Lumen\n=\nLumen is a very small, self-hosted Lisp for Lua and JavaScript. It provides a flexible compilation environment with an extensible reader, macros, and extensible special forms, but otherwise attempts..."
Now we define `read-from-file`, which reads Lumen source code and returns it as a form that can be evaluated:

  (define-global read-from-file (path)
    (let (s ((get reader 'stream) (read-file path))
          body ((get reader 'read-all) s))
      `(do ,@body)))

  > (read-from-file "reader.l")
  ("do" ("define" "delimiters" ("set-of" "\"(\"" "\")\"" "\";\"" "\"\\r\"" "\"\\n\"")) ...
Those are the forms defined in reader.l: https://github.com/sctb/lumen/blob/aedf2fd2c209bfc7926e0d4ea...

Let's step through the forms and print them.

  > (step x (read-from-file "reader.l")
      (print (str x)))
  "do"
  ("define" "delimiters" ("set-of" "\"(\"" "\")\"" "\";\"" "\"\\r\"" "\"\\n\""))
  ("define" "whitespace" ("set-of" "\" \"" "\"\\t\"" "\"\\r\"" "\"\\n\""))
  ("define" "stream" ("str" "more") ("obj" more: "more" pos: 0 len: ("#" "str") string: "str"))
  ("define" "peek-char" ("s") ("let" ((pos: true len: true string: true) "s") ("when" ("<" "pos" "len") ("char" "string" "pos"))))
  ("define" "read-char" ("s") ("let" "c" ("peek-char" "s") ("if" "c" ("do" ("inc" ("get" "s" ("quote" "pos"))) "c"))))
  ...
Pretty good! We're already doing some basic compiler-type stuff. That's Lumen's power: It's a flexible compiler. (IMO one of the finest in the world due to its simplicity.)

Now, what can we do with these forms? Well, we can expand them:

  > (step x (expand (read-from-file "reader.l"))
      (print (str x)))
  "do"
  ("%local" "delimiters" ("%object" "\"(\"" true "\")\"" true "\";\"" true "\"\\n\"" true "\"\\r\"" true))
  ("%local" "whitespace" ("%object" "\"\\r\"" true "\" \"" true "\"\\n\"" true "\"\\t\"" true))
  ("%local-function" "stream" ("str" "more") ("return" ("%object" "\"more\"" "more" "\"pos\"" 0 "\"len\"" ("#" "str") "\"string\"" "str")))
  ("%local-function" "peek-char" ("s") ("do" ("%local" "____id" "s") ("%local" "__pos" ("get" "____id" "\"pos\""))
  ...
We can compile them:

  > (print (compile (expand (read-from-file "reader.l"))))
  local delimiters = {["("] = true, [")"] = true, [";"] = true, ["\n"] = true, ["\r"] = true}
  local whitespace = {["\r"] = true, [" "] = true, ["\n"] = true, ["\t"] = true}
  local function stream(str, more)
    return {more = more, pos = 0, len = _35(str), string = str}
  end
  local function peek_char(s)
    local ____id9 = s
    local __pos6 = ____id9.pos
    local __len3 = ____id9.len
    local __string3 = ____id9.string
    if __pos6 < __len3 then
      return char(__string3, __pos6)
    end
  end
  local function read_char(s)
    local __c21 = peek_char(s)
    if __c21 then
      s.pos = s.pos + 1
      return __c21
    end
  end
  ...
And we can switch languages:

  > (set target 'js)
  "js"
  > (print (compile (expand (read-from-file "reader.l"))))
  var delimiters = {"(": true, ")": true, ";": true, "\n": true, "\r": true};
  var whitespace = {"\r": true, " ": true, "\n": true, "\t": true};
  var stream = function (str, more) {
    return {more: more, pos: 0, len: _35(str), string: str};
  };
  var peek_char = function (s) {
    var ____id12 = s;
    var __pos8 = ____id12.pos;
    var __len4 = ____id12.len;
    var __string4 = ____id12.string;
    if (__pos8 < __len4) {
      return char(__string4, __pos8);
    }
  };
  var read_char = function (s) {
    var __c28 = peek_char(s);
    if (__c28) {
      s.pos = s.pos + 1;
      return __c28;
    }
  };
  ...
Ok, on to the cool stuff.

Make a file called lumen.l:

  (when-compiling
    `(do ,(read-from-file "runtime.l")
         ,(read-from-file "macros.l")
         ,(read-from-file "main.l")))
English translation: "When compiling, read the forms from runtime.l, macros.l, and main.l, join them together, then compile the result."

Let's compile this file and see what happens:

  $ bin/lumen -c lumen.l
  environment = {{}}
  target = "lua"
  function nil63(x)
    return x == nil
  end
  function is63(x)
    return not nil63(x)
  end
  function no(x)
    return nil63(x) or x == false
  end
  function yes(x)
    return not no(x)
  end
  function either(x, y)
    if is63(x) then
      return x
    else
      return y
    end
  end
  ...
Presto! We get bin/lumen.lua: https://github.com/sctb/lumen/blob/aedf2fd2c209bfc7926e0d4ea...

Why does it generate Lua? Because on my system, Lumen happens to default to running on LuaJIT, and the host language is the default. If Lua wasn't installed on your system, you'd be seeing JS instead.

To get a specific language, pass the `-t` parameter:

  $ bin/lumen -c lumen.l -t js
  environment = [{}];
  target = "js";
  nil63 = function (x) {
    return x === undefined || x === null;
  };
  is63 = function (x) {
    return ! nil63(x);
  };
  no = function (x) {
    return nil63(x) || x === false;
  };
  yes = function (x) {
    return ! no(x);
  };
  either = function (x, y) {
    if (is63(x)) {
      return x;
    } else {
      return y;
    }
  };
  ...
That gives us bin/lumen.js: https://github.com/sctb/lumen/blob/aedf2fd2c209bfc7926e0d4ea...

Let's simplify the makefile. Open makefile in your edior and replace it with this:

  .PHONY: all clean test

  LUMEN_LUA  ?= lua
  LUMEN_NODE ?= node
  LUMEN_HOST ?= $(LUMEN_LUA)

  LUMEN := LUMEN_HOST="$(LUMEN_HOST)" bin/lumen

  MODS := bin/lumen.x	\
    bin/reader.x	\
    bin/compiler.x	\
    bin/system.x

  all: $(MODS:.x=.js) $(MODS:.x=.lua)

  clean:
    @git checkout bin/*.js
    @git checkout bin/*.lua
    @rm -f obj/*

  bin/%.js : %.l
    @echo $@
    @$(LUMEN) -c $< -o $@ -t js

  bin/%.lua : %.l
    @echo $@
    @$(LUMEN) -c $< -o $@ -t lua

  test: all
    @echo js:
    @LUMEN_HOST=$(LUMEN_NODE) ./test.l
    @echo lua:
    @LUMEN_HOST=$(LUMEN_LUA) ./test.l
Try it out:

  $ make -B test
  bin/lumen.js
  bin/reader.js
  bin/compiler.js
  bin/system.js
  bin/lumen.lua
  bin/reader.lua
  bin/compiler.lua
  bin/system.lua
  js:
   647 passed, 0 failed
  lua:
   647 passed, 0 failed
Perfect. Our new lumen.l file fits into the compiler pipeline nicely.

It may not seem like it, but we now have a tool of remarkable power. Let's see why.

Open lumen.l back up. We recall it looks like this:

  (when-compiling
    `(do ,(read-from-file "runtime.l")
         ,(read-from-file "macros.l")
         ,(read-from-file "main.l")))
Let me show you what makes Lumen special. Change lumen.l to this:

  (define-global %lumen ()
    (when-compiling
      `'(do ,(read-from-file "runtime.l")
            ,(read-from-file "macros.l")
            ,(read-from-file "main.l"))))

  (when-compiling
    `(do ,(read-from-file "runtime.l")
         ,(read-from-file "macros.l")
         ,(read-from-file "main.l")))
then compile:

  $ make
Now change lumen.l to this:

  (define-global %lumen ()
    (when-compiling
      `'(do ,(read-from-file "runtime.l")
            ,(read-from-file "macros.l")
            ,(read-from-file "main.l"))))
    
  (when-compiling
    (%lumen))
and compile again:

  $ make
Here comes the surprise. Change lumen.l to this:

  (define-global %lumen ()
    (when-compiling
      `',(%lumen)))
    
  (when-compiling
    (%lumen))
and compile:

  $ make
Now delete the source code:

  $ rm runtime.l
and compile:

  $ make -B test
  make -B test
  bin/lumen.js
  bin/reader.js
  bin/compiler.js
  bin/system.js
  bin/lumen.lua
  bin/reader.lua
  bin/compiler.lua
  bin/system.lua
  js:
   647 passed, 0 failed
  lua:
   647 passed, 0 failed
What happened to the source code? It's gone!

https://youtu.be/TGwZVGKG30s?t=25

Gone? What do you mean gone? I had perfectly fine source code and you mean to tell me it's gone?!

Not anymore you don't. Poof.

Yet lumen remains:

  $ make test
  js:
   647 passed, 0 failed
  lua:
   647 passed, 0 failed

Last week I was trying to learn R, so I added a target for it: https://github.com/sctb/lumen/pull/193

Now I don't have to write R.

Here's a (now very-outdated) branch that has full support for Python: https://github.com/shawwn/lumen/tree/features/python

Now I don't have to write Python.

This has been a short tour of why Lumen has fascinated me for the last three years, and hope you find its mysteries delightful. It is only through abstraction that we can bend computers to our will, and Lumen is a decisive step forward.

Happy to answer any questions!

Replies shawn · 2018-09-11
Open on HN
Loading the discussion…

Domain filters

Stories from these domains are hidden from every list. Subdomains match too: blocking substack.com also hides danluu.substack.com.

    New collection

    Delete this collection?

    About YAVCHN

    YAVCHN is a reader for Hacker News and Lobsters, with articles and discussions in separate windows or Classic pages.

    Created by Paul Parks and built with PUDL.

    YAVCHN source code on GitHub

    Help

    Keyboard

    j / k
    Move down and up the story list. The arrow keys scroll whatever has focus.
    Enter
    Read the marked story in the article reader.
    ]
    Read the next story in the same article-reader applet. Back returns to the previous story.
    p
    Pin or unpin the marked story, which keeps it in Pinned.
    n / N
    Move to the next or previous top-level comment in the window in front.
    c
    Collapse or expand that comment.
    f
    Hide or show the story list.
    Esc
    Close a menu or this help.
    Access key m
    Go to the menu bar. Most browsers take it with Alt on Windows and Linux, and Safari with Control and Option.
    ?
    Show this help.

    Windows

    Each story opens in a window holding its article above its discussion; drag the bar between them to share the room differently. A window can be moved by its title bar, resized from any edge, snapped to a half or a corner by dragging it there, maximised, or minimised to the bar at the foot of the page. Use Window > New reader window to open an empty reader, or Story > Open in new reader window to open another reader for the current article. Docked readers keep their articles when you select another story from the sidebar. Minimized readers can be restored and reused for their site. A window's Next story link reads on down the list in the same window.

    A link in a comment or an article to another Hacker News or Lobsters thread opens that thread in a window too. A link to a single HN comment opens the comment above its replies.

    While a story's window is in front, the Story and Discussion menus in the menu bar hold its commands: pinning, Next story, sorting, collapsing every thread, jumping to the first new comment. Each window also remembers where you were in its article and discussion, so a reload, or Back to a story that Next took you past, finds your place again. Closing a window forgets it.

    The whole arrangement lives in the address, so a bookmark or a shared link brings it back, and Back undoes the last change. Moving between Hacker News, Lobsters, their lists, Pinned and Find changes only the list, and leaves the windows open.

    The list

    The pin at the start of a row keeps the story in Pinned, and the cross at its end hides it. Pinned can be narrowed by words in the title, site or author, by source, and to the stories you haven't opened yet, and ordered by when you pinned them, by points or by comments; the filters are part of the address, so a filtered view can be bookmarked. Scroll past the end of the list to load more. Domain filters, in the View menu, hide every story from a site.

    Collections are named lists of stories. Story > Add to collection files the story in front into one or more of them, and the Collections feed shows them all or one at a time; the menu that chooses collections also creates, renames, and deletes them. A note is your own text on a story. Choose Add note in a story's toolbar to write one; it saves as you type. Rows with a note carry the note mark, and the Notes feed lists every noted story and searches the text of your notes.

    Browsing view

    View > Windowed and View > Classic select the browsing view and save your default in this browser. Window view reuses a reader for each feed. Classic view opens stories and applets as pages. Open as a page is a one-off action that does not change your saved default. Use the Windowed selector to return an article to a window. Direct page links always open as pages.

    Applets

    The Applets menu in the menu bar holds three tools, each a window of its own. Replies to me takes your Hacker News user name and lists the replies to your last thirty comments and stories, checking again every three minutes while it is open, and marking what is new since you last marked them read. Look up a user opens a profile on Hacker News or Lobsters, with their submissions and recent comments, as a commenter's name in any discussion does; the bar at the top of a profile looks up someone else in the same window, and Back returns to the one before. Who is hiring? filters the posts of HN's monthly hiring threads by the words you type.

    They read only what the sites publish to everyone, so none of them asks for a login, and your user name stays in this browser anonymously and is included in retained applet state when signed in.

    Find

    Find takes any link and lists every time it was submitted to Hacker News and Lobsters, so you can read each discussion of it.

    About

    YAVCHN never sees your Hacker News or Lobsters login. The discussion is fetched from each site's public API; to vote or reply, follow the link above the discussion, or the arrow beside a comment, to the source's own site. Without a YAVCHN account, your data stays in this browser. When signed in, pins, collections, notes, blocked domains, and retained reading state are stored with your account and synchronized across devices. Hidden stories and layout stay in this browser.

    Open source: github.com/paulmooreparks/yavchn. Built with PUDL.