Rename function in a specific package on Common Lisp - import

I want to use the package cl-ppcre and series directly on my common lisp environment. I use sly, so in my slynkrc I add this code:
(setf (cdr (assoc '*print-length* slynk:*slynk-pprint-bindings*)) 20)
(setf *print-length* 20)
(setf *evaluator-mode* :interpret)
(ql:quickload '(:alexandria
:cl-ppcre
:cl-interpol
:series
:cl-actors
:chanl
:lparallel))
(eval-when (:compile-toplevel :execute :load-toplevel)
(series::install))
(defun λ-reader (stream char)
(declare (ignore char stream))
'LAMBDA)
(set-macro-character #\λ #'λ-reader)
(use-package :cl-ppcre)
(use-package :cl-interpol)
(interpol:enable-interpol-syntax)
The problem with this is whith the symbol function split. that is in both packages defined.
#<THREAD "main thread" RUNNING {10005605B3}>:
USE-PACKAGE #<PACKAGE "CL-PPCRE"> causes name-conflicts in
#<PACKAGE "COMMON-LISP-USER"> between the following symbols:
CL-PPCRE:SPLIT, SERIES:SPLIT
See also:
In Scala you can import, Renaming a class, but in this case I can use shadowing import, and import only what I need, what is the best solution for that, and if it is possible to import and rename a function in common lisp

You could maybe do it like this:
(defun alias% (as symbol &key (package *package*))
(when (fboundp symbol)
(setf (symbol-function as) (symbol-function symbol)))
(when (boundp symbol)
(setf (symbol-value as) (symbol-value symbol)))
(setf (symbol-plist as) (symbol-plist symbol))
;; maybe also documentation of all types
(shadowing-import as package))
(defmacro defalias (as symbol &key (package *package*))
`(eval-when (:compile-toplevel :load-toplevel :execute)
(alias% ',as ',symbol :package ,package)))
Then you can do:
(defalias foo cl:list)
(foo 1 2 3) ; => (1 2 3)

Looking at the doc on CLtL2, I'd say there is no macro to do that. Please prove me wrong.
Maybe the following works ? I didn't test properly edit: it doesn't work as is.
(use-package :cl-ppcre)
(setf (fdefinition 're-split) #'split) ;; create an alias
(unintern 'split)
(use-package :series)
And now use re-split and split.

Related

Is there any way to see the implementations of built-in macros in Common Lisp?

Common Lisp built-in functions are probably implemented in C. But I imagine macros are implemented in lisp (sorry if I'm wrong about any of two sentences). Is there any way (through some function or some macro) to see the implementations of built-in macros in Common Lisp? I'm using CLisp.
The ability to inspect function and macro definitions is a feature of your development environment. These days it is typical to use SLIME or SLY with emacs as the basis of a Lisp development environment. I personally use SLIME, but I have heard good things about SLY, too.
In SLIME you can invoke slime-edit-definition (either by keying M-x slime-edit-definition or by using the keybinding M-.) to visit a definition for the symbol under the cursor in a source file. This works both when editing in a source file, or from the REPL. This feature is extremely useful when you want to inspect some library code you are working with, but you can also view a lot of built-in definitions this way. You can even jump to a new definition from a new symbol found in whatever definition you are currently inspecting.
After you are done looking at a definition, you can use M-x slime-pop-find-definition-stack, or the easier to remember keybinding M-, (M-* will also work), to back out through the previously viewed definitions, eventually returning to your starting point.
Here is an example, in SBCL:
CL-USER> with-open-file[press M-.]
(Note that the "[press M-.]" above is not typed, but only meant to remind what action is taken here). With the cursor on or right after the symbol with-open-file, press M-. to see the definition:
(sb-xc:defmacro with-open-file ((stream filespec &rest options)
&body body)
(multiple-value-bind (forms decls) (parse-body body nil)
(let ((abortp (gensym)))
`(let ((,stream (open ,filespec ,#options))
(,abortp t))
,#decls
(unwind-protect
(multiple-value-prog1
(progn ,#forms)
(setq ,abortp nil))
(when ,stream
(close ,stream :abort ,abortp)))))))
This time after keying M-. SLIME gives a choice of definitions to view:
CL-USER> and[press M-.]
Displayed in an emacs buffer:
/path-to-source/sbcl-2.0.4/src/code/macros.lisp
(DEFMACRO AND)
/path-to-source/sbcl-2.0.4/src/pcl/ctypes.lisp
(DEFINE-METHOD-COMBINATION AND)
We want to see the macro definition, so move the cursor to the line showing (DEFMACRO AND), and the following definition is displayed:
;; AND and OR are defined in terms of IF.
(sb-xc:defmacro and (&rest forms)
(named-let expand-forms ((nested nil) (forms forms) (ignore-last nil))
(cond ((endp forms) t)
((endp (rest forms))
(let ((car (car forms)))
(cond (nested
car)
(t
;; Preserve non-toplevelness of the form!
`(the t ,car)))))
((and ignore-last
(endp (cddr forms)))
(car forms))
;; Better code that way, since the result will only have two
;; values, NIL or the last form, and the precedeing tests
;; will only be used for jumps
((and (not nested) (cddr forms))
`(if ,(expand-forms t forms t)
,#(last forms)))
(t
`(if ,(first forms)
,(expand-forms t (rest forms) ignore-last))))))
There is more stuff here, since you are now actually in the source file that contains the definition for and; if you scroll down a bit you can also find the definition for or.
A lot of SBCL functions are written in Lisp; SBCL has a very high-quality compiler, so a lot of stuff that you might otherwise expect to be written in C can be written in Lisp without loss of performance. Here is the definition for the function list-length:
CL-USER> list-length[press M-.]
(defun list-length (list)
"Return the length of the given List, or Nil if the List is circular."
(do ((n 0 (+ n 2))
(y list (cddr y))
(z list (cdr z)))
(())
(declare (type fixnum n)
(type list y z))
(when (endp y) (return n))
(when (endp (cdr y)) (return (+ n 1)))
(when (and (eq y z) (> n 0)) (return nil))))
The same thing can be done when using CLISP with SLIME. Here is with-open-file as defined in CLISP:
CL-USER> with-open-file[press M-.]
(defmacro with-open-file ((stream &rest options) &body body)
(multiple-value-bind (body-rest declarations) (SYSTEM::PARSE-BODY body)
`(LET ((,stream (OPEN ,#options)))
(DECLARE (READ-ONLY ,stream) ,#declarations)
(UNWIND-PROTECT
(MULTIPLE-VALUE-PROG1
(PROGN ,#body-rest)
;; Why do we do a first CLOSE invocation inside the protected form?
;; For reliability: Because the stream may be a buffered file stream,
;; therefore (CLOSE ,stream) may produce a disk-full error while
;; writing the last block of the file. In this case, we need to erase
;; the file again, through a (CLOSE ,stream :ABORT T) invocation.
(WHEN ,stream (CLOSE ,stream)))
(WHEN ,stream (CLOSE ,stream :ABORT T))))))
But, many CLISP functions are written in C, and those definitions are not available to inspect in the same way as before:
CL-USER> list-length[press M-.]
No known definition for: list-length (in COMMON-LISP-USER)

Certain functions not loading into repl

Working through Little Schemer,
We're required to define a few of our own functions.
I've defined them, only add1 and sub1 appear in the repl after it loads. I'm using Racket v7.0.
#lang racket
(provide atom? add1 sub1)
(define atom?
(lambda (x)
(and (not (pair? x)) (not (null? x)))))
(define add1
(lambda (x)
(+ x 1)))
(define sub1
(lambda (x)
(- x 1)))
I cannot figure out why (atom?) does not load. When I copy paste the s-expression into repl it works. Any ideas?
Since you are unsing #lang racket and provide the correct way to use the file is with require.
$ ls
toys.rkt
$ racket
Welcome to Racket v6.8.
> (require "toys.rkt")
> (atom? '())
#f
So imagine you make a program like this:
#lang racket
(require "toys.rkt")
(if (atom? 'test)
'atom
'no-atom)
You save it and run it:
$ racket program.rkt
'atom
Also note that you can use R6RS and make toys a library. You then need to use plt-r6rs --install toys.rkt and then use (import (rnrs base) (toys)).

How to get a function/macro definition from CL REPL?

I've got another question involving self-reference in Common Lisp. I found a thread on Stack Exchange which poses a problem of writing the shortest program that would print all printable ASCII characters NOT present in the program's source code. This got me thinking how to tackle the problem in Common Lisp. I hit against two problems - one probably trivial, the other more tricky:
First is the case of writing a CL script, e.g. starting with #!/usr/bin/env sbcl --script. I thought that through *posix-argv* I could access all command line arguments including the name of the called script. I also looked for the equivalent of Bash $0 but could find none. What worked for me in the end is this ugly Bash-ified SBCL script, which explicitly passes $0 to SBCL and proceeds from that:
#!/bin/bash
#|
sbcl --script $0 $0
exit
|#
(defun file-string (path)
(with-open-file (stream path)
(let ((data (make-string (file-length stream))))
(read-sequence data stream)
data)))
(let* ((printable (mapcar #'code-char (loop for i from #x20 to #x7e collect i)))
(absent (set-difference
printable
(coerce (file-string (cadr *posix-argv*)) 'list))))
(print (coerce absent 'string)))
My question regarding this point is: can you think of any way of doing it without relying so heavily on Bash supplying relevant arguments? Or, more briefly: is there a CL (SBCL in particular) equivalent of $0?
Now comes the part that I'm totally puzzled with. Before resorting to the script approach above I tried to accomplish this goal in a more REPL-oriented way. Based on the &whole specifier in defmacro and considerations in this thread I've tried to get the name of the macro from the &whole argument and somehow "read in" its source. And I have absolutely no idea how to do it. So in short: given the name of the macro, can I somehow obtain the defmacro form which defined it? And I'm talking about a generic solution, rather than parsing the REPL history.
EDIT: Regarding mbratch's question about use of macroexpand-1 here's how I do it:
(defmacro self-refer (&whole body)
(macroexpand-1 `',body))
With this call I'm able to obtain (SELF-REFER) by calling (SELF-REFER). Which isn't much of a solution...
I hope someone could point me in the right direction. Thanks!
Getting the source of a macro is not defined in Common Lisp.
This may work (Example from LispWorks):
CL-USER 10 > (defmacro foo (a b) `(* (+ ,a ,b) (+ ,a ,a)))
FOO
CL-USER 11 > (pprint (function-lambda-expression (macro-function 'foo)))
(LAMBDA
(DSPEC::%%MACROARG%% #:&ENVIRONMENT1106 &AUX (#:&WHOLE1107 DSPEC::%%MACROARG%%)
(#:\(A\ ...\)1108 (CDR #:&WHOLE1107))
(#:CHECK-LAMBDA-LIST-TOP-LEVEL1110
(DSPEC::CHECK-LAMBDA-LIST-TOP-LEVEL '(A B)
#:&WHOLE1107
#:\(A\ ...\)1108
2
2
'NIL
:MACRO))
(A (CAR (DSPEC::THE-CONS #:\(A\ ...\)1108)))
(#:\(B\)1109 (CDR (DSPEC::THE-CONS #:\(A\ ...\)1108)))
(B (CAR (DSPEC::THE-CONS #:\(B\)1109))))
(DECLARE (LAMBDA-LIST A B))
(BLOCK FOO `(* (+ ,A ,B) (+ ,A ,A))))
An even more esoteric way is to alter the existing DEFMACRO to record its source.
Many Lisp implementations have a non-standard feature called advising. LispWorks for example can advise macros:
CL-USER 31 > (defadvice (defmacro source-record-defmacro :after)
(&rest args)
(setf (get (second (first args)) :macro-source) (first args)))
T
Above adds code to the standard DEFMACRO macro, which records the source on the symbol property list of the macro name. defmacro is the name of the thing to advise. source-record-defmacro is the chosen name of this advice. :after then specifies that the code should run after the normal defmacro code.
CL-USER 32 > (defmacro foo (a b) `(* (+ ,a ,b) (+ ,a ,a)))
FOO
CL-USER 33 > (pprint (get 'foo :macro-source))
(DEFMACRO FOO (A B) `(* (+ ,A ,B) (+ ,A ,A)))
Again, this is completely non-standard - I'm not sure if a comparable mechanism exists for SBCL, though it has something called 'encapsulate'.
A very belated followup to Rainer Joswig's LispWorks solution. I've been using Allegro CL lately and discovered the fwrap facility. Conceptually it's very similar to the defadvice above and slighly more verbose. Here's a re-iteration of Rainer's example in ACL 10.0:
(def-fwrapper source-record-defmacro (&rest args)
(setf (get (second (first args)) :macro-source) (first args))
(call-next-fwrapper))
Having defined an fwrapper you need to "put it into action" explicitly:
(fwrap 'defmacro 'srd 'source-record-defmacro)
After this it's like in Rainer's example:
CL-USER> (defmacro foo (a b) `(* (+ ,a ,b) (+ ,a ,a)))
FOO
CL-USER> (pprint (get 'foo :macro-source))
(DEFMACRO FOO (A B) `(* (+ ,A ,B) (+ ,A ,A)))
; No value

Is there a function included with Emacs to recursively walk the directory structure and call a function?

I would like to recursively walk down the directory structure from a particular point and call copyright-update-directory at each level.
Is there a function included with Emacs 24 that would help with this? For example something like:
(recursive-directory-walk "~/src/foo" '(copyright-update-directory))
If no such function exists, some pointers on getting started implementing this (or a working implementation) would be great.
The f.el library (github) on MELPA contains functions for filesystem traversal.
(mapc 'copyright-update-directory (f-directories "~/path" nil t))
This will descend the directory hierarchy recursively. See the documentation for f-directories.
Not sure if exists, but not very hard to write your own.
(defun folder-dirs (folder)
(delete-if-not 'file-directory-p
(mapcar (lambda(arg) (file-name-as-directory (concat (file-name-as-directory folder) arg)))
(delete-if (lambda (arg) (or (string= ".." arg) (string= "." arg)))
(directory-files folder)))))
(defun recursively-run-on-every-dir (fn folder)
"FN - function, taking one argument;
FOLDER - initial forder"
(funcall fn folder)
(mapc (lambda(arg) (recursively-run-on-every-dir fn arg))
(folder-dirs folder))
nil)
;; use your function instead of print
(recursively-run-on-every-dir 'print "/your/initial/path/")
Just use find-lisp
(require 'find-lisp)
;; a simple function, just to test
(defun my-funct (x)
(princ x)
(terpri))
(mapc 'my-funct (find-lisp-find-files "~/src/foo/" "\\.txt$"))
Emacs has the build-in function directory-files-recursively for this purpose:
(mapc #'YOUR-FUNCTION
(remove-if-not
#'file-directory-p ;only dirs
(directory-files-recursively YOUR-DIRECTORY "" t)))
It's also much faster than the f-directories function mentioned in the other answer because it doesn't use recursion internal.
I think Chris Barrett's answer is the correct and idiomatic one. However, for learning purposes i wanted to implement Python's os.walk, a general function for breadth-first traversing of directory trees. I used dash.el list library and f.el file and directory libraries. This is a stack-based implementation translated from Python.
(defun walk (path)
(let ((stack (list (f-full path)))
result)
(while stack
(let* ((path (pop stack))
(ds_ (f-directories path))
(ds (-map 'f-relative ds_))
(fs (-map 'f-relative (f-files path))))
(--each ds_ (!cons it stack))
(!cons (list path ds fs) result)))
(reverse result)))
See functions: f-full, pop, f-directories, f-relative, f-files, --each, !cons, reverse. Now you can use it in loops the same you would use it in Python:
(loop for (b ds fs) in (walk path)
do (copyright-update-directory b "*"))

How can I find out which version of emacs introduced a function?

I want to write a .emacs that uses as much of the mainline emacs functionality as possible, falling back gracefully when run under previous versions. I've found through trial and error some functions that didn't exist, for example, in emacs 22 but now do in emacs 23 on the rare occasion that I've ended up running my dotfiles under emacs 22. However, I'd like to take a more proactive approach to this, and have subsets of my dotfiles that only take effect when version >= <some-threshold> (for example). The function I'm focusing on right now is scroll-bar-mode but I'd like a general solution.
I have not seen a consistent source for this info; I've checked the gnu.org online docs, the function code itself, and so far nothing. How can I determine this, without keeping every version of emacs I want to support kicking around?
I cannot answer your question directly, but one technique I use is to check the functionp function that tells me if a function exists.
e.g.
(if (load "completion" t)
(progn
(initialize-completions)
(if (functionp 'dynamic-completion-mode)
(dynamic-completion-mode) ; if exists
(completion-mode) ; otherwise use old version
)
) ; progn
) ; if
update: adding version specific macros
In addition to using functionp I also have some version specific macros:
(defmacro GNU_EMACS_21 (&rest stuff)
(list 'if (string-match "GNU Emacs 21" (emacs-version)) (cons 'progn stuff)))
(defmacro GNU_EMACS_20 (&rest stuff)
(list 'if (string-match "GNU Emacs 20" (emacs-version)) (cons 'progn stuff)))
(defmacro GNU_EMACS_19 (&rest stuff)
(list 'if (string-match "GNU Emacs 19" (emacs-version)) (cons 'progn stuff)))
(defmacro WINSYS_X (&rest stuff)
(list 'if (eq window-system 'x) (cons 'progn stuff)))
(defmacro WINSYS_W32 (&rest stuff)
(list 'if (eq window-system 'w32) (cons 'progn stuff)))
(defmacro WINSYS_NIL (&rest stuff)
(list 'if (eq window-system nil) (cons 'progn stuff)))
(defmacro SYSTYPE_LINUX (&rest stuff)
(list 'if (string-match "linux" (symbol-name system-type)) (cons 'progn stuff)))
I can then use these:
(GNU_EMACS_21
(if (load "cua" t)
(CUA-mode t)
)
)
(WINSYS_NIL ; when running in text mode
(push (cons 'foreground-color "white") default-frame-alist)
(push (cons 'background-color "black") default-frame-alist)
(push (cons 'cursor-color "cyan") default-frame-alist)
(push (cons 'minibuffer t) default-frame-alist)
)
I'm guessing you already know this, however; and questions like "when did CUA mode get included with Emacs" are difficult to answer..
The "NEWS" files (accessible via C-h N) may give hints as to when functions were introduced.
It's usually better practice to test the existence of the function or variable you want to use, rather than test the Emacs version. Use fboundp and boundp, for example. Occasionally it makes sense to check featurep, but there again it is usually better to use fboundp or boundp.