Lisp alternative implementation

Lisp alternative implementation

As mentioned in a blog post here, we dive into on a journey to craft an interpreter with node.js and I'm here again to show to everyone how to implement a simple interpreter of lisp. You can count with a base structure and just hack on some points get things up and running. There it is the reference:

GitHub - ktfth/tslisp
Contribute to ktfth/tslisp development by creating an account on GitHub.

Now we can start, with some key aspects of the implementation:

  • TokenType - where toke enumeration lives
  • Token - Where the abstraction of a token are structured
  • Scanner - The analisys of a program happens on that part to become tokens
  • Parser - Here our AST are builded to produce an abstraction who we can came accross
  • Interpreter - Now the AST can be understood and execute the instructions of our rules

With this in mind our goal here is to implement a minus operation, starting by token map on TokenTye.ts:

...
MINUS: 3
...

After that Scanner.ts receive an statement on scanToken for minus instruction:

...
case '-'.charCodeAt(0): this.addToken(TokenType.MINUS); break;
...

With this our interpreter are gaining a meaning execution, now act on Parser.ts adding the following instruction:

...
if (this.match(TokenType.MINUS)) {
  const operator = this.previous();
  const values = [];
  while (this.match(TokenType.NUMBER)) {
    const expr = new Literal(this.previous().literal);
    values.push(expr);
  }
  if (this.check(TokenType.LEFT_PAREN)) {
    const expr = this.expression();
    values.push(expr);
  }
  return new Binary(operator, values);
}
...

Now we have a tree to walk, and for the final goal just include the code of operation on Interpreter.ts for the correctly execution:

...
case TokenType.MINUS:
  if (values.some(value => value.constructor.toString().indexOf('Number') > -1)) {
    return values.reduce((a, b) => a - b);
  }
  break;
...

Now to see what happens, just run the build command [sudo] npm run build and to see what happens after the build [sudo] npm start and see the magic in front of your eyes:

We've come to the end of our journey. I hope you have a newfound appreciation for interpreters, along with some tips on how to write better code. Do you have any questions? I'd be happy to answer them in the email kaeyosthaeron@gmail.com. In the meantime, why not check out my other posts on programming? You might just find that one skill you were looking for all this time.

Happy coding!

See our partner:

Maçons Livres
Nosso canal tem a nobre missão de levar aos nossos amigos e irmãos , informações relevantes a nossa sublime ordem. Tudo sobre a ordem maçônica você encontra aqui !Por dentro da Ordem Maçônica