Full Code of maryrosecook/littlelisp for AI

master 5f81efa7bcab cached
7 files
11.3 KB
3.1k tokens
1 requests
Download .txt
Repository: maryrosecook/littlelisp
Branch: master
Commit: 5f81efa7bcab
Files: 7
Total size: 11.3 KB

Directory structure:
gitextract__i2r7b5i/

├── .gitignore
├── LICENSE
├── README.md
├── littlelisp.js
├── littlelisp.spec.js
├── package.json
└── repl.js

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
node_modules/

================================================
FILE: LICENSE
================================================
The MIT License (MIT)

Copyright (c) 2013-2014 Mary Rose Cook and contributors

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

================================================
FILE: README.md
================================================
# Little Lisp

A mini Lisp interpreter in JavaScript.  Supports lists (obvs), function invocation, lambdas, lets, if statements, numbers, strings and the library functions `first`, `rest` and `print`.

* By Mary Rose Cook
* https://maryrosecook.com
* mary@maryrosecook.com

Thank you to Martin Tornwall for the implementations of let and if.

## Repl

```
$ node repl.js
```

## Some runnable programs

```lisp
1
```

```lisp
(first (1 2 3))
```

```lisp
((lambda (x) (rest x)) ("a" "b" "c"))
```


================================================
FILE: littlelisp.js
================================================
;(function(exports) {
  var library = {
    first: function(x) {
      return x[0];
    },

    rest: function(x) {
      return x.slice(1);
    },

    print: function(x) {
      console.log(x);
      return x;
    }
  };

  var Context = function(scope, parent) {
    this.scope = scope;
    this.parent = parent;

    this.get = function(identifier) {
      if (identifier in this.scope) {
        return this.scope[identifier];
      } else if (this.parent !== undefined) {
        return this.parent.get(identifier);
      }
    };
  };

  var special = {
    let: function(input, context) {
      var letContext = input[1].reduce(function(acc, x) {
        acc.scope[x[0].value] = interpret(x[1], context);
        return acc;
      }, new Context({}, context));

      return interpret(input[2], letContext);
    },

    lambda: function(input, context) {
      return function() {
        var lambdaArguments = arguments;
        var lambdaScope = input[1].reduce(function(acc, x, i) {
          acc[x.value] = lambdaArguments[i];
          return acc;
        }, {});

        return interpret(input[2], new Context(lambdaScope, context));
      };
    },

    if: function(input, context) {
      return interpret(input[1], context) ?
        interpret(input[2], context) :
        interpret(input[3], context);
    }
  };

  var interpretList = function(input, context) {
    if (input.length > 0 && input[0].value in special) {
      return special[input[0].value](input, context);
    } else {
      var list = input.map(function(x) { return interpret(x, context); });
      if (list[0] instanceof Function) {
        return list[0].apply(undefined, list.slice(1));
      } else {
        return list;
      }
    }
  };

  var interpret = function(input, context) {
    if (context === undefined) {
      return interpret(input, new Context(library));
    } else if (input instanceof Array) {
      return interpretList(input, context);
    } else if (input.type === "identifier") {
      return context.get(input.value);
    } else if (input.type === "number" || input.type === "string") {
      return input.value;
    }
  };

  var categorize = function(input) {
    if (!isNaN(parseFloat(input))) {
      return { type:'number', value: parseFloat(input) };
    } else if (input[0] === '"' && input.slice(-1) === '"') {
      return { type:'string', value: input.slice(1, -1) };
    } else {
      return { type:'identifier', value: input };
    }
  };

  var parenthesize = function(input, list) {
    if (list === undefined) {
      return parenthesize(input, []);
    } else {
      var token = input.shift();
      if (token === undefined) {
        return list.pop();
      } else if (token === "(") {
        list.push(parenthesize(input, []));
        return parenthesize(input, list);
      } else if (token === ")") {
        return list;
      } else {
        return parenthesize(input, list.concat(categorize(token)));
      }
    }
  };

  var tokenize = function(input) {
    return input.split('"')
                .map(function(x, i) {
                   if (i % 2 === 0) { // not in string
                     return x.replace(/\(/g, ' ( ')
                             .replace(/\)/g, ' ) ');
                   } else { // in string
                     return x.replace(/ /g, "!whitespace!");
                   }
                 })
                .join('"')
                .trim()
                .split(/\s+/)
                .map(function(x) {
                  return x.replace(/!whitespace!/g, " ");
                });
  };

  var parse = function(input) {
    return parenthesize(tokenize(input));
  };

  exports.littleLisp = {
    parse: parse,
    interpret: interpret
  };
})(typeof exports === 'undefined' ? this : exports);


================================================
FILE: littlelisp.spec.js
================================================
var t = require('./littlelisp').littleLisp;

var is = function(input, type) {
  return Object.prototype.toString.call(input) === '[object ' + type + ']';
};

// takes an AST and replaces type annotated nodes with raw values
var unannotate = function(input) {
  if (is(input, 'Array')) {
    if (input[0] === undefined) {
      return [];
    } else if (is(input[0], 'Array')) {
      return [unannotate(input[0])].concat(unannotate(input.slice(1)));
    } else {
      return unannotate(input[0]).concat(unannotate(input.slice(1)));
    }
  } else {
    return [input.value];
  }
};

describe('littleLisp', function() {
  describe('parse', function() {
    it('should lex a single atom', function() {
      expect(t.parse("a").value).toEqual("a");
    });

    it('should lex an atom in a list', function() {
      expect(unannotate(t.parse("()"))).toEqual([]);
    });

    it('should lex multi atom list', function() {
      expect(unannotate(t.parse("(hi you)"))).toEqual(["hi", "you"]);
    });

    it('should lex list containing list', function() {
      expect(unannotate(t.parse("((x))"))).toEqual([["x"]]);
    });

    it('should lex list containing list', function() {
      expect(unannotate(t.parse("(x (x))"))).toEqual(["x", ["x"]]);
    });

    it('should lex list containing list', function() {
      expect(unannotate(t.parse("(x y)"))).toEqual(["x", "y"]);
    });

    it('should lex list containing list', function() {
      expect(unannotate(t.parse("(x (y) z)"))).toEqual(["x", ["y"], "z"]);
    });

    it('should lex list containing list', function() {
      expect(unannotate(t.parse("(x (y) (a b c))"))).toEqual(["x", ["y"], ["a", "b", "c"]]);
    });

    describe('atoms', function() {
      it('should parse out numbers', function() {
        expect(unannotate(t.parse("(1 (a 2))"))).toEqual([1, ["a", 2]]);
      });
    });
  });

  describe('interpret', function() {
    describe('lists', function() {
      it('should return empty list', function() {
        expect(t.interpret(t.parse('()'))).toEqual([]);
      });

      it('should return list of strings', function() {
        expect(t.interpret(t.parse('("hi" "mary" "rose")'))).toEqual(['hi', "mary", "rose"]);
      });

      it('should return list of numbers', function() {
        expect(t.interpret(t.parse('(1 2 3)'))).toEqual([1, 2, 3]);
      });

      it('should return list of numbers in strings as strings', function() {
        expect(t.interpret(t.parse('("1" "2" "3")'))).toEqual(["1", "2", "3"]);
      });
    });

    describe('atoms', function() {
      it('should return string atom', function() {
        expect(t.interpret(t.parse('"a"'))).toEqual("a");
      });

      it('should return string with space atom', function() {
        expect(t.interpret(t.parse('"a b"'))).toEqual("a b");
      });

      it('should return string with opening paren', function() {
        expect(t.interpret(t.parse('"(a"'))).toEqual("(a");
      });

      it('should return string with closing paren', function() {
        expect(t.interpret(t.parse('")a"'))).toEqual(")a");
      });

      it('should return string with parens', function() {
        expect(t.interpret(t.parse('"(a)"'))).toEqual("(a)");
      });

      it('should return number atom', function() {
        expect(t.interpret(t.parse('123'))).toEqual(123);
      });
    });

    describe('invocation', function() {
      it('should run print on an int', function() {
        expect(t.interpret(t.parse("(print 1)"))).toEqual(1);
      });

      it('should return first element of list', function() {
        expect(t.interpret(t.parse("(first (1 2 3))"))).toEqual(1);
      });

      it('should return rest of list', function() {
        expect(t.interpret(t.parse("(rest (1 2 3))"))).toEqual([2, 3]);
      });
    });

    describe('lambdas', function() {
      it('should return correct result when invoke lambda w no params', function() {
        expect(t.interpret(t.parse("((lambda () (rest (1 2))))"))).toEqual([2]);
      });

      it('should return correct result for lambda that takes and returns arg', function() {
        expect(t.interpret(t.parse("((lambda (x) x) 1)"))).toEqual(1);
      });

      it('should return correct result for lambda that returns list of vars', function() {
        expect(t.interpret(t.parse("((lambda (x y) (x y)) 1 2)"))).toEqual([1, 2]);
      });

      it('should get correct result for lambda that returns list of lits + vars', function() {
        expect(t.interpret(t.parse("((lambda (x y) (0 x y)) 1 2)"))).toEqual([0, 1, 2]);
      });

      it('should return correct result when invoke lambda w params', function() {
        expect(t.interpret(t.parse("((lambda (x) (first (x))) 1)")))
          .toEqual(1);
      });
    });

    describe('let', function() {
      it('should eval inner expression w names bound', function() {
        expect(t.interpret(t.parse("(let ((x 1) (y 2)) (x y))"))).toEqual([1, 2]);
      });

      it('should not expose parallel bindings to each other', function() {
        // Expecting undefined for y to be consistent with normal
        // identifier resolution in littleLisp.
        expect(t.interpret(t.parse("(let ((x 1) (y x)) (x y))"))).toEqual([1, undefined]);
      });

      it('should accept empty binding list', function() {
        expect(t.interpret(t.parse("(let () 42)"))).toEqual(42);
      });
    });

    describe('if', function() {
      it('should choose the right branch', function() {
        expect(t.interpret(t.parse("(if 1 42 4711)"))).toEqual(42);
        expect(t.interpret(t.parse("(if 0 42 4711)"))).toEqual(4711);
      });
    });
  });
});


================================================
FILE: package.json
================================================
{
  "name": "littlelisp",
  "description": "An interpreter for a little lisp.",
  "author": "Mary Rose Cook <mary@maryrosecook.com> (https://maryrosecook.com/)",
  "version": "0.1.0",
  "scripts": {
    "test": "node_modules/jasmine-node/bin/jasmine-node *.spec.js"
  },
  "dependencies": {
    "jasmine-node": "^1.14.5"
  }
}


================================================
FILE: repl.js
================================================
var repl = require("repl");
var littleLisp = require("./littlelisp").littleLisp;

repl.start({
  prompt: "> ",
  eval: function(cmd, context, filename, callback) {
    var ret = littleLisp.interpret(littleLisp.parse(cmd));
    callback(null, ret);
  }
});
Download .txt
gitextract__i2r7b5i/

├── .gitignore
├── LICENSE
├── README.md
├── littlelisp.js
├── littlelisp.spec.js
├── package.json
└── repl.js
Condensed preview — 7 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (12K chars).
[
  {
    "path": ".gitignore",
    "chars": 13,
    "preview": "node_modules/"
  },
  {
    "path": "LICENSE",
    "chars": 1102,
    "preview": "The MIT License (MIT)\n\nCopyright (c) 2013-2014 Mary Rose Cook and contributors\n\nPermission is hereby granted, free of ch"
  },
  {
    "path": "README.md",
    "chars": 497,
    "preview": "# Little Lisp\n\nA mini Lisp interpreter in JavaScript.  Supports lists (obvs), function invocation, lambdas, lets, if sta"
  },
  {
    "path": "littlelisp.js",
    "chars": 3778,
    "preview": ";(function(exports) {\n  var library = {\n    first: function(x) {\n      return x[0];\n    },\n\n    rest: function(x) {\n    "
  },
  {
    "path": "littlelisp.spec.js",
    "chars": 5636,
    "preview": "var t = require('./littlelisp').littleLisp;\n\nvar is = function(input, type) {\n  return Object.prototype.toString.call(in"
  },
  {
    "path": "package.json",
    "chars": 327,
    "preview": "{\n  \"name\": \"littlelisp\",\n  \"description\": \"An interpreter for a little lisp.\",\n  \"author\": \"Mary Rose Cook <mary@maryro"
  },
  {
    "path": "repl.js",
    "chars": 256,
    "preview": "var repl = require(\"repl\");\nvar littleLisp = require(\"./littlelisp\").littleLisp;\n\nrepl.start({\n  prompt: \"> \",\n  eval: f"
  }
]

About this extraction

This page contains the full source code of the maryrosecook/littlelisp GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 7 files (11.3 KB), approximately 3.1k tokens. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!