• Stars
    star
    138
  • Rank 263,015 (Top 6 %)
  • Language
    Scheme
  • Created over 6 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Embeddable lisp/scheme interpreter written in C.

Lisp Interpreter

Any sufficiently complicated C or Fortran program contains an ad hoc, informally-specified, bug-ridden, slow implementation of half of Common Lisp. -- Philip Greenspun

An embeddable lisp/scheme interpreter written in C. It includes a subset of R5RS with some extensions from MIT Scheme.

I created this while reading SICP to improve my knowledge of lisp and to make an implementation that allows me to easily add scripting to my own programs.

Philosophy

  • Simple: This project doesn't aim to be optimal, or fully standards compliant. It is just a robust foundation for scripting. It is implemented as a recursive AST walker on the C stack.

    If you need more try s7 or chicken

  • Unintrusive: Just copy in the header file. Turn on and off major features with build macros. It should be portable between major platforms.

  • Unsurprising: You should be able to read the source code and understand how it works. The C API should work how you expect.

  • First class data: Lisp s-expressions are undervalued as an alternative to JSON or XML. Preprocessor flags can remove most scheme features if you just want to read s-expressions and manipulate them in C.

Features

  • C99, no dependencies, two files.
  • Core lisp language if, let, do, lambda, cons, eval, etc.
  • Subset of scheme R5RS library: lists, vectors, hash tables, integers, real numbers, characters, strings, and integers.
  • Common lisp goodies: unhygenic macros (define-macro), push, dotimes.
  • Easy to integrate C functions.
  • Exact garbage collection with explicit invocation.
  • REPL command line tool.
  • Efficient parsing and manipulation of large data files.

Non-Features

  • Compiler or VM.
  • Full numeric tower.
  • Full call/cc. This only supports simple stack jumps.
  • syntax rules.
  • UNIX system interface/IO library.

Examples

Interactive programming with Read, eval, print loop.

$ ./lisp
> (define (sqr x) (* x x)))
> (define length 40)
> (define area 0)
> (set! area (sqr length))
1600

Quickstart

LispContext ctx = lisp_init();
lisp_load_lib(ctx);

LispError error;
Lisp program = lisp_read("(+ 1 2)", &error, ctx);
Lisp result = lisp_eval(program, &error, ctx);

if (error != LISP_ERROR_NONE)
    lisp_print(result); ; => 3

lisp_shutdown(ctx);

Loading Data

Lisp s-expressions can be used as a lightweight substitute to JSON or XML. Looking up keys which are reused is even more efficient due to symbol comparison.

JSON

{
   "name" : "Bob Jones",
   "age" : 54,
   "city" : "SLC",
}

Lisp

#((name . "Bob Jones")
  (age . 54)
  (city . "SLC"))

Loading the structure in C.

LispContext ctx = lisp_init();
// load lisp structure
Lisp data = lisp_read_file(file, ctx);
// get value for age
Lisp age_entry = lisp_avector_ref(data, lisp_make_symbol("AGE", ctx), ctx);
// ...
lisp_shutdown(ctx);

Calling C functions

C functions can be used to extend the interpreter, or call into C code.

Lisp integer_range(Lisp args, LispError* e, LispContext ctx)
{
    // first argument
    LispInt start = lisp_int(lisp_car(args));
    args = lisp_cdr(args);
    // second argument
    LispInt end = lisp_int(lisp_car(args));

    if (end < start)
    {
        *e = LISP_ERROR_OUT_OF_BOUNDS;
        return lisp_null();
    }

    LispInt n = end - start;
    Lisp numbers = lisp_make_vector(n, ctx);

    for (LispInt i = 0; i < n; ++i)
        lisp_vector_set(numbers, i, lisp_make_int(start + i));

    return numbers;
}
// ...

// wrap in Lisp object
Lisp func = lisp_make_func(integers_in_range);

// add to enviornment with symbol INTEGER-RANGE
Lisp env = lisp_env_global(ctx);
lisp_env_define(env, lisp_make_symbol("INTEGER-RANGE", ctx), func, ctx);

In Lisp

(integer-range 5 15)
; => #(5 6 7 8 9 10 11 12 13 14)

Constants can also be stored in the environment in a similar fashion.

Lisp pi = lisp_make_real(3.141592);
lisp_env_define(env, lisp_make_symbol("PI", ctx), pi, ctx);

Macros

Common Lisp style (defmacro) is available with the name define-macro.

(define-macro nil! (lambda (x)
  `(set! ,x '()))

Garbage Collection

Garbage is only collected if it is explicitly told to. You can invoke the garbage collector in C:

lisp_collect(ctx);

OR in lisp code:

(gc-flip)

Note that whenever a collect is issued ANY Lisp value in Cwhich is not accessible through the global environment may become invalid. Be careful what variables you hold onto in C.

Don't call eval in a custom defined C function unless you know what you are doing.

See internals for more details.

Documentation

For the language refer to MIT Scheme with the understanding that not everything is missing. If we do implement a feature that MIT scheme has, we will try to follow their specificaiton.

For the C API refer to the header and sample programs (repl.c, printer.c).

Project License

Copyright (c) 2020 Justin Meiners

Permission to use, copy, modify, and distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

More Repositories

1

lc3-vm

Write your own virtual machine for the LC-3 computer!
Makefile
1,194
star
2

ios-color-wheel

A fully scalable, dynamically rendered color wheel for iOS.
Objective-C
81
star
3

srcweave

A literate programming system for any language.
Common Lisp
78
star
4

efficient-programming-with-components

Course notes for Alexander Stepanov's teachings on design and usage of C++ STL.
HTML
73
star
5

stb-truetype-example

Example of how to use stb_truetype library for rendering TrueType fonts.
C
64
star
6

image-sequence-streaming

Realtime, non-linear animation playback for interactive pieces.
Objective-C
54
star
7

classic-colors

Paint program for Unix. Inspired by MS Paint (Windows 95-98).
C
45
star
8

sgi-stl-docs

Standard template library (STL) documentation from SGI. (Mirror)
42
star
9

iOS-Quizkit

Local Quiz/Test administration and management for iOS.
Objective-C
31
star
10

lc3-rogue

Roguelike tunnel generator in LC3 assembly. (Homework)
Assembly
25
star
11

why-train-when-you-can-optimize

Learn multi-variable optimization by creating a drawing assistant. No deep learning required!
Makefile
25
star
12

text2image

Render text to images with this tiny command line tool.
C
19
star
13

c-craft

Minecraft clone written in C.
C
19
star
14

tiny-blockchain

Write your own proof-of-work blockchain.
Makefile
17
star
15

gesture-recognition

Handwriting and gesture recognition with line integrals.
JavaScript
16
star
16

pre-rendered-backgrounds

An Adventure in Pre-Rendered Backgrounds. (Video game prototype.)
C
16
star
17

molecule-viewer

3D chemical molecule visualizer for XYZ files.
C++
15
star
18

spherical-harmonics

Spherical Harmonics expository paper (undergrad) and implementation.
TeX
14
star
19

neural-nets-sim

McCulloch & Pitts neural net simulator.
JavaScript
11
star
20

c-game-debug-console

Quake style debug console for games. Written in ANSI C.
C
10
star
21

justinmeiners.github.io

My personal website on Github pages.
JavaScript
9
star
22

shamans

A 3D turn-based strategy game for the iPad.
C
8
star
23

exercises

Exercises I do from books, articles, etc.
Scheme
8
star
24

mode-7

An experiment with mode-7 software rendering.
C
5
star
25

derivative-map-tool

Compute derivative maps from height maps for bumpmapping.
C
5
star
26

c-foundation

An implementation of an ANSI C class system similar to Apple's Core Foundation. (Retain/release, autorelease, mutable/immutable, etc)
C
4
star
27

sicp-html-original

Original HTML text for the classic textbook Structure and Interpretation of Computer Programs.
HTML
4
star
28

text2cs

Converts text files to C strings, usually to be included in another program. (SQL queries, shaders, etc).
C
3
star
29

js13k-2022-volcano-drop

3D video game in 13Kb (no WebGL!).
JavaScript
3
star
30

sicm-docker

Docker container for running "Structure and Interpretation of Classical Mechanics"
Scheme
3
star
31

html-8bit-chess

8-bit Chess with HTML5 canvas.
JavaScript
3
star
32

chicken-termbox

Chicken Scheme bindings for termbox.
C
3
star
33

tcmportmapper

Automatically exported from code.google.com/p/tcmportmapper
C
1
star
34

lin-math

My attempt at creating a generalized vector/matrix library.
C++
1
star
35

google-chrome-comic-book

Archive of 2008 Google Chrome comic book: https://www.google.com/googlebooks/chrome/
HTML
1
star