ラベル CommonLisp の投稿を表示しています。 すべての投稿を表示
ラベル CommonLisp の投稿を表示しています。 すべての投稿を表示

2015年6月10日水曜日

[CommonLisp]ABCLでクラスファイルを作る

jnew-runtime-classを参考にしました。
(in-package :jvm)

(defun make-empty-class-file (class-name &optional (super-name "java.lang.Object"))
  (make-class-file (make-jvm-class-name class-name)
                   (make-jvm-class-name super-name)
                   '(:public)))

(defun create-class-bytes (class-file)
  (let ((stream (sys::%make-byte-array-output-stream)))
    (write-class-file class-file stream)
    (finish-output stream)
    (sys::%get-output-stream-bytes stream)))

(defun write-class-bytes (fname bytes)
  (with-open-file (f fname :direction :output :element-type '(unsigned-byte 8))
    (let ((n (java:jarray-length bytes)))
      (dotimes (i n)
        (write-byte (mod (java:jarray-ref bytes i) 256) f)))))

(defun create-helloworld-class (class-name fname)
  (let ((class-file (make-empty-class-file class-name)))
    (let* ((string-array-class (class-array (make-jvm-class-name "java.lang.String")))
           (method (make-jvm-method "main" :void `(,string-array-class) :flags '(:public :static))))
      (class-add-method class-file method)
      (with-code-to-method (class-file method)
        (emit-getstatic "java.lang.System" "out" (make-jvm-class-name "java.io.PrintStream"))
        (emit 'ldc (pool-string "Hello,World"))
        (emit-invokevirtual "java.io.PrintStream"
                            "println"
                            `(,(make-jvm-class-name "java.lang.String"))
                            :void)
        (emit 'return))
      (finalize-class-file class-file)
      (write-class-bytes fname (create-class-bytes class-file)))))


(create-helloworld-class "AbclHelloWorld" "AbclHelloWorld.class")
> java AbclHelloWorld
Hello,World

2014年7月17日木曜日

[Common Lisp] 多次元配列に対するmap

多次元配列の各要素に対して関数を適用した結果を返すmap系関数を作成する場合、 make-arrayに:displaced-toキーワードを指定して作成したベクターに対してmap-intoを使うと簡潔に書けそうです。

(defun map-array! (fn array)
  (let ((v (make-array (array-total-size array) :displaced-to array)))
    (map-into v fn v))
  array)

(asdf:load-system :alexandria)
(map-array! #'1+ (alexandria:copy-array #2A((1 2) (3 4))))
;; => #2A((2 3) (4 5))

以下、初めて知った多次元配列関連の関数

  • row-major-aref
  • array-row-major-index

2013年12月21日土曜日

ABCLでApache POIを使う

ABCLはJVM上で動作するCommon Lisp処理系なので、Javaのライブラリが利用できます。

(require :abcl-contrib)
(require :abcl-asdf)

(asdf:defsystem apache-poi
  :components ((:mvn "org.apache.poi/poi/3.8")
               (:mvn "org.apache.poi/poi-ooxml/3.8")))

(asdf:load-system 'apache-poi)

(defpackage :test-poi
  (:use :cl :jss))

(in-package :test-poi)

(defun create-9x9 (path)
  (let* ((wb (new 'xssfworkbook))
         (sh (#"createSheet" wb)))
    (dotimes (i 9)
      (#"createRow" sh i))
    (dotimes (i 9)
      (dotimes (j 9)
        (#"setCellValue" (#"createCell" (#"getRow" sh j) i)
                         (format nil "~A" (* (1+ i) (1+ j))))))
    (#"write" wb (new 'fileoutputstream path))))

(create-9x9 "test.xlsx")

2013年12月20日金曜日

ABCLでClojureっぽい記法でJavaと連携


gistに書きました。

ABCLはJVM上で動作するCommon Lisp処理系ですが、Javaの機能を呼び出す方法が面倒くさいかんじなのでClojure風の記法でアクセスできるようにするリーダマクロを書いてみました。


2013年12月3日火曜日

はじめてのアセンブリ(Lisp編)

1 はじめに

( Lisp Advent Calendar 2013 3日目の記事です )
FortranやLispが誕生して50年以上の月日が経過した現在では、 世の大半のプログラムがCやJavaやExcel VBAといった高級言語で作られています。
多くのプログラマにとっては、もはやアセンブリは直接書く必要のないものなのかもしれません。
しかし、(たとえあまり使うことがなくても)Lispを学ぶことで悟りを得られる(らしい)ように、 アセンブリを学ぶことで普段使っているOSやコンパイラやVMが一体何をしているのかを学ぶ手助けとなるのではないかと思います。
低レイヤーもカバーするプログラマを目指して、アセンブリ言語をアセンブラでアセンブルして実行してみましょう。

2 足し算

最初にアセンブラを用意しましょう。ここ(http://ccl.clozure.com/)からダウンロードできます。
現在の最新リリースバージョンは1.9なので、以降の内容は Clozure CL 1.9 (Linux X8664) を前提とします。
アセンブリを書くための作業環境として、パッケージを作成しておきます。
(defpackage asm
  (:use :cl :ccl)
  (:import-from :ccl defx86lapfunction))

(in-package :asm)
まずは2つの整数を加算する関数を書いてみます。
1行ずつ解説もつけてみました。
;; add2という関数を定義します。
;; 引数はaとbで、それぞれレジスタarg_yとarg_zを使って渡します。
;; arg_yとarg_zはそれぞれRDIとRSIの別名です。
(defx86lapfunction add2 ((a arg_y) (b arg_z))
  ;; 引数が2つかどうかチェックします。(lapmacro)
  (check-nargs 2)
  ;; RBPをスタックに積みます(スタックフレーム作成その1)
  (pushq (% rbp))
  ;; RSPをRBPに設定(代入)します(スタックフレーム作成その2)
  (movq (% rsp) (% rbp))
  ;; 引数同士を加算してbに保存します。
  (addq (% a) (% b))
  ;; スタックフレームを復元します(BPをSPにコピー,スタックからpopした値をBPにコピー)
  (leave)
  ;; b(arg_z)に保存した値を戻り値として関数を終了します。
  (single-value-return))

;; 実行します。
(add2 1 2)
;; => 3

3 分岐

条件分岐のサンプルとして、引数が1のときに1を、それ以外の時に0を返す関数を作成します。
アセンブリの条件分岐は、cmp命令やtest命令で比較処理時に設定されるフラグを使った条件付きのジャンプ命令で行います。
(defx86lapfunction one? ((n arg_z))
  (check-nargs 1)
  (pushq (% rbp))
  (movq (% rsp) (% rbp))
  (movq (% n) (% rax))
  ;; 戻り値のデフォルト値として1(1である)を設定します。
  (movq ($ '1) (% arg_z))
  ;; RAXと測値1を比較します。
  (cmpq ($ '1) (% rax))
  ;; RAX==1の時, ENDラベルまでジャンプします。
  (je END)
  ;; (RAX!=1の時) 戻り値に0(1でない)を設定します。
  (movq ($ '0) (% arg_z))
  ;; ENDラベル
  END
  (leave)
  (single-value-return))

;; 実行
(one? 0)
;; => 0
(one? 1)
;; => 1
(one? 2)
;; => 0

4 CPUID

最後にCPUID命令を実行して情報を取得する関数を作成します。
CPUIDはEAXレジスタに取得したい情報の種類を指定して呼び出すと、EAX、EBX、ECX、EDXに情報を格納してくれる命令です。 CPUID(Wikipedia)
引数に取得する情報の種類を取り、4つのレジスタの値を返す関数を作成してみます。
なお、自由に使えるレジスタが少ないっぽいので一旦スタックに積んだりしてます。
(defx86lapfunction cpuid ((operation arg_z))
  ;; 引数の数をチェック
  (check-nargs 1)
  ;; スタックフレーム作成
  (pushq (% rbp))
  (movq (% rsp) (% rbp))
  ;; CPUIDで上書きされてしまうRBXを保存
  (pushq (% rbx))
  ;; CPUIDで取得する情報の種類をRAX(EAX)に保存
  (unbox-fixnum operation rax)
  ;; CPUID命令実行
  (cpuid)
  ;; 呼び出し結果をlispのfixnumに変換
  (box-fixnum rbx rbx)
  ;; 多値で返すためにスタックに積む(2つ目)
  (pushq (% rbx))
  ;; 退避していたRBXの値を復元
  (movq (@ 8 (% rsp)) (% rbx))
  (box-fixnum rax rax)
  ;; 多値で返すためにスタックに積む(1つ目)
  (movq (% rax) (@ 8 (% rsp)))
  (box-fixnum rcx rcx)
  ;; 多値で返すためにスタックに積む(3つ目)
  (pushq (% rcx))
  (box-fixnum rdx rdx)
  ;; 多値で返すためにスタックに積む(4つ目)
  (pushq (% rdx))
  ;; 戻り値の数を設定
  (set-nargs 4)
  ;; 関数を終了して多値を返す
  (jmp-subprim .SPnvalret))
(defun u32->str (n)
  (map 'string
       (lambda (byte) (code-char (ldb byte n)))
       (list (byte 8 0)
             (byte 8 8)
             (byte 8 16)
             (byte 8 24))))

;; 実行
(multiple-value-bind (_ ebx ecx edx) (cpuid 0)
  (format nil "~A~A~A"
          (u32->str ebx)
          (u32->str edx)
          (u32->str ecx)))
;; => "GenuineIntel"
※ Lisp Advent Calendar 2日目でタグの話題がありましたが、CCLはポインタにタグが付いてるタイプのLispです。 なので、Lisp側から整数の1を渡したつもりでも機械語としてはタグの分(ここでは3bit)ずれた値になってしまいます。 box/unboxはこのずれを補正するための処理で、実際には掛け算やシフトが行われています。

5 おわりに

あせんぶりとりすぷがあわさりさいきょうにみえる

6 メモ書き

  • 測値を指定する際にクオートをつけるとlispのfixnum、付けないと機械語の整数になるっぽい
  • 引数が4つ以上になるとスタックを使わなければならない
  • レジスタの別名は compiler/X86/X8664/x8664-arch.lisp で定義されている
  • (:^ lab) : label address expression
  • sar: Shift Arithmetic Right
  • lea: load effective address
  • leave: high level procedure exit (BPをSPにコピー,スタックからpopした値をBPにコピー)
  • disassembleすると出てくる (lea (@ disp (% rip)) (% fn))は、関数のポインタに関数を表すタグ(7)をつけた値をfnレジスタに設定する処理らしい。この命令のバイト数が7になることを利用しているっぽい。

2013年9月29日日曜日

[Common Lisp] 破壊的な関数

Common Lispには、戻り値を作り出すために元々の構造を破壊する関数があります。

sort、stable-sort を除く破壊的な関数には対応する非破壊的な関数があるので、基本的には非破壊版を利用しておいたほうが良さそうです。

なお、破壊的関数の先頭に付く n は non-consing の略だそうです。

詳しくは 実践Common Lispの12章 あたりを見ると良いでしょう。

非破壊的破壊的概要
sortソート
stable-sort安定ソート
reversenreverseリストの反転
appendnconcリストの結合
revappendnreconcリストの結合
butlastnbutlastリストの末尾以外取得
removedeleteシーケンスの要素削除
remove-ifdelete-if条件に一致する要素削除
remove-if-notdelete-if-not条件に一致しない要素削除
remove-duplicatesdelete-duplicates重複を削除
unionnunion和集合
intersectionnintersection積集合
set-differencenset-difference差集合
set-exclusive-ornset-exclusive-or対称差
string-capitalizenstring-capitalize単語の先頭を大文字、それ以外を小文字に変換
string-downcasenstring-downcase文字列を小文字に変換
string-upcasenstring-upcase文字列を大文字に変換
substnsubst木構造(リスト)の要素を変更
subst-ifnsubst-if木構造(リスト)の要素を変更
subst-if-notnsubst-if-not木構造(リスト)の要素を変更
sublisnsublis木構造(リスト)の要素を変更
substitutensubstituteシーケンスの要素を変更
substitute-ifnsubstitute-ifシーケンスの要素を変更
substitute-if-notnsubstitute-if-notシーケンスの要素を変更

2013年8月29日木曜日

[Common Lisp]iterateのドライバを新しく定義する

Common Lisp Advent Calendar 2012で iterate というloopマクロに似たイテレーションライブラリが紹介されていました。 (iterateを使ってloopマクロの呪縛から解き放たれる)

loopマクロと異なり拡張ができるようなので、 OOPのデザインパターンに出てくる(has-next/nextを使った)イテレーターパターンっぽいコードでループできるようにしてみました。

;; イテレーターパターンっぽいインターフェースと実装を定義
;; iterator-next メソッドと has-next-p メソッドを実装したクラスを定義する

(ql:quickload :cl-fad)
(ql:quickload :cl-annot)

(defpackage pattern.iterator
  (:use :cl :cl-annot))

(in-package :pattern.iterator)

(enable-annot-syntax)

@export 
(defgeneric has-next-p (obj))

@export
(defgeneric iterator-next (obj))

@export
(defclass <sequence-iterator> ()
  ((seq :initarg :seq)
   (pos :initarg :pos :initform 0)))

(defmethod has-next-p ((obj <sequence-iterator>))
  (with-slots (seq pos) obj
    (< pos (length seq))))

(defmethod iterator-next ((obj <sequence-iterator>))
  (with-slots (seq pos) obj
    (prog1 (elt seq pos)
      (incf pos))))

@export
(defun sequence-iterator (seq)
  (make-instance '<sequence-iterator> :seq seq))

@export
(defclass <directory-walker> ()
  ((rest :initform nil)))

@export
(defun directory-walker (root)
  (make-instance '<directory-walker> :root root))

(defmethod initialize-instance ((obj <directory-walker>) &key (root "./") &allow-other-keys)
  (call-next-method)
  (push (fad:canonical-pathname root) (slot-value obj 'rest)))

(defmethod has-next-p ((obj <directory-walker>))
  (with-slots (rest) obj
    (not (null rest))))

(defmethod iterator-next ((obj <directory-walker>))
  (with-slots (rest) obj
    (let ((path (pop rest)))
      (when (fad:directory-exists-p path)
        (setf rest (nconc (fad:list-directory path) rest)))
      path)))
;; ドライバの実装
;; iterator-nextとhas-next-pを使ったループをiterateに組み込む。

(ql:quickload "iterate")
(ql:quickload :cl-fad)
(in-package :cl-user)

(defpackage test
  (:use :cl :iterate :pattern.iterator))

(in-package :test)

;; IN-ITERATORというキーワードでイテレータパターン風の処理でループできるように拡張
(defmacro-driver (FOR var IN-ITERATOR obj)
  (let ((gitr (gensym))
        (kwd (if generate 'generate 'for)))
    `(progn
       (with ,gitr = ,obj)
       (while (pattern.iterator:has-next-p ,gitr))
       (,kwd ,var next (pattern.iterator:iterator-next ,gitr)))))
(iter (for x in-iterator (pattern.iterator:sequence-iterator '(1 2)))
      (collect x))
;; => (1 2)

;; 以下のディレクトリ構成で実行
;; ./ (/home/kurohuku/tmp)
;;  |- A.txt
;;  |- B
;;  |  |- B1.txt
;;  |  |- B2.lisp
;;  |- C.txt
(iter (for x IN-ITERATOR (directory-walker "./"))
      (collect x))
;; => (#P"" #P"/home/kurohuku/tmp/A.txt" #P"/home/kurohuku/tmp/B/"
;;     #P"/home/kurohuku/tmp/B/B1.txt" #P"/home/kurohuku/tmp/B/B2.lisp"
;;     #P"/home/kurohuku/tmp/C.txt")

(iter (for x IN-ITERATOR (directory-walker "./"))
      (when (string-equal (pathname-type x) "txt")
        (collect x)))
;; => (#P"/home/kurohuku/tmp/A.txt" #P"/home/kurohuku/tmp/B/B1.txt"
;;     #P"/home/kurohuku/tmp/C.txt")

2013年7月7日日曜日

[Common Lisp] FTPでファイル転送

最近、複数のサーバーのいくつかのディレクトリにファイルを転送する、という作業が必要になりました。

expect + scp(ftp)なシェルスクリプトが作成されましたが、1ファイルごとに接続を行っていて遅かったので python + ftplib で書き直したりしました。

久々に Common Lisp を書こうと思ったので、ftpでの転送処理を題材にしてみます。

1 ライブラリを探す

さすがにftpを実装しようと試みたりはせず、ライブラリを探します。
quicklisp の system-apropos 関数を使ってそれっぽい名前のライブラリを探してみます。

 CL-USER> (ql:system-apropos "ftp")
#<SYSTEM ftp / cl-ftp-20101006-http / quicklisp 2013-06-15>

cl-ftp を使うことにします。

ファイルパスの処理も行いたいです。
組み込みの関数や cl-fad だとパスネームからファイル名+拡張子を取ってくる方法が分からなかったので、 ファイルパスの処理用のライブラリも探してみます。

(ql:system-apropos "path")
#<SYSTEM cl-paths / cl-vectors-20130312-git / quicklisp 2013-06-15>
#<SYSTEM cl-paths-ttf / cl-vectors-20130312-git / quicklisp 2013-06-15>
#<SYSTEM com.gigamonkeys.pathnames / monkeylib-pathnames-20120208-git / quicklisp 2013-06-15>
#<SYSTEM iolib.pathnames / iolib-0.7.3 / quicklisp 2013-06-15>
#<SYSTEM xpath / plexippus-xpath-20120909-darcs / quicklisp 2013-06-15>

iolib.pathnames を使ってみることにします。

ハッシュテーブルのキーと値に対するループ処理を行いたいです。
loopマクロでハッシュテーブルを使おうとすると記述が面倒なので、ユーティリティマクロを定義します。 が、自分で書くのは面倒なのでライブラリを使います。

Common Lispにはユーティリティライブラリがたくさん存在しますが、 今回は最近登場した Quickutil というユーティリティライブラリを使って、 使いたいユーティリティだけを読み込むことにします。

2 コードを書く

;; ** ライブラリ読み込み
;; quicklispで cl-ftp と iolib.pathnames を取得して読み込む。
(ql:quickload :ftp)
(ql:quickload :iolib.pathnames)

;; quickutilを読み込む。
;; 現時点(2013年7月6日)では、まだ quicklisp に登録されていないので、
;; git cloneしたりアーカイブをダウンロードしたりして
;; quicklisp/local-protects の中に保存しておく。
(ql:quickload :quickutil)

;; quickutil を使って dohash マクロと alist-hash-table 関数を読み込む
(qtlc:utilize-utilities '(:dohash :alist-hash-table))


;; ** 実装
(defun make-target-file-name (source-file target-dir)
  (let* ((fname (iolib.pathnames:file-path-file
                 (iolib.pathnames:file-path source-file)))
         (target-fname
           (iolib.pathnames:merge-file-paths fname target-dir)))
    target-fname))

(defun ftp-copy-file (conn file target-dir)
  (let ((target-fname (make-target-file-name file target-dir)))
    (format t " - copy to: ~A~%" target-fname)
    (ftp:store-file conn
                    file
                    (iolib.pathnames:file-path-namestring target-fname))))

;; Emacs: (put 'qtl:dohash 'common-lisp-indent-function 1)
(defun ftp-copy (remote-host copy-info-map &key port username password)
  (ftp:with-ftp-connection (conn :hostname remote-host
                                 :port port
                                 :passive-ftp-p t
                                 :username username
                                 :password password) 
    (format t "connect to [~A]~%" remote-host)
    (qtl:dohash (dir files copy-info-map)
      (dolist (file files)
        (ftp-copy-file conn file dir)))))

;; (転送先ディレクトリ . (転送するファイル ...))
;; リモートの tmp ディレクトリに
;; ローカルのカレントディレクトリにある 1.txt, 2.txt を転送する設定
(defparameter *copy-info-map*
  (qtl:alist-hash-table
   '(("tmp" "1.txt" "2.txt"))
  :test #'equal))

(defparameter *remote-hosts*
  '("localhost"))

(defun run ()
  (dolist (remote-host *remote-hosts*)
    (ftp-copy remote-host *copy-info-map*
              :port 10000
              :username "test"
              :password "test")))

;;  (run)

なお、作業マシンにはftpサーバーを入れてなかったので、 python の pyftpdlib で適当にでっちあげて実行しました。

2012年12月13日木曜日

正規表現を利用して文字列を作成する

( Lisp Advent Calendar 2012 の13日目の記事です)

テストなどのために適当なデータを作成したいことがあります。
この時、データをランダムに作成できると、楽ができる上に 自分の考えていなかった入力パターンから問題を見つけることができて良さそうです。

作成したいデータが数値なら、疑似乱数生成用の関数(rand,randomなど)を使えば事足ります。
文字列を作成したい場合は、正規表現を利用すれば楽ができそうです。

Clojure には、正規表現からその正規表現にマッチするような文字列を作成してくれる re-rand という ライブラリがあります。

[re-rand "0.1.0"]
user> (require [re-rand :as r])

user> (repeatedly 3 #(r/re-rand #"\d{4}/\d{2}/\d{2} \d\d:\d\d:\d\d"))
("7511/27/85 13:37:43" "6728/87/88 96:68:15" "1536/63/37 90:23:02")

user> (repeatedly 3 #(r/re-rand #"[0-9零一二三四五六七八九]{1,10}"))
("六二零七" "1七8" "二三七八一2八1")

Common Lisp には・・・と思って調べて見ましたが、見つけることができませんでした。 仕方ないので自分で作りましょう。

幸い、一番大変そうな正規表現のパースは cl-ppcre の parse-string 関数で行えます。

(asdf:load-system :cl-ppcre)

(defpackage :random-string
  (:use :cl)
  (:export random-string
           *repeat-limit*
           *charset-every*
           *charset-digit*
           *charset-word*
           *charset-whitespace*))

(in-package :random-string)

(defvar *repeat-limit* 64)

(defvar *charset-everything*
  (lambda () (code-char (random 256) )))

(defvar *charset-digit* "0123456789")

(defvar *charset-word*
  (concatenate 'string
   "abcdefghijklmnopqrstuvwxyz"
   "ABCEFGHJIJKLMNOPQRSTUVWXYZ"
   "!\"#$%'()-=^~\\|[]{};:+*,.<>/?_"))

(defvar *charset-whitespace*
  (format nil "%c%c%c" #\space #\newline #\tab))

(defun one-of (obj)
  (if (functionp obj)
      (funcall obj)
      (let ((count (length obj)))
        (elt obj (random count)))))

(defun random-string (regexp)
  (generate (ppcre:parse-string regexp)))

(defmethod generate ((obj string))
  obj)

(defmethod generate ((obj character))
  (string obj))

(defmethod generate ((obj list))
  (generate/list (first obj) (rest obj)))

(defmethod generate ((obj (eql :digit-class)))
  (string (one-of *charset-digit*)))

(defmethod generate ((obj (eql :everything)))
  (string (one-of *charset-everything*)))

(defmethod generate ((obj (eql :whitespace-char-class)))
  (string (one-of *charset-whitespace*)))

(defmethod generate ((obj (eql :word-char-class)))
  (string (one-of *charset-word*)))

(defmethod generate/list ((cls (eql :sequence)) rest)
  (apply #'concatenate 'string (mapcar #'generate rest)))

(defmethod generate/list ((cls (eql :char-class)) rest)
  (string (one-of (mapcar #'generate rest))))

(defmethod generate/list ((cls (eql :range)) rest)
  (string
   (destructuring-bind (from to) rest
     (code-char
      (+ (char-code from)
         (random (1+ (- (char-code to) (char-code from)))))))))

(defmethod generate/list ((cls (eql :INVERTED-CHAR-CLASS)) rest)
  (error "unsupported expression: INVERTED-CHAR-CLASS"))

(defmethod generate/list ((cls (eql :greedy-repetition)) rest)
  (destructuring-bind (min max gen-cls) rest
    (let ((max (or max (+ min *repeat-limit*))))
      (apply #'concatenate 'string
             (loop :repeat (+ min (random (1+ (- max min))))
                :collect (generate gen-cls))))))

(defmethod generate/list ((cls (eql :register)) rest)
  (apply #'concatenate 'string (mapcar #'generate rest)))

(defmethod generate/list ((cls (eql :alternation)) rest)
  (generate (one-of rest)))

CL-USER> (random-string:random-string "b(an)+a")
"banananananananananananananananana"

CL-USER> (dotimes (_ 3)
           (print (random-string:random-string "[012]\\d{3}-((0[1-9])|(1[12]))-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z")))
"2056-09-58T98:80:10Z" 
"2057-02-82T36:65:58Z" 
"1077-11-18T77:72:22Z"

CL-USER> (dotimes (_ 3)
           (print (random-string:random-string "[\\d零一二三四五六七八九]{1,5}")))

"二二四四" 
"五68" 
"二七"

文字集合の選択などで偏りが出てしまいますが、適当なデータを作成する程度なら十分利用できるかなぁ、と思います。

今回書いたコードでは、やりたいことの9割くらいを正規表現ライブラリのcl-ppcreが行ってくれています。
Lisp使いは「全部自分で書く」みたいなイメージがありますが、 leiningen や Quicklisp を使うとライブラリのインストールは簡単ですし、 やりたいことにマッチするライブラリがあったら、ありがたく使わせてもらいましょう。

2012年12月10日月曜日

Log4CLを使ってみる

( Common Lisp Libraries Advent Calendar の10日目の記事です )

最近やっと実感を得ましたが、(デバッグ)ログは大事ですね。 遠隔地にいるライブラリ製作者とやりとりする回数を減らせます。

ということで、Common Lispでログ出力するライブラリ、Log4CL を眺めてみます。

Log4CL は、CLikiの Current recommended libraries で紹介されています。
JavaのロギングライブラリであるLog4jを参考にして作られているようなので、Java使いの人にとっては使いやすいのかもしれません。

インストールは Quicklisp で行えます。

> (ql:quickload :log4cl)

正確な情報はgithubにあるREADME.mdおよびソースコードを読んで調べて頂くとして、 ざっと概要を説明してみます。

Log4CL は次の3つの構成要素から成ります。

  • ロガー : ログの出力先 (論理的)
  • アペンダ : ログの出力先(出力方法) (コンソール出力・ファイル出力など)
  • レイアウト : ログ出力の整形方法

論理的な出力先であるロガーに、実際の出力方法を定義したアペンダを対応づけ、 レイアウトで指定されたフォーマットでログを出力します。

ログレベルは、 fatal,error,warn,info,debug, user1 ~ user4, trace, user5 ~ user9 の15段階が指定できます。 ログレベルの名前に対応する出力関数(マクロ)が定義されています。

CL-USER> (log:fatal "fatal error")
[22:57:21] [fatal] <cl-user> - fatal error

CL-USER> (log:info "hello")
[22:57:51] [info] <cl-user> - hello

1文字の省略形も定義されています。

CL-USER> (log:i "helo")
[22:59:26] [info] <cl-user> - helo

CL-USER> (log:w "w")
[23:00:10] [warn] <cl-user> - w

「<cl-user>」 は現在のパッケージ名です。 ロガーを指定しない場合、デフォルトでカレントパッケージの名前がロガーとして利用されます。

ロガーの作成はmake-logger関数、あるいはmake関数で行えます。
ロガーは親子関係を持ちますが、キーワードシンボルを指定すると 親=カレントパッケージ名, 子=シンボル名 という 構造が作成されるようです。

ログ出力関数でロガーを指定する場合は、名前(シンボル)を直接指定するほうが短くて良さそうです。

CL-USER> (log:w (log:make-logger :child) "w")
[23:02:41] [warn] <cl-user:child> - w

CL-USER> (log:f (log:make-logger '(parent child)) "f")
[23:03:13] [fatal] <parent:child> - f

CL-USER> (log:e :child "e")
[23:04:17] [error] <cl-user:child> - e

ロガーが出力するログレベルを設定するには、 config 関数を使います。省略形は c です。
なお、親ロガーの設定を引き継ぐよう設定するには、:unsetを指定すれば良いようです。 デフォルトの設定は :unset です。

CL-USER> (log:debug "hoge")
; No value
CL-USER> (log:c :d)  ;; (log:config :debug) と同等
CL-USER> (log:debug "hoge")
[23:13:02] [debug] <cl-user> - hoge

ログレベルに対応する出力処理以外に、評価前の式と評価後の値を出力する expr 関数があります。 処理系が SBCL の場合は、どの関数の中でログが出力されたかまでロガー名に含めてくれるようです。

(defun foo (a)
           (flet ((bar (b)
                    (log:expr a b (+ a b))))
             (bar 10)))
(log:config :debug)

;; CCL
CL-USER> (foo 2)
[23:17:57] [debug] <cl-user> - A=2 B=10 (+ A B)=12 

;; SBCL
CL-USER> (foo 2)
[23:17:06] [debug] <cl-user:foo:bar> - A=2 B=10 (+ A B)=12 

その他、アペンダやレイアウトの対応づけや設定ファイルの読み込み等が可能ですが、 README.md 以上に有益なことを書ける気がしないので、ドキュメントにかかれていない アペンダの定義を行い、syslogにログを出力してみます。

(ql:quickload :cl-syslog)

;; アペンダを定義
(defclass syslog-appender (log4cl-impl:appender)
  ())

;; アペンダの出力方法を定義
(defmethod log4cl-impl:appender-do-append ((appender syslog-appender) logger level log-func)
  ;; 出力はcl-syslogに丸投げ。
  (cl-syslog:log "log4cl" :local7 :info
    (with-output-to-string (s)
      (log4cl-impl:layout-to-stream
       (slot-value appender 'log4cl-impl:layout) s logger level log-func))))

;; ロガーを作成
(defvar syslog-logger (log:make '(syslog)))

;; ロガーにアペンダを対応付ける
(log:add-appender syslog-logger (make-instance 'syslog-appender))

;; ログ出力
(log:i syslog-logger "from cl")
kurohuku@mypc:/var/log$ tail -1 syslog
Dec 10 23:49:36 mypc log4cl: INFO - from cl

Log4jと異なりデフォルトで定義されてるアペンダは少ないので、 コンソールやファイル以外に出力を行いたい場合は自分でアペンダを定義する必要がありますが、 expr関数(マクロ)などはデバッグに便利ですし、試しに使ってみると良いと思います。

なお、Quicklispで (ql:system-apropos "log") でライブラリを検索したところ、 他にもロギングライブラリっぽいものが見つかりました。

  • cl-log
  • hu.dwim.logger
  • log5
  • logv
  • (cl-syslog)
  • (irc-logger)

・・・見つかりましたが、数が多いので比較はしません。ごめんなさい。

2012年11月10日土曜日

オイラーの贈物(1.2)とLispと順列

二項展開(binomial expansion)の展開後の各項の係数(二項係数(binomial coefficient))は 階乗(factorial)を利用して以下の用に書けます。

${}_n C _r \equiv \frac{n!}{r!(n - r)!}$
latexの数式
${}_n C _r \equiv \frac{n!}{r!(n - r)!}$
;; Common Lisp

(defun recursive-factorial (n)
  (check-type n (integer 0 *))
  (if (zerop n)
      1
      (* n (recursive-factorial (1- n)))))

(defun factorial (n)
  (check-type n (integer 0 *))
  (if (zerop n)
      1
      (loop
         :named loop
         :for i from 1 to n
         :for result = i then (* i result)
         :finally (return-from loop result))))

(defvar *memoized-factorial* (make-hash-table))
(setf (gethash 0 *memoized-factorial*) 1)
(setf (gethash 1 *memoized-factorial*) 1)
(defun memoized-factorial (n)
  (check-type n (integer 0 *))
  (let ((x (gethash n *memoized-factorial*)))
    (if x
        x
        (let ((y (* n (memoized-factorial (1- n)))))
          (setf (gethash n *memoized-factorial*) y)
          y))))

(defun binomial-coefficient (n r)
  (check-type n (integer 0 *))
  (check-type r (integer 0 *))
  (assert (<= r n))
  ;; n! / r!(n - r)!
  (/ (memoized-factorial n)
     (* (memoized-factorial r)
        (memoized-factorial (- n r)))))

この式はn個の中からr個を取る組み合わせ(combination)の数を求める式でもあります。

要素の順番も考慮する順列(permutation)の数の場合は、以下のようになります。

${}_n P _r \equiv \frac{n!}{(n - r)!}$
latexの数式
$ {}_n P _r \equiv \frac{n!}{(n - r)!}$
(defun permutation (n r)
  (check-type n (integer 0 *))
  (check-type r (integer 0 *))
  (assert (<= r n))
  ;; n! / (n - r)!
  (/ (memoized-factorial n)
     (memoized-factorial (- n r))))

多くのプログラミング言語では順列を生成するための機能が用意されているようです。

RubyのArrayクラス(array.cで定義)とC++のstd::next_permutationを使ってみます。

> p [1, 2, 3].permutation(2).to_a
[[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]]

## nPr = 3P2 = 3! / (3-2)! = 3! = 6
> p [1, 2, 3].permutation(2).to_a.size
6

> p [1, 2, 3].combination(2).to_a
[[1, 2], [1, 3], [2, 3]]

## nCr = 3C2 = 3! / 2!(3-2)! = 3! / 2 = 3
> p [1, 2, 3].combination(2).to_a.size
3
#include <algorithm>
#include <cstdio>

void print_array(int arr[3]){
        printf("%d, %d, %d\n", arr[0], arr[1], arr[2]);
}

int main(void){
        int arr[3] = {1, 2, 3};
        std::sort(arr, arr+3);
        int count = 0;
        do {
                print_array(arr);
                count++;
        } while(std::next_permutation(arr, arr+3));

        printf("count = %d\n", count);
        return 0;
}

// 1, 2, 3
// 1, 3, 2
// 2, 1, 3
// 2, 3, 1
// 3, 1, 2
// 3, 2, 1
// count = 6

これらのアルゴリズムをCommon Lispで書いてみます。

なお、Common Lispには順列を操作するためのライブラリとして cl-permutation があります。 プログラム中で順列を生成したりしたい場合はわざわざ自作せずありがたく利用させて頂きましょう。

;; from Ruby (array.c)
(defun permute0 (n r p index used vals result)
  (dotimes (i n)
    (when (zerop (bit used i))
      ;; 順列のindex番目の要素として元の配列のi番の要素を選択
      (setf (svref p index) i)
      (if (< index (1- r))
          (progn
            ;; 選択済みの要素に対応するフラグをONにする
            (setf (bit used i) 1)
            (permute0 n r p (1+ index) used vals result)
            ;; 選択済みフラグをOFFにする
            (setf (bit used i) 0))
          (progn
            ;; 添字の配列から値の配列を作成して結果配列に追加
            (vector-push 
             (loop :for j :across p :collect (elt vals j))
             result))))))

(defun permute (seq r)
  (let* ((n (length seq))
         (result (make-array (permutation n r) :fill-pointer 0 :adjustable t))
         (used (make-array n :element-type 'bit :initial-element 0))
         (p (make-array r :element-type '(integer 0 *))))
    (permute0 n r p 0 used seq result)
    result))
> (permute '(1 2 3) 2)
#((1 2) (1 3) (2 1) (2 3) (3 1) (3 2))
;; from C++ (std::next_permutation)
(defun next-permutation (arr)
  (let ((len (length arr)))
    (unless (or (= len 0) (= len 1))
      (loop
         :for pos :from (1- len) :downto 1
         :when (< (aref arr (1- pos)) (aref arr pos))
         :do (progn
               (rotatef (aref arr (1- pos))
                        (aref arr
                              (position-if
                               #'(lambda (x) (< (aref arr (1- pos)) x))
                               arr
                               :from-end t)))
               (setf (subseq arr pos)
                     (nreverse
                      (make-array (- len pos)
                                  :displaced-to arr
                                  :displaced-index-offset pos)))
               (return-from next-permutation t))))))
> (defmacro do-while (test &body body)
          `(loop
              :do (progn ,@body)
              :while ,test))
> (let ((tmp (vector 0 1 2)))
          (do-while (next-permutation tmp)
            (print tmp)))
#(0 1 2) 
#(0 2 1) 
#(1 0 2) 
#(1 2 0) 
#(2 0 1) 
#(2 1 0)

他にも色々なアルゴリズムが存在するようです。 その中のひとつとして、階乗進数 を利用したプログラムを書いてみます。

(defun factoradic-permutation (n width)
  (let ((fact (make-array width :initial-element 1))
        (mantissa (make-array width :initial-element 0)))
    ;; 階乗を計算して配列に設定
    (loop
       :for i :from 1 :below width
       :for acc := i :then (* acc i)
       :do (setf (aref fact i) acc))
    ;; 階乗進数の仮数を計算して配列に設定
    (loop
       :for i :from (1- width) :downto 1
       :for acc := n :then (mod acc (aref fact (1+ i)))
       :do (setf (aref mantissa i)
                 (floor acc (aref fact i))))
    ;; 階乗進数を利用して順列を作成 (配列mantissaを使いまわす)
    (let ((tmp (loop :for i :from 0 :below width :collect i)))
      (loop
       :for i :from (1- width) :downto 0
       :for x := (aref mantissa i)
       :do (setf (aref mantissa i) (nth x tmp)
                 tmp (delete (nth x tmp) tmp))))
    (nreverse mantissa)))
> (dotimes (n 6)
>  (print (factoradic-permutation n 3)))
#(0 1 2) 
#(0 2 1) 
#(1 0 2) 
#(1 2 0) 
#(2 0 1) 
#(2 1 0)

2012年10月25日木曜日

オイラーの贈物とLisp(1.1.1)

オイラーの贈物 を読みながら、登場する数式などをCommon Lispで書いてみます。

1.1.1 自然数と素数(P6)より、有名なエラトステネスの篩と、 Wikipediaの 素数の項目 に載っていたウラムの螺旋を出力するコードです。 画像の作成には Vecto を利用しました。

(defun eratosthenes-sieve (n)
  "Return a sequence which indicates whether index is the prime number or not."
  ;; `n' is greater than or equal to 2
  (check-type n (integer 2 *))
  (let ((seq (make-array (1+ n) :initial-element t)))
    (setf (svref seq 0) nil) ; 0 is not a prime number.
    (setf (svref seq 1) nil) ; 1 is not a prime number.
    ;; The outer loop can stop at the square root of `n'.
    (loop :for i :from 2 :to (floor (sqrt n))
       :when (svref seq i)
       :do
       ;; The inner loop can start at the square of `i'.
       ;; (Multiples of `i' which are less than the square of `i' are already set to `nil'.)
       (loop :for j :from (* i 2) :to n :by i
          :do (setf (svref seq j) nil)))
    seq))


(ql:quickload "vecto")

(defun draw-uram-spiral (edge-length output-file-name &key (pixel 2))
  (assert (<= 1 edge-length))
  (let* ((limit (expt edge-length 2))
         (primes (eratosthenes-sieve (expt edge-length 2)))
         (picture-edge-length (* pixel edge-length)))
    (vecto:with-canvas
        (:width picture-edge-length :height picture-edge-length)
      (vecto:set-rgb-fill 1.0 1.0 1.0)
      (vecto:rectangle 0.0 0.0 picture-edge-length picture-edge-length)
      (vecto:fill-path)
      (vecto:set-rgb-fill 0.0 0.0 1.0)
      (let ((idx 2)
            (step 0)
            (x (floor edge-length 2))
            (y (floor edge-length 2)))
        (loop
           :while (<= idx limit)
           :do 
           (dotimes (_ (1+ (floor step 2)))
             (when (<= idx limit)
               (case (mod step 4)
                 (0 (incf x))
                 (1 (decf y))
                 (2 (decf x))
                 (3 (incf y)))
               (when (svref primes idx)
                 (vecto:rectangle (* x pixel) (* y pixel) pixel pixel)
                 (vecto:fill-path))
               (incf idx)))
           (incf step)))
      (vecto:save-png output-file-name))))
> (draw-uram-spiral 100 "uram.png")

2012年9月22日土曜日

Haskell入門書的クイックソート

Haskellの入門書に乗っていそうなクイックソートをClojureとCommon Lispで書いてみます。

- Clojure
;; defnやletで分配束縛ができます
;; group-byで関数を適用した結果の値によってグループ分けができます
;; ハッシュテーブル(map)は指定されたキーに対応する値を取得する関数にもなります
(defn qsort [cmp [piv & rst :as coll]]
  (if (empty? coll) []
    (#(concat (qsort cmp (%1 true)) [piv] (qsort cmp (%1 false)))
     (group-by #(boolean (cmp %1 piv)) rst))))

- Common Lisp
;; remove-if-not (filter)
(defun qsort-1 (cmp lst)
  (when lst
    (destructuring-bind (piv &rest rest) lst
      (flet ((f (x) (funcall cmp x piv)))
 (append (qsort-1 cmp (remove-if-not #'f rest))
  (list piv)
  ;; (remove-if-not (complement #'f) rest)
  (qsort-1 cmp (remove-if #'f rest)))))))

;; loopマクロ
(defun qsort-2 (cmp lst)
  (when lst
    (loop
       :with piv = (first lst)
       :for x in (rest lst)
       :if (funcall cmp x piv)
       :collect x into lesser
       :else
       :collect x into greater
       :finally (return
    (append (qsort-2 cmp lesser)
     (list piv)
     (qsort-2 cmp greater))))))

2012年7月11日水曜日

[CommonLisp]Internal Server Errorをフックする

Web系がさっぱりわからないので、勉強がてらなにか書いてみようと思いました。
 Webアプリケーションを書く前に、プログラム中で発生した例外をフックして、Internal Server Errorとしてブラウザに表示させるようにしてみます。
(asdf:load-system :clack)
;; swank:backtraceのほうがみやすい?
(asdf:load-system :trivial-backtrace)

(defpackage :mw-debug
  (:use :cl :clack))

(in-package :mw-debug)

(defun mw-debug-debugger-hook (c hook)
  (declare (ignore hook))
  (let ((restart (find-restart 'mw-debug-restart)))
    (when (not restart)
      (error "mw-debug-restart not found"))
    (invoke-restart restart c (trivial-backtrace:print-backtrace c :output nil))))

(defclass <mw-debug> (<middleware>)
  ())

(defmethod call ((this <mw-debug>) env)
  (let ((*debugger-hook* #'mw-debug-debugger-hook))
    (restart-case (call-next this env)
      (mw-debug-restart (c bt)
 `(500
   (:content-type "text/plain")
   (,(format nil "Internal Server Error~%~%")
     ,(format nil "-- Error -------------------------------~%")
     ,(with-output-to-string (*standard-output*)
       (describe c))
     ,(format nil "-- Backtrace ---------------------------~%")
     ,bt))))))
(defun b (tmp)
  ;; 未定義の関数を呼び出す。
  (c))
(defun a ()
  (b 2))
(defun run (port)
  (clackup
   (wrap (make-instance '<mw-debug>)
  (lambda (env)
    (a)))
   :port port))

;; (run 9999)

2012年7月5日木曜日

[CommonLisp]MOPを使って型指定子によりメソッドを特定する

Wikipedia日本語版の「列挙型」の項目に、CommonLispの型指定子はメソッドの引数特定には使えませんよ、と書いてあったので、無理やり実現する方法を考えてみました。
マクロを使うと負けな気がするので、MOPを利用してみます。
(asdf:load-system :closer-mop)

(defpackage type-spec-class
  (:use :cl)
  (:export
    <type-spec-meta>
    <type-spec-gf>
    define-type-spec))

(in-package :type-spec-class)

(defclass <type-spec-meta> (c2mop:standard-class)
  ((spec :initarg :spec :reader type-spec-of)))

(defmethod c2mop:validate-superclass ((cls <type-spec-meta>)
          (super c2mop:standard-class))
  t)

(defclass <type-spec-gf> (c2mop:standard-generic-function)
  ()
  (:metaclass c2mop:funcallable-standard-class))

(defmethod c2mop:validate-superclass ((cls <type-spec-gf>)
          (super c2mop:standard-generic-function))
  t)

(defmacro define-type-spec (name spec)
  `(progn
     (deftype ,name () ,spec)
     (c2mop:ensure-class-using-class
      (make-instance '<type-spec-meta> :spec ,spec)
      ',name)))

(defmethod c2mop:compute-discriminating-function :around
    ((gf <type-spec-gf>))
  (let ((org-fn (call-next-method)))
    (lambda (&rest args)
      (let* ((methods (c2mop:generic-function-methods gf))
             (m (find-type-spec-method methods args)))
       (if m
         (apply (c2mop:method-function m) args)
         (apply org-fn args))))))

(defun find-type-spec-method (methods args)
  (loop
     :for m in methods
     :for s = (c2mop:method-specializers m)
     :do (when (applicable-type-spec-method-p s args)
           (return-from find-type-spec-method m))))

(defun applicable-type-spec-method-p (specifier args)
  (flet ((type-spec-class-p (cls)
    (subtypep (class-of cls) '<type-spec-meta>)))
    (when (some #'type-spec-class-p specifier)
      (loop
        :for cls in specifier
        :for a in args
        :do (unless (or (and (type-spec-class-p cls)
                             (typep a (type-spec-of cls)))
                        (typep a cls))
              (return-from applicable-type-spec-method-p nil)))
      t)))
以下のようにして使います。
(in-package :cl-user)

(type-spec-class:define-type-spec color '(member :red :blue :green))

(defgeneric what-is (obj)
  (:generic-function-class type-spec-class:<type-spec-gf>))

(defmethod what-is ((obj t))
  "unknown")
  
(defmethod what-is ((obj symbol))
  "symbol")

(defmethod what-is ((obj color))
  (format nil "color ~A" obj))

(what-is :red)
;; => "color RED"
(what-is :hoge)
;; => "symbol"
(what-is 2)
;; => "unknown"
 
<type-spec-meta>のインスタンス(であるクラスのインスタンス)を引数にとるメソッドは通常のメソッドよりも優先度が高くなっていますが、 最初に見つかったものを呼び出しているだけなので、<type-spec-meta>のインスタンス間での優先度は扱っていません。

2012年6月26日火曜日

[CL]Windowsでselect

CCL + CFFIでWindows上でselectしてみます。
(asdf:load-system :usocket)
(asdf:load-system :bordeaux-threads)
(asdf:load-system :cffi)

(defconstant FD-SETSIZE 64)

(cffi:defcstruct timeval
  (tv-sec :ulong)
  (tv-usec :ulong))

(cffi:defcstruct fd-set
  (fd-count :uint)
  (fd-array :uint :count 64))

(cffi:defcfun ("select" win-select) :int
  (nfds :int)
  (readfds :pointer)
  (writefds :pointer)
  (exceptfds :pointer)
  (timeout :pointer))

(defun fd-zero (set)
  (setf (cffi:foreign-slot-value set 'fd-set 'fd-count) 0))

(defun fd-set (fd set)
  (when (< (cffi:foreign-slot-value set 'fd-set 'fd-count) FD-SETSIZE)
    (setf (cffi:mem-aref (cffi:foreign-slot-pointer set 'fd-set 'fd-array)
    :uint
    (cffi:foreign-slot-value set 'fd-set 'fd-count))
   fd)
    (incf (cffi:foreign-slot-value set 'fd-set 'fd-count))))

(defun fd-isset (fd set)
  (cffi:foreign-funcall "__WSAFDIsSet" :uint fd ::pointer set :int))

(defun fd-clr (fd set)
  (loop
     :with count = (cffi:foreign-slot-value set 'fd-set 'fd-count)
     :with i = 0
     :while (<  i count)
     :if (= (cffi:mem-aref (cffi:foreign-slot-pointer set 'fd-set 'fd-array) :uint i) fd)
     :do (loop :while (< i (1- count))
     :do
     (setf (cffi:mem-aref (cffi:foreign-slot-pointer set 'fd-set 'fd-array) :uint i)
    (cffi:mem-aref (cffi:foreign-slot-pointer set 'fd-set 'fd-array) :uint (1+ i)))
     (incf i))
     (decf count)
     :else
     :do (incf i)
     :finally (setf (cffi:foreign-slot-value set 'fd-set 'fd-count) count)))


(defun test ()
  (let* ((listener (usocket:socket-listen "localhost" 8888 :reuse-address t))
  (listener-fd (ccl:socket-os-fd (usocket:socket listener)))
  (fds (list listener-fd))
  (fd-obj `((,listener-fd ,listener))))
    (format t "Listener Fd:~A~%" listener-fd)
  (cffi:with-foreign-object (set 'fd-set)
    (loop
       (fd-zero set)
       (dolist (fd fds) (fd-set fd set))
       (unless (= 0 (win-select
       (apply #'max fds)
       set
    (cffi:null-pointer) (cffi:null-pointer) (cffi:null-pointer)))
  (dolist (fd fds)
    (when (fd-isset fd set)
      (if (= fd listener-fd)
   (let* ((sock (usocket:socket-accept listener))
   (sock-fd (ccl:socket-os-fd (usocket:socket sock))))
     (format t "Accept~%")
     (force-output t)
     (push sock-fd fds)
     (push (list sock-fd sock) fd-obj))
   (progn
     (format t "ReadLine:~A~%"
      (read-line (usocket:socket-stream (second (assoc fd fd-obj)))))
     (force-output t))))))))))


;; (defparameter th (bordeaux-threads:make-thread #'test))
;; (defparameter *con* (usocket:socket-connect "localhost" 8888))
;; (format (usocket:socket-stream *con*) "Hello, World~%")
;; (force-output (usocket:socket-stream *con*))
;; (bordeaux-threads:destroy-thread th)

2012年6月10日日曜日

FFIを利用してWindows上でメッセージボックスを表示する

FFI(Foreign Function Interface)を利用して、Windows上でメッセージボックスを表示してみます。

注意点
  • APIにはAscii用のMessageBoxAとUnicode用のMessageBoxWがある
  • Unicodeの符号化形式はUTF-16LE

Common Lisp

FFIは処理系依存です。各処理系の差異を吸収してくれる、CFFIというライブラリがあります。 CFFIはQuicklispでインストール可能です。 文字列のエンコードを直接指定しない場合は, cffi:*default-foreign-encoding* に設定されている値が利用されます。
;; ffi-test.lisp
(asdf:load-system :cffi)

(defpackage :ffi-test
  (:use :cl :cffi)
  (:export message-box))

(in-package :ffi-test)

(load-foreign-library "user32.dll")

(defcfun ("MessageBoxW" message-box) :int32
  (hWnd :pointer)
  (lpText (:string :encoding :utf-16le))
  (lpCaption (:string :encoding :utf-16le))
  (uType :uint))
> (load "ffi-test.lisp")
> (ffi-test:message-box (cffi:null-pointer) "hello" "わーるど" 0)
または
(cffi:foreign-funcall 
   "MessageBoxW"
   :pointer (cffi:null-pointer)
   (:string :encoding :utf-16le) "hello"
   (:string :encoding :utf-16le) "わーるど"
   :uint 0
   :int32)

Racket

Racketではffi/unsafeライブラリを利用すればよさそうです。
#lang racket
;; ffi-test.rkt
(require ffi/unsafe)
(provide message-box)

(define user32 "user32.dll")

(define message-box
  (get-ffi-obj
   "MessageBoxW" user32
   (_fun _pointer
  _string/utf-16
  _string/utf-16
  _uint32
  -> _int32)
   #f))
> (load "ffi-test.rkt")
> (require 'ffi-test)
> (message-box #f "hello" "わーるど" 0)

Ruby

RubyでWindowsのDLLの関数を呼び出すには、Win32APIライブラリを利用すればよさそうです。
# -*- coding: utf-8 -*-
require "Win32API"
require "nkf"

class String
  def to_utf16le
    NKF.nkf("-w16L0", self)
  end
end

msgbox = Win32API.new('user32', 'MessageBoxW', %w(p p p i), 'i')
msgbox.call(0, "hello".to_utf16le, "わーるど".to_utf16le, 0)

Python

Pythonではctypesライブラリを利用すればよさそうです。
# -*- coding: utf-8 -*-
import ctypes

user32 = ctypes.windll.user32

user32.MessageBoxW(None, "hello", "わーるど", 0)

2012年6月2日土曜日

[Common Lisp] cl-annotで契約による設計のようななにか

cl-annotのアノテーションを利用して、契約による設計(Design By Contrat)っぽいことを行ってみます。

(asdf:load-system :cl-annot)
(asdf:load-system :alexandria)

(defpackage net.phorni.contract
  (:use :cl)
  (:export
   ;; annotation
   contract
   ;; condtion
   contract-error
   pre-contract-error
   post-contract-error
   ;; macro
   with-contract
   def/contract))

(in-package :net.phorni.contract)

(define-condition contract-error (error)
  ((expr :reader contract-expr :initarg :expr))
  (:report (lambda (condition stream)
      (format stream
       "~A: ~A"
       (type-of condition)
       (contract-expr condition)))))
(define-condition pre-contract-error (contract-error)
  ())
(define-condition post-contract-error (contract-error)
  ())

;; type-specifierの判別は処理系依存らしい
(defun type-specifier-p (x)
  (or
   #+CCL (ccl:type-specifier-p x)))

(defmacro contract-check (contract-type expr)
  (let ((gsym (gensym)))
    `(let ((,gsym ,expr))
       (if ,gsym
    ,gsym
    (error ,contract-type
    :expr ',expr)))))

(defun parse-contract-body (body)
  (loop
     :for expr in body
     :if (and (listp expr) (eq :pre (car expr)))
     :collect expr into pre
     :else :if (and (listp expr) (eq :post (car expr)))
     :collect expr into post
     :else
     :collect expr into parsed-body
     :finally (return (list pre post parsed-body))))

(defun pre-contract-expand (pre-list)
  `(progn
     ,@(loop
   :for pre in pre-list
   :collect
   `(contract-check 'pre-contract-error ,(second pre)))))

(defun post-contract-expand (vars post-list)
  `(progn
     ,@(loop
   :for post in post-list
   :collect
   `(contract-check 'post-contract-error
      (apply
       (lambda ,(cadr post)
         ,@(cddr post))
       ,vars)))))

(defmacro with-contract (&body body)
  (destructuring-bind
 (pre post parsed-body)
      (parse-contract-body body)
    (let ((gtmp (gensym)))
      `(progn
  ,(pre-contract-expand pre)
  (let ((,gtmp (multiple-value-list (progn ,@parsed-body))))
    ,(post-contract-expand gtmp post)
    (values-list ,gtmp))))))

(defun multiple-value-result-contract-spec? (x)
  (and (listp x)
       (eq :values (car x))
       (every #'type-specifier-p (cdr x))))

(defun check-multiple-value-num (result num)
  (= (length result) num))

(defmacro def/contract ((&rest args-contract) result-contract orig-def)
  (dolist (a args-contract)
    (unless (and (listp a)
   (= (length a) 2)
   (symbolp (first a))
   (type-specifier-p (second a)))
      (error "invalid pre-contract spec: ~A" a)))
  (when (and (not (multiple-value-result-contract-spec? result-contract))
      (type-specifier-p result-contract))
    (setf result-contract (list :values result-contract)))
  (unless (multiple-value-result-contract-spec? result-contract)
    (error "invalid post-contract spec: ~A" result-contract))  
  (let ((def (nth 0 orig-def))
 (name (nth 1 orig-def))
 (args (nth 2 orig-def))
 (body (nthcdr 3 orig-def))
 (gresult (gensym)))
    (multiple-value-bind
   (parsed-body declares doc)
 (alexandria:parse-body body :documentation t)
      `(,def ,name ,args
  ,doc
  ,@declares
  (with-contract
    ,@(loop
  :for a in args-contract
  :collect `(:pre (typep ,(first a) ',(second a))))
    (:post (&rest ,gresult)
    (and (check-multiple-value-num 
   ,gresult
   ,(length (cdr result-contract)))
         (every #'identity 
         (mapcar #'typep 
          ,gresult
          ',(cdr result-contract)))))
    ,@parsed-body)))))

(cl-annot:defannotation contract (args result def) (:arity 3)
  `(def/contract ,args ,result ,def))

;; ex

(def/contract ((n (integer 0 *)) (m (integer 1 *))) number
  (defun my-div-1 (n m)
    (/ n m)))
;; (my-div-1 2 3) => 2/3
;; (my-div-1 -1 1) => PRE-CONTRACT-ERROR: (TYPEP N '(INTEGER 0 *))

(cl-annot:enable-annot-syntax)

@contract ((n (integer 0 *)) (m (integer 1 *))) number
(defun my-div-2 (n m)
  (/ n m))
;; (my-div-2 4 2) => 2
;; (my-div-2 4 0) => PRE-CONTRACT-ERROR: (TYPEP M '(INTEGER 1 *))

2012年2月17日金曜日

処理系に質問する方法

いろいろなプログラミング言語を利用していると、
同じような機能の関数の名前が言語間で異なることがしばしばあります。
ブラウザを立ち上げてドキュメントを探して、としても良いかもしれませんが、
ちょっとど忘れした名前を調べるだけならば、使っている処理系に問いあわせるだけで
目的を達成できそうです。
ということで、各処理系でのヘルプ機能を調べてみました。



Ruby


Rubyのオブジェクトにはメソッドやメンバ変数の一覧を取得するメソッドが備わっています。



  • methods メソッドを返す

  • public_methods publicなメソッドを返す

  • private_methods privateなメソッドを返す

  • protected_methods protectedなメソッドを返す

  • instance_methods メソッドを返す

  • included_modules インクルードしているモジュールを返す

  • constants 定数名を返す

  • instance_variables インスタンス変数名を返す


xxx_methods系の戻り値の各要素は、1.8系だと文字列、1.9系だとシンボルだそうです。



> String.instance_methods.grep /upcase/
#=> ["upcase!", "upcase"]


Python


Pythonには情報を表示するhelp関数が存在します。
モジュールやクラスなどを指定できるようです。


> help(__builtins__)

> help(str)

> help("print")

また、inspectモジュールをインポートするとgetmembers関数で
メンバ一覧を取得できるようになるので、メソッドを検索することもできます。



> import inspect
> import re
> for (name, _) in inspect.getmembers(str):
... if re.search("up", name):
... print name
...
isupper
upper


inspectモジュールには関数の定義ファイルやソースコードを取得する関数もあるようです。


> inspect.getfile(inspect.getfile)
'/usr/lib/python2.6/inspect.py'
> inspect.getsource(inspect.getsource)
...


Common Lisp


Common Lisp処理系は、関数や変数を検索するapropos関数を備えています。
apropos関数は検索するパッケージを指定することができるので、
COMMON-LISPパッケージ(CLパッケージ)を指定することで仕様に存在する関数のみを検索する、
ということも可能です(指定しない場合はすべてのパッケージが対象)



  • apropos 関数や変数を検索する。パッケージを指定できる。

  • apropos-list 関数や変数を検索しリストにして返す。パッケージを指定できる。



;; SBCL
> (apropos "upcase" :cl)
CHAR-UPCASE (fbound)
NSTRING-UPCASE (fbound)
STRING-UPCASE (fbound)


パッケージ一覧やシンボル一覧を取得する方法もあります。



  • list-all-packages すべてのパッケージを返す

  • do-all-symbols すべてのシンボルを処理するためのループを実行するマクロ

  • do-external-symbols パッケージ外部に公開されているシンボルを処理するためのループを実行するマクロ

  • *features* 有効な機能一覧を格納している変数



オブジェクトの情報を表示するdescribe関数、
情報の表示を対話的に行うinspect関数といった機能があります。


また、Common Lispでは関数や変数の定義にドキュメントを含めることができ、
documentation関数でそのドキュメントを取得することができます。



Racket


Scheme処理系のRacketは、REPL(インタプリタ)にhelpと打ち込むと
インストールされているドキュメントを既定のブラウザで開いてくれます。


また、xreplというライブラリを読み込むことでREPLに機能を追加してくれます。
追加されるヘルプ機能は以下のとおりです。



  • apropos 関数や変数を検索する

  • describe 関数や変数がどこで定義されたかを表示する

  • doc 指定した関数のドキュメントを既定のブラウザで表示する



> (require xrepl)
> ,apropos upcase
; Matches: char-upcase, string-locale-upcase, string-upcase.
> ,describe string-upcase
; `string-upcase' is a bound identifier,
; defined in #%kernel
; required through "racket/init.rkt"

> ,doc string-upcase
Sending to web browser...
file: c:\Program Files (x86)\Racket\doc\reference\strings.html
anchor: (def._((quote._~23~25kernel)._string-upcase))


Gauche


Scheme処理系のGaucheは、関数や変数を探すapropos関数を備えています。


> (apropos 'upcase)
char-upcase (scheme)
;; 文字列処理を行うSRFI-13ライブラリを読み込む
> (use srfi-13)
#<undef>
> (apropos 'upcase)
char-upcase (scheme)
string-upcase (srfi-13)
string-upcase! (srfi-13)


オブジェクトの情報を表示したい場合は、describe関数が使えます。



Guile


GNUのScheme処理系Guileは、関数や変数を探すapropos関数を備えています。



> (apropos "upcase")
(guile): char-upcase #<primitive-procedure char-upcase>
(guile): string-upcase! #<primitive-procedure string-upcase!>
(guile): string-upcase #<primitive-procedure string-upcase>


Chicken


Scheme処理系のChickenは、utilsライブラリを読み込むことで
関数や変数を検索するapropos関数が利用できるようになります。



> (require 'utils)
> (apropos 'upcase)
char-upcase : (procedure c692)
> (require 'srfi-13)
> (apropos 'upcase)
char-upcase : (procedure c692)
string-upcase : (procedure s694 . maybe-start+end695)
string-upcase! : (procedure s698 . maybe-start+end699)


Clojure


JVM上のLisp系言語であるClojureは、関数や変数の検索、ドキュメントや
ソースコードの表示といったヘルプ機能を備えているようです。



  • doc ドキュメントを表示する

  • source ソースコードを表示する

  • find-doc ドキュメントを検索する

  • apropos 関数名を検索する



Emacs Lisp


Emacsの拡張言語であるEmacs Lispにはさまざまなヘルプ機能があります。
多すぎるのでよく使っているもののみを列挙します。



  • apropos 関数名や変数名を検索する

  • help-for-help ヘルプ(デフォルトでC-hに割り当てられているコマンド)

  • find-function 関数の定義位置へ移動する

  • find-variable 変数の定義位置へ移動する

2011年6月15日水曜日

cl-gtk2 + Glade

cl-gtk2はgladeで作成したファイルを利用できるようなので遊んで見ました。

ソースコード

(asdf:load-system :cl-gtk2-glib)
(asdf:load-system :cl-gtk2-gdk)
(asdf:load-system :cl-gtk2-cairo)
(asdf:load-system :closure-html)
(asdf:load-system :cxml-stp)
(asdf:load-system :drakma)
(asdf:load-system :cl-ppcre)
(asdf:load-system :cl-interpol)

(defpackage :gtk-user
(:use :cl)
(:export run))

(in-package :gtk-user)

(cl-interpol:enable-interpol-syntax)
(setf drakma:*drakma-default-external-format* :utf-8)

(defun reference-of (node)
(let ((tag (stp:local-name node)))
(cond
((string= tag "a")
(or (stp:attribute-value node "href") ""))
((string= tag "img")
(or (stp:attribute-value node "src") ""))
((string= tag "link")
(or (stp:attribute-value node "href") ""))
((string= tag "script")
(or (stp:attribute-value node "src") ""))
(T ""))))

(defun text-of (node)
(let ((text (stp:string-value node)))
(if (> (length text) 30)
(concatenate 'string (subseq text 0 27 ) "...")
text)))

;; ありそうな文字コードを総当たりで試す。富豪的富豪的。
(defun octets-to-string-by-error-handler (octets)
(let ((formats (list :shift_jis :utf-8 :euc-jp :eucjp
:sjis
:utf-16 :utf-16BE :utf-16le
:utf-32 :utf-32be :utf-32le
:utf-8b )))
(tagbody
:retry
(print formats)
(handler-case
(return-from octets-to-string-by-error-handler
(sb-ext:octets-to-string octets :external-format (pop formats)))
(error (e)
(declare (ignore e))
(if formats
(go :retry)
(error "can't convert octets to string")))))))

(defun get-http-body-string (url)
(multiple-value-bind
(arr code headers url stream)
(drakma:http-request url :external-format-in :binary)
(let ((content-type (cdr (find :content-type headers :test #'string= :key #'car))))
(if content-type
(cl-ppcre:register-groups-bind (charset)
((cl-ppcre:create-scanner #?/charset=(\w+)/ :case-insensitive-mode t)
content-type)
;; todo
(octets-to-string-by-error-handler arr))))))

(defun run ()
(let ((out *standard-output*))
(gtk:within-main-loop
(let* ((builder
(make-instance 'gtk:builder
:from-file "/path/to/GladeTest.glade"))
(window (gtk:builder-get-object builder "ToplevelWindow"))
(entry (gtk:builder-get-object builder "entry1"))
(button (gtk:builder-get-object builder "button1"))
(tree (gtk:builder-get-object builder "treeview1"))
;; treeview1のmodelは後で上書きする
(dummy (gtk:builder-get-object builder "liststore1"))
(liststore (make-instance 'gtk:array-list-store)))

;; treeview1のmodelを上書き
(setf (gtk:tree-view-model tree) liststore)

;; tree-viewの列(model)
(gtk:store-add-column liststore "gchararray" #'stp:local-name)
(gtk:store-add-column liststore "gchararray" #'text-of)
(gtk:store-add-column liststore "gchararray" #'reference-of)

;; tree-viewの列(view)
(let ((col-tag (make-instance 'gtk:tree-view-column :title "タグ"))
(col-text (make-instance 'gtk:tree-view-column :title "text"))
(col-ref (make-instance 'gtk:tree-view-column :title "参照先"))
(cr (make-instance 'gtk:cell-renderer-text)))
(gtk:tree-view-column-pack-start col-tag cr)
(gtk:tree-view-column-add-attribute col-tag cr "text" 0)
(gtk:tree-view-column-pack-start col-text cr)
(gtk:tree-view-column-add-attribute col-text cr "text" 1)
(gtk:tree-view-column-pack-start col-ref cr)
(gtk:tree-view-column-add-attribute col-ref cr "text" 2)
(gtk:tree-view-append-column tree col-tag)
(gtk:tree-view-append-column tree col-text)
(gtk:tree-view-append-column tree col-ref))

;; ボタンクリック時の動作
(gobject:g-signal-connect
button "clicked"
(lambda (b)
(handler-case
(let* ((str (get-http-body-string (gtk:entry-text entry)))
(doc (chtml:parse str (cxml-stp:make-builder))))
(stp:do-recursively (node doc)
(when
(and
(typep node 'stp:element)
(some
(lambda (s) (string-equal s (stp:local-name node)))
'("a" "link" "script" "img")))
(gtk:store-add-item liststore node))))
(error (e)
(let ((diag (make-instance 'gtk:message-dialog
:text (format nil
"error:(~A) ~A"
(gtk:entry-text entry)
e)
:message-type :error)))
(unwind-protect (gtk:dialog-run diag)
(gtk:object-destroy diag)))))))
(gtk:widget-show window)))))


gladeファイル

<?xml version="1.0" encoding="UTF-8"?>
<interface>
<requires lib="gtk+" version="2.16"/>
<!-- interface-naming-policy toplevel-contextual -->
<object class="GtkWindow" id="ToplevelWindow">
<property name="title" translatable="yes">ToplevelWindow</property>
<child>
<object class="GtkVBox" id="vbox3">
<property name="visible">True</property>
<child>
<object class="GtkHBox" id="hbox1">
<property name="height_request">30</property>
<property name="visible">True</property>
<child>
<object class="GtkLabel" id="label5">
<property name="visible">True</property>
<property name="label" translatable="yes">URL:</property>
</object>
<packing>
<property name="expand">False</property>
<property name="position">0</property>
</packing>
</child>
<child>
<object class="GtkEntry" id="entry1">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="invisible_char">•</property>
</object>
<packing>
<property name="position">1</property>
</packing>
</child>
<child>
<object class="GtkButton" id="button1">
<property name="label" translatable="yes">読み込み</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">True</property>
</object>
<packing>
<property name="expand">False</property>
<property name="position">2</property>
</packing>
</child>
</object>
<packing>
<property name="expand">False</property>
<property name="position">0</property>
</packing>
</child>
<child>
<object class="GtkTreeView" id="treeview1">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="model">liststore1</property>
</object>
<packing>
<property name="position">1</property>
</packing>
</child>
</object>
</child>
</object>
<object class="GtkListStore" id="liststore1"/>
</interface>

利用しているライブラリはすべてquicklispでインストールできます。

ライブラリのおおまかな内容は以下のとおり。

  • cl-gtk2-*** : GTKバインディング
  • closure-html : HTMLパーサー
  • cxml-stp : DOMに似たもの
  • cl-ppcre : 正規表現
  • drakma : HTTPクライアント
  • cl-interpol : リーダーの拡張。正規表現リテラルに利用。

sb-ext:octets-to-stringを利用しているのでSBCLでのみ動作します。他の処理系で動作ささせる場合、バイト列を文字列に変換する箇所を変更する必要があります。

(gtk-user::run) を評価するとテキストボックス(entry)を持ったウィンドウが表示されます。このテキストボックスにURLを入力して隣のボタンをクリックすると、URLの内容(HTML)を取得し、他のURLへを参照していそうなa/link/img/scriptタグを抜き出してtree-viewに表示します。

わかりづらかった点として、gtk:array-list-storeがCommonLisp側で定義されたクラスだということがありました。 array-list-storeは便利そうだと思いましたが、GTK側に組み込まれているクラスではないので、 Gladeでモデルに指定できない(ような気がします)。