tomhrr / dale

Lisp-flavoured C
BSD 3-Clause "New" or "Revised" License
1.03k stars 48 forks source link

Adding compiler-macros using c++-like constexpr #94

Closed porky11 closed 7 years ago

porky11 commented 8 years ago

for example when I want define pow for int:

(def pow (fn extern int ((n int) (pow int))
  …)
(def pow (macro extern int ((n int) (pow (constexpr int)))
  …) ;;this would define a specialized version of pow, if the value of pow is known at compile time

so if I write (pow x 3) it could expand to (* x x x) instead of calling a function using loops constantexpr may just be an atom, and if something should be evaluated at compile-time, macros will have to be used.

tomhrr commented 8 years ago

On Sun, Sep 11, 2016 at 05:21:01AM -0700, Fabio Krapohl wrote:

for example when I want define pow for int:

(def pow (fn extern int ((n int) (pow int)) …) (def pow (macro extern int ((n int) (pow (constexpr int))) …) ;;this would define a specialized version of pow, if the value of pow is known at compile time

so if I write (pow x 3) it could expand to (* x x x) instead of calling a function using loops constantexpr may just be an atom, and if something should be evaluated at compile-time, macros will have to be used.

Rather than adding dispatch on constant expressions, which is likely to be a fair undertaking, it would be preferable if the macros handled dispatch internally. For example, in the above case, if the 'pow' argument is a token with a parseable value below some threshold, then the 'pow' macro can return an optimised expansion. This requires that the names be different, and it also doesn't help when the 'pow' argument is something more complicated than a bare number, but are these constraints such that better handling is warranted for your use case?

If it would be ideal for it to be handled better, I'd rather add some sort of 'eval'-like form to the introspection module for evaluating arbitary constant forms, than make dispatch more complicated.

porky11 commented 8 years ago

Some eval-like form may be nice, even for other cases. But I don't know yet how I would implement it, or if it is even possible without changing the c++-source

tomhrr commented 8 years ago

On Mon, Sep 12, 2016 at 12:54:20PM -0700, Fabio Krapohl wrote:

Some eval-like form may be nice, even for other cases. But I don't know yet how I would implement it, or if it is even possible without changing the c++-source

An eval-expression function has been added to the introspection module. It only works for ints at the moment, though it could be expanded to handle other (primitive) types pretty easily. See https://raw.githubusercontent.com/tomhrr/dale/master/t/src/eval-expression.dt.