anko / eslisp

un-opinionated S-expression syntax and macro system for JavaScript
ISC License
528 stars 31 forks source link

Fix for loading macros from relative paths when run within a Node REPL #48

Closed ynohtna closed 7 years ago

ynohtna commented 7 years ago

I've been interactively testing my interoperation of eslisp with bog standard JS within a Node REPL.

However, macros can not be defined within this environment due to the assumption that require.main will always be valid made at https://github.com/anko/eslisp/blob/master/src/built-in-macros.ls#L404-L423 ("hack around require makes loading macros from relative paths work").

require.main is undefined when eslisp (or any module) is imported interactively into the Node REPL. Evaluating any macro within eslisp within the REPL environment results in the following exception:

TypeError: Error evaluating macro `macro` (called at line 1, column 0): Cannot read property 'constructor' of undefined
    at compileAsMacro (/Users/anthony/src/eslisp/lib/built-in-macros.js:574:22)

The change in this PR calls env.compile-to-js with Node's global require when require.main is undefined, allowing macros to be used within the REPL, and with relative imports based at the folder where the Node REPL was executed.

anko commented 7 years ago

I found related issue while writing unit-tests for this, and went a bit deeper with the fix. I believe this should cover your specific use-case and more. If you're still up for it, could you confirm that on current master things look fine?

Thanks for your help!

ynohtna commented 7 years ago

It's a great fix. Thank you!