How do I deal with required Clojurescript code from Clojurescript macros? - macros

Let us say I have a X.clojurescript and a X.clojure namespace. Everything in X.clojurescript is Clojurescript code, everything in X.clojure is Clojure code. Unfortunately, I cannot define macros directly in Clojurescript, I have to define them in Clojure and then bring them into a Clojurescript namespace using
(ns X.clojurescript.abc
(:require-macros [X.clojure.def :as clj]))
This is fine. However, what if the macro (defined in X.clojure) is going to need to reference something defined in a Clojurescript namespace (X.clojurescript)? The problem is that the Clojure compiler does not look in my Clojurescript namespace (a separate directory) when resolving other namespaces.
I have gotten around this problem by simply creating a namespace in my Clojure code that has the same namespace and needed definition as exist in Clojurescript, but this seems kind of stupid. So, for instance, if I need X.clojurescript.abc.y in my macro, I will just create an additional namespace on the Clojure side that defs a dummy y in my Clojure version of X.clojurescript.abc; kind of dumb.
How do I deal with a macro that needs to refer to something on the Clojurescript side?

The only time a macro needs a specific namespace at the time of definition is if the macro is using code from said namespace to generate the list of symbols it will return.
you can follow along with these examples in the repl:
(defmacro foo
[a]
`(bar/bar ~a))
the definition of foo will compile even though bar is not a defined namespace
(foo :a)
calling foo will now fail because you have not defined the bar namespace, or the function bar yet
(ns bar)
(defn bar
[x]
[x x])
defines bar in the bar namespace
(ns user)
(foo :a)
=> [:a :a]
Notice that bar does not need to exist at the time of foo's definition. In fact the namespace does not even need to exist at the time of foo's definition.

Related

Scheme (Kawa) - How to force macro expansion inside another macro

I want to make a macro, that when used in class definition creates a field, it's public setter, and an annotation. However, it'd seem the macro is not expanding, mostly because it's used inside other (class definition) macro.
Here is an example how to define a class with one field:
(define-simple-class test-class ()
(foo :: java.util.List ))
My macro (only defines field as of now):
(define-syntax autowire
(syntax-rules ()
((autowire class id)
(id :: class))))
However, if I try to use it:
(define-simple-class test-class ()
(autowire java.util.List foo))
and query fields of the new class via reflection, I can see that it creates a field named autowire, and foo is nowhere to be seen. Looks like an issue of the order the macros are expanded.
Yes, macros are expanded “from the outside in”. After expanding define-simple-class, the subform (autowire java.util.List foo) does not exist anymore.
If you want this kind of behaviour modification, you need to define your own define-not-so-simple-class macro, which might expand to a define-simple-class form.
However, please step back before making such a minor tweak to something that is standard, and ask yourself whether it is worth it. The upside might be syntax that is slightly better aligned to the way you think, but the downside is that it might be worse aligned to the way others think (who might need to understand your code). There is a maxim for maintainable and readable coding: “be conventional”.

Common Lisp Macros Without Parantheses and Unusual Call Syntax

I am wondering how one writes macros in Common Lisp that allow him to part with Lisp forms in calls to the former.
For instance, suppose I have the following macro:
(defmacro define-route ((app uri method) &body body)
`(setf (ningle:route ,app ,uri :method ,method)
,#body))
A call to it would look something like this:
(define-route (*app* "/" :GET)
(print "Welcome to ningle using GET!"))
What if one wanted to write a macro that could be called like this:
#route(*app*, "/", :GET)
or like this:
route: *app*, "/", :GET
Is this possible? I have seen the #route syntax somewhere before but am not sure how to implement it, nor do I remember what it was called to look it up again.
We encounter this decorator syntax (or annotations in CL) in the Caveman or Lucerne web frameworks:
#route GET "/"
(defun index ()
(render #P"index.tmpl"))
I doubt you can do route: *app*, "/", :GET.
cl-annot is a general annotation library for CL.
It is a reader macro, more examples here: http://lisp-lang.org/wiki/article/reader-macros
ps: Snooze, by the author of Sly (and yasnippet), is a web frameworks that treats routes as usual functions, thus route parameters as usual function arguments. It also has built-in reporting of errors (in browser, in the debugger, with a custom 404 page). I liked it better than the two mentioned. No big experience with either of them.

Class finalization: how to avoid creating dummy instances?

I've run into a problem that a third-party library needs to act on a class as if it was finalized. After some reading I understand the motivation behind this mechanism, but I don't really know how it functions.
Example:
(make-instance 'expression :op '+ :left 'nan :right 'nan)
(defmethod normalize-expression ((this expression))
(optima:match this
((optima::or (expression :left 'nan) (expression :right 'nan)) 'nan)
((expression :op op :left x :right y) (funcall op x y))))
Unless I add the first line, the function will not compile, giving me this error:
; caught ERROR:
; (during macroexpansion of (SB-PCL::%DEFMETHOD-EXPANDER NORMALIZE-EXPRESSION ...))
; SB-MOP:CLASS-SLOTS called on #<STANDARD-CLASS EXPRESSION>, which is not yet finalized.
; See also:
; AMOP, Generic Function SB-MOP:CLASS-SLOTS
optima is a pattern-matching library, the (expression :op op ...) is matching instances of class expression against the given pattern. I don't know in much details, but it looks like it needs to know what are the accessors defined for this class, and it looks like that information is not available until it is finalized. So, is there any way to sidestep the finalization problem?
The class will not be extended (at least not in this project, and it's not being planned). It doesn't hurt that much to create a dummy instance... it is just an ugly solution, so I hoped to find a better one. Also, perhaps, I'd get some more info on finalization, which is good too :)
Forgetting to ensure class finalization seems to be quite common mistake when using MOP.
In lisp, classes are defined in two "phases":
Direct class definition
Effective class definition
Direct class definition is isomorphic to defclass form. It has class name, names of superclasses, list of direct slots (i.e., slots defined on this particular class but on its superclasses).
Effective class definition contains all information needed for compiler/interpreter. It contains list of all class slots (including those defined on superclasses), class instance layout, references to accessor methods, etc.
Process of transforming direct class definition to effective class definition is called class finalization. Since CLOS supports redefining classes, finalization might be called multiple times for a class. One of the reasons why finalization is delayed is because class may be defined before its superclasses are defined.
Regarding your particular problem: is seems that optima:match should ensure that class is finalized before trying to list its slots. This can be done with two functions: class-finalized-p (to check whether class needs finalization) and finalize-inheritance to actually perform finalization. Or you can use utility function closer-mop:ensure-finalized. (closer-mop is a library for portable usage of CLOS MOP).
E.g.,:
(c2mop:ensure-finalized (find-class 'expression))

Implementing Interfaces and calling Java Constants in Clojure (Newbie)

I am trying to write a wrapper for the google adwords api in Clojure but struggle with constants and Interfaces.
The java code looks like this :
CampaignServiceInterface campaignService =
user.getService(AdWordsService.V201109.CAMPAIGN_SERVICE);
Usually you can call constants in Clojure with e.g. (Math/PI) but when I write:
(def user (AdWordsUser. ))
(.getService user (AdWordsService/V201109/CAMPAIGN_SERVICE))
I just get "no such namespace".
Also I am a bit clueless on how to implement the interface correct. I think I should use "reify" but I get stuck.
Link to Interface:
http://google-api-adwords-java.googlecode.com/svn-history/r234/trunk/docs/com/google/api/adwords/v201003/cm/CampaignServiceInterface.html
(defn campaign-service [ ]
(reify
com.google.adwords.api.v201109.cm.CampaignServiceInterface
(get [this] ??))))
If I read it correctly, AdWordsService.V201109.CAMPAIGN_SERVICE is a static constant of an inner class of class AdWordsService.
To access inner classes you need to use java's internal name mangling scheme **; separate the inner class from its outer class with a $ sign:
AdWordsService$V201109/CAMPAIGN_SERVICE
** the JVM doesn't actually have a notion of inner classes, so java "fakes" it by creating a standalone class AdWordsService$V201109
1.About accessing constants. Did you import AdWordsService? If not you either can access AdWordsService with fully qualified name: some.package.name.AdWordsService/V201109/CAMPAIGN_SERVICE, or import it via import macro.
2.Check examples here: http://clojuredocs.org/clojure_core/clojure.core/reify
(defn campaign-service [ ]
(reify
com.google.adwords.api.v201109.cm.CampaignServiceInterface
(get [_ selector] (some-function selector))
(mutate [_ operations] (some-function-2 operations))))

In common-lisp how can i override/change evaluation behaviour for a specific type of object?

In common-lisp, I want to implement a kind of reference system like this:
Suppose that I have:
(defclass reference () ((host) (port) (file)))
and also I have:
(defun fetch-remote-value (reference) ...) which fetches and deserializes a lisp object.
How could I intervene in the evaluation process so as whenever a reference object is being evaluated, the remote value gets fetched and re-evaluated again to produce the final result?
EDIT:
A more elaborate description of what I want to accomplish:
Using cl-store I serialize lisp objects and send them to a remote file(or db or anything) to be saved. Upon successful storage I keep the host,port and file in a reference object. I would like, whenever eval gets called on a reference object, to first retrieve the object, and then call eval on the retrieved value. Since a reference can be also serialized in other (parent) objects or aggregate types, I can get free recursive remote reference resolution by modyfing eval so i dont have to traverse and resolve the loaded object's child references myself.
EDIT:
Since objects always evaluate to themselves, my question is a bit wrongly posed. Essentially what I would like to do is:
I would like intercept the evaluation of symbols so that when their value is an object of type REFERENCE then instead of returning the object as the result of the symbol evaluation, to return the result of (fetch-remote-value object) ?
In short: you cannot do this, except by rewriting the function eval and modifying your Lisp's compiler. The rules of evaluation are fixed Lisp standard.
Edit After reading the augmented question, I don't think, that you can achieve full transperency for your references here. In a scenario like
(defclass foo () (reference :accessor ref))
(ref some-foo)
The result of the call to ref is simply a value; it will not be considered for evaluation regardless of its type.
Of course, you could define your accessors in a way, which does the resolution transparently:
(defmacro defresolver (name class slot)
`(defmethod ,name ((inst ,class))
(fetch-remote-reference (slot-value inst ',slot))))
(defresolver foo-reference foo reference)
Edit You can (sort of) hook into the symbol resolution mechanism of Common Lisp using symbol macros:
(defmacro let-with-resolution (bindings &body body)
`(symbol-macrolet ,(mapcar #'(lambda (form) (list (car form) `(fetch-aux ,(cadr form)))) bindings) ,#body))
(defmethod fetch-aux ((any t)) any)
(defmethod fetch-aux ((any reference)) (fetch-remote-reference any))
However, now things become pretty arcane; and the variables are no longer variables, but magic symbols, which merely look like variables. For example, modifying the content of a variable "bound" by this macro is not possible. The best you can do with this approach is to provide a setf expansion for fetch-aux, which modifies the original place.
Although libraries for lazy evaluatione and object persistence bring you part of the way, Common Lisp does not provide a portable way to implement fully transparent persistent values. Lazy or persistent values still have to be explicitly forced.
MOP can be used to implement lazy or persistent objects though, with the slot values transparently forced. It would take a change in the internals of the Common Lisp implementations to provide general transparency, so you could do e.g. (+ p 5) with p potentially holding a persistent or lazy value.
It is not possible to directly change the evaluation mechanisms. You would need to write a compiler for your code to something else. Kind of an embedded language.
On the CLOS level there are several ways to deal with it:
Two examples:
write functions that dispatch on the reference object:
(defmethod move ((object reference) position)
(move (dereference reference) position))
(defmethod move ((object automobile) position)
...))
This gets ugly and might be automated with a macro.
CHANGE-CLASS
CLOS objects already have an indirection, because they can change their class. Even though they may change their class, they keep their identity. CHANGE-CLASS is destructively modifying the instance.
So that would make it possible to pass around reference objects and at some point load the data, change the reference object to some other class and set the slots accordingly. This changing the class needs to be triggered somewhere in the code.
One way to have it automagically triggered might be an error handler that catches some kinds of errors involving reference object.
I would add a layer on top of your deserialize mechanism that dispatches based on the type of the incoming data.