lokke-org / lokke

Lokke: Clojure for Guile
Other
199 stars 11 forks source link

Lokke: Clojure for Guile

Lokke intends to provide a full dialect of Clojure for Guile. It also consists of a set of Guile modules providing some of Clojure's functionality in two different guises.

Note: everything is currently very experimental, including the various API "levels" -- they may not all survive, depending in part on whether or not they end up seeming valuable enough to be worth the maintenance costs.

For Clojure itself

The Clojure dialect is currently available via ./lokke which can run code, serve as a !# interpreter, or provide a REPL. See below for further information.

For a more Clojure oriented experience in Scheme

Lokke provides one set of modules, starting with (lokke core) that create an environment that looks suspiciously like Clojure. In most cases these modules prefer Clojure's approach when there's a conflict, and they're not shy about using generic functions. For example, = is a generic, and implements Clojure's semantics, not Scheme's, and currently (lokke core) and (lokke base syntax), will replace let and when, via use-modules, so be cautious. We recommend following the Clojure practice of explicitly #:selecting the symbols you want to import, (or #:prefixing the namespace) to avoid the problem entirely, and to make it much easier to discover the origin of a binding. In some cases, Scheme vectors may be required in place of Clojure's immutable vectors, perhaps something like (let #(x 1 y 2) ...), though the approach to these binding forms on the Scheme side is still experimental.

For a more Scheme oriented experience in Scheme

Lokke may also provide (lokke scm ...) modules, which define a more Scheme-friendly, and possibly more efficient interface -- think (lokke-vector-length v) as compared to (count v). Perhaps the most notable existing module is (lokke scm vector) which intends to provide a C backed implementation of Clojure's persistent vectors.

Getting started

Currently Lokke can be found at GitHub and sourcehut.

To build Lokke, you'll need

Your system may already provide these. For Debian, for example:

# apt install autoconf automake libpcre2-dev libunistring-dev
# apt install make gettext gcc git

and then for Guile:

# apt-get install guile-3.0 guile-3.0-dev

See INSTALL for additional platform-specific information.

Once you have the dependencies installed, you should be able to build lokke like this:

$ git clone https://github.com/lokke-org/lokke
$ cd lokke
$ ./setup
$ autoreconf -fi
$ ./configure
$ make check

Hopefully the tests will pass. If not, please report them to the Lokke list. Parallel builds are supported, so depending on the host, something like make -j5 check can be much faster.

If you have more than one version of Guile installed, you may be able to select a particular version at configuration time like this:

$ ./configure GUILE_EFFECTIVE_VERSION=3.0

unless your platform requires other arrangements, which should be mentioned in the relevant section in INSTALL.

After building, you can run Clojure programs like this:

$ ./lok -l hello.clj
...
hello

or the REPL like this:

$ ./lok
...
lokke@lokke.user>

./lok ... is equivalent to ./lokke run ....

Currently the Lokke REPL is the Guile REPL, with the initial language and environment set for Lokke, and so all of the Guile features should be available. For now, lokke loads $XDG_CONFIG_HOME/lokke/interactive.scm if $XDG_CACHE_HOME is set, otherwise ~/.config/lokke/interactive.scm rather than ~/.guile.

See ./lokke --help or man -M . lokke.1 for additional information. A plain text version of the manual page is also available.

Assuming your guile was compiled with readline support, it's likely you'll want to add something like this to ~/.config/lokke/interactive.scm:

;;; -*-scheme-*-
(use-modules (ice-9 readline))
(activate-readline)

The REPL history will be stored in the file indicated by the environment variable LOKKE_HISTORY if set, otherwise $XDG_CACHE_HOME/lokke/history if $XDG_CACHE_HOME is set, otherwise ~/.cache/lokke/history.

There is also a ./guile wrapper which just runs Guile with the correct environment for Lokke (and which ./lokke relies on). It can be useful during development, or if you would like to try out the Scheme specific facilities:

$ ./guile
...
scheme@(guile-user)> (use-modules (lokke core))
scheme@(guile-user)> (take 3 (repeat "?"))
$1 = #<<class> <lazy-seq> 55bdaff362c0 ("?" "?" "?")>

As you can see, seqs are not written like lists. Currently the Scheme write representation of many Clojure objects is intentionally distinct. Of course prn from (lokke core) prints the Clojure representation.

From ./guile, you can switch to a Lokke REPL manually like this:

scheme@(guile-user)> ,module (lokke ns lokke user)
scheme@(lokke ns lokke user)> ,language lokke
Happy hacking with Lokke, a Clojure dialect!  To switch back, type `,L scheme'.
lokke@(lokke ns lokke user)> (inc 1)
$1 = 2

Lokke expects all Clojure namespaces to be located in a lokke/ns/ subdirectory of one of the directories specified by the Guile load path. The path can be adjusted by setting GUILE_LOAD_PATH in the environment. For example, since ./mod is in ./lokke's default load path, Lokke will look for clojure.string in mod/lokke/ns/clojure/string.go (compiled version), mod/lokke/ns/clojure/string.clj, and mod/lokke/ns/clojure/string.scm in that order (namspaces can be implemented in Clojure or Scheme).

See the DESIGN document for an overview of the implementation, and detailed information about Guile is available in the Guile Reference Manual which should also be available via info guile if installed.

General comparison with Clojure/JVM

On the Scheme side

Clojure namespaces and Guile modules

Clojure namespaces are Guile modules (which have very comparable semantics), and the entire Clojure namespace tree is situated under (lokke ns) in the Guile module tree, i.e. clojure.string is implemented by the (lokke ns clojure string) module, and clojure.string/join is exactly equivalent to a Guile reference to the join function in the (lokke ns clojure string) module.

All clojure namspaces starting with guile represent direct references to the root of the guile module tree, e.g. (guile.srfi.srfi-19/current-date) calls the current-date function in the guile (srfi srfi-19) module. These provide a convenient way to refer to modules that are not under a (lokke ns ...) prefix, and of course you can use them in forms like ns and require. As a special case, the guile namespace refers to the (guile) module, not (guile guile). For example (guile/current-time) or (guile/delete-file ...).

In many cases, you may have lokke or lok handle the Guile %load-path for you via deps.edn :paths, but manual arrangements like this will also work fine:

src/something/core.clj
mod/lokke/ns -> ../../src

and then:

$ GUILE_LOAD_PATH=$(pwd)/mod lok -e "(require '[something.core ...])" ...

Namespace (alias ...) calls only take full effect at the end of the enclosing top level form (because at the moment, the compiler works from a snapshot of the alias map, cf. rewrite-il-calls).

Exception handling

There is experimental support for try/catch/finally which maps closely to Guile's exceptions (also rnrs conditions), meaning that in addition to catching an ex-info exception via (catch ExceptionInfo ex ...), you can catch Guile exceptions if you know the appropriate type, e.g. (catch guile.ice-9.exceptions/&error ex ...) (which is the same as rnrs.conditions/&error).

When an exception is caught, ex is bound to the exception/condition object as you might expect. Access the elements of Lokke-specific exceptions via the normal accessors: ex-message, ex-data, etc., and the lokke.exception namespace provides additional bindings like ex-info?, and ex-cause.

Note that the current implementation only expects and intends to support Clojure exception semantics, i.e. any given try will be entered and exited at most once. No consideration has been given to the accomodation of multiple entries or exits (e.g. via use of Scheme's call-with-current-contination, or related mechanisms).

At the moment, in addition to ExceptionInfo Lokke provides rudimentary JVM compatibility via Throwable, Error, Exception, and AssertionError types. The first three are currently &errors, and AssertionError is an &assertion. All four can be constructed via JVM-style Type. constructors (e.g. Throwable.) that accept arguments matching the JVM's.

Consider the current arrangement very unstable.

Exception suppression

Lokke has experimental support for suppressing exceptions, a concept also found on the JVM and in Python, though the details vary. If an exception is thrown from within a finally block, and there was a pending Lokke exception, the exception that was thrown from the finally block will be added to the pending exception as a suppressed exception, and the exception will be rethrown. The collection of suppressed exceptions can be retrieved with lokke.exception/ex-suppressed, and a suppressed exception can be added to any exception with lokke.exception/add-suppressed. Note that add-suppressed is persistent, returning a new exception that may or may not share structure with the original.

As an example:

    (try
      (print-masterpiece)  ; Throws (ex-info ... {:kind :lp0-on-fire})
      (finally
        (turn-off-light)))  ; Throws (ex-info ... {:kind :switch-broken})

At this point, without suppression you'd know that you need to fix your light switch, but have no idea that your printer is on fire. But with suppression, that information is preserved:

    (try
      (print-masterpiece)  ; Throws (ex-info ... {:kind :lp0-on-fire})
      (finally
        (turn-off-light)))  ; Rethrows lp0-on-fire exception, with switch-broken
                            ; available via (ex-suppressed lp0-on-fire).

The JVM provides a related precedent, though it only applies to try-with-resources constructs.

Because Guile exceptions are compositional, and the suppressed exceptions are implemented via an exception type, this system is compatible with all Guile exceptions, not just Lokke exceptions, i.e. suppressed exceptions can be added to any exception when appropriate.

See DESIGN for further details.

with-final

with-final is provided by lokke.exception for more flexible resource management. You can specify final actions to take either:always or only if there's an :error. The latter can be particularly useful in cases where normal cleanup must happen in a completely different scope. For example:

    (defn start-server [...]
      (with-final [foo (open-foo ...) :error close
                   bar (connect-bar ...) :error disconnect
                   ...]
        ...do many things...
        {:foo foo :bar bar ...}))

    (defn stop-server [info]
      (with-final [_ (:foo info) :always close
                   _ (:bar info) :always disconnect
                   ...]
        true)

with-final may be considered a generalization of with-open.

Dynamic variables and binding

At the moment, dynamic variables must be declared via (defdyn name init-expr) rather than via metadata, and they are always inherited by sub-threads, unlike on the JVM, where only some forms provide binding conveyance. You can define dynamic variables without conveyance via defdynloc.

Whether or not bindings are established in parallel is undefined.

Comparisons, hashing, and equality

Additional differences from Clojure/JVM

Known issues

Contributing

Patches to Lokke should have a Signed-off-by: header. Including this header in your patches signifies that you are licensing your changes under the terms described in the License section below. If you like, git can can add the appropriate pseudo-header for you via the --signoff argument to commit, amend, etc.

Additional information, conventions, etc. may be found in the Hacking section in DESIGN.

The mailing list is available for broader, more general discussions, and patches are welcome there

Please send patches and problem reports to the list or raise a pull request. We may prefer the list for more involved discussions.

Additional tests

You can run the full test suite (requires all changes in the working tree to be committed) like this:

make check-everything

Note that this may download and execute code (e.g. dependencies like tools.cli via --deps). (The normal make check tests should not.)

Lokke (Danish)

Etymology

From Old Norse lokka. Cognate with German locken. Pronunciation

Verb

lokke ‎(imperative lok, infinitive at lokke, present tense lokker, past tense lokkede, past participle har lokket)

  1. tempt, entice, lure, seduce
  2. persuade, coax, cajole, wheedle, inveigle

Source

Definition provided by the wiktionary. (CC BY-SA 3.0)

Additional contacts

Thanks

Sincere thanks to Russell Mull, Ryan Senior, and Zak-Kent, for invaluable support and advice during the creation of the initial version.

License

This project (Lokke) is free software; unless otherwise specified you can redistribute it and/or modify it under the terms of (at your option) either of the following two licenses:

1) The GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1, or (at your option) any later version

2) The Eclipse Public License; either version 1.0 (EPL-1.0) or (at your option) any later version.

which is also specified by

SPDX-License-Identifier: LGPL-2.1-or-later OR EPL-1.0+

When an SPDX-License-Identifier appears in a given file, it specifies the license that applies to the contents of that file.

Any files covered by another license include a suitable disclaimer describing the applicable terms, including, but not limited to:

Copyright © 2015-2022 Rob Browning <rlb@defaultvalue.org>