我需要分析 Elisp (Emacs Lisp) 代码,所以我使用Instaparse为它编写了一个解析器。我预计它会很慢,但是每秒执行 1k 行太慢了,即使在计算器(或我相当旧的 i7)上也是如此。它会那么糟糕还是我做错了什么?
这是明确的,我尽量保持向前/向后看,不幸的是,Elisp 对符号的构成非常自由,所以我不得不在前面/后面添加一些以区分数字和符号。此外,我试图通过将符号、数字和关键字解析为“ident”来推迟这一点,它只给了我 30% 的时间。从我的测试来看,Instaparse 似乎在递归规则方面遇到了很多困难,而 lisps 具有高度递归的性质,所以也许我没有把它搞砸 - 它就是那么慢......
解析器:
(ns slowparse
(:require [clojure.string :as str]
[instaparse.combinators :as c]
[instaparse.core :as insta]))
(def grammar
"Elisp grammar."
"<root> = any +
<any> = sexp | keyword | number | symbol | prefix | string | vector |
comment | whitespace | char | Epsilon
comment = comment-tok #'(?:[^\\n]*|$)'
string = <str-l-tok> #'(?:(?:\\\\\\\\)|(?:\\\\\")|[^\"])*' <str-r-tok>
char = <char-tok> #'(?:(?:\\\\(?:C|M)-)|(?:\\\\))?(?:.|\\s)'
<whitespace> = <#'\\s+'>
sexp = sexp-l-tok any + sexp-r-tok
vector = vec-l-tok any + vec-r-tok
<prefix> = quote | template | spread | hole
<prfxbl> = sexp | symbol | keyword | number | prefix | vector
quote = quote-tok prfxbl
template = tmpl-tok prfxbl
hole = hole-tok ! spread-tok prfxbl
spread = hole-tok spread-tok prfxbl
<sexp-l-tok> = <'('>
<sexp-r-tok> = <')'>
<vec-l-tok> = <'['>
<vec-r-tok> = <']'>
<str-l-tok> = <'\"'>
<str-r-tok> = <'\"'>
<quote-tok> = '#' ? <\"'\">
<tmpl-tok> = <'`'>
<num-b-x-tok> = '#'
<hole-tok> = <','>
<spread-tok> = <'@'>
<comment-tok> = <';'>
<char-tok> = '?'
<kv-tok> = <':'>
symbol = ! ( number | kv-tok | comment-tok | num-b-x-tok | char-tok )
ident
keyword = kv-tok ident
number = num-b10 | num-bx
<num-b10> = #'[-+]?(?:(?:[\\d]*\\.[\\d]+)|(?:[\\d]+\\.[\\d]*)|(?:[\\d]+))' &
( ! ident )
<num-bx> = #'(?i)#(?:b|o|x|(?:\\d+r))[-+]?[a-z0-9]+'")
(def ident
{:ident
(let [esc-ch (str/join ["\\[" "\\]" "\\(" "\\)" "\"" "\\s" "'" "," "`" ";"])
tmpl "(?:(?:\\\\[{{ec}}])|[^{{ec}}])+"]
(->> esc-ch (str/replace tmpl "{{ec}}") c/regexp c/hide-tag))})
(insta/defparser ^{:doc "Elisp parser."} elisp-parser
(merge ident (c/ebnf grammar))
:start :root)
(def test-text (slurp "/tmp/foo.el"))
(time (insta/parse elisp-parser test-text))