cl-cpp-generator2 icon indicating copy to clipboard operation
cl-cpp-generator2 copied to clipboard

Calling `write-source` or `emit-c` from outside package

Open DPAttila opened this issue 1 year ago • 0 comments

Good day; first of all, thank you for this amazing package!

When I call write-source or emit-c from outside the package, generation does not work as expected. (I guess this is the reason why there's always (in-package :cl-cpp-generator2) in the example files.)

Is there a way to fix or circumvent this problem?

Minimal working example:

(I am using SBCL on a Linux machine.)

(load "~/quicklisp/setup.lisp")

(eval-when (:compile-toplevel :execute :load-toplevel)
  (ql:quickload "cl-cpp-generator2"))

(use-package :cl-cpp-generator2)

(format t "~a:~%~a~%"
        *package*
        (emit-c :code
          `(do0 
             (include <stdio.h>) 
             (defstruct0 struct_a (a int)))))

Note how the code above is in the default package. It's output:

$ sbcl --load tmp1.lisp --quit
...

#<package "COMMON-LISP-USER">:
do0(include(<stdio.h>), defstruct0(struct_a, a(int)))

If I execute the same expression inside the package, it works as expected:

(load "~/quicklisp/setup.lisp")

(eval-when (:compile-toplevel :execute :load-toplevel)
  (ql:quickload "cl-cpp-generator2"))
  
(in-package :cl-cpp-generator2)

(format t "~a:~%~a~%"
        *package*
        (emit-c :code 
          `(do0
             (include <stdio.h>)
             (defstruct0 struct_a (a int)))))
$ sbcl --load tmp2.lisp --quit
...
#<package "CL-CPP-GENERATOR2">:
#include <stdio.h> 
struct strcut_a {
        int a; 
}; ;

I've also tried something like

(defun emit-from-package ()
  (in-package :cl-cpp-generator2)
  (format t "~a:~%~a~%"
          *package*
          (emit-c :code
            `(do0 
               (include <stdio.h>) 
               (defstruct0 struct_a (a int)))))
  (in-package :my-package))

(emit-from-package)

Interestingly, this produces:

$ sbcl --load tmp3.lisp --quit
...

#<package "CL-CPP-GENERATOR2">:
do0(include(<stdio.h>), defstruct0(struct_a, a(int)))

So the package does change, but the output is still incorrect. (This leads me to believe that the in-package expression should be at top-level or has some side-effect at compile-time evaluation.)

Best Regards, DPA.

DPAttila avatar Jul 10 '24 16:07 DPAttila