Personal emacs config
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

486 lines
18 KiB

  1. ;;; treepy.el --- Generic tree traversal tools -*- lexical-binding: t -*-
  2. ;;
  3. ;; Filename: treepy.el
  4. ;;
  5. ;; Copyright (C) 2017 Daniel Barreto
  6. ;;
  7. ;; Description: Generic Tree Traversing Tools
  8. ;; Author: Daniel Barreto <daniel.barreto.n@gmail.com>
  9. ;; Keywords: lisp, maint, tools
  10. ;; Package-Version: 0.1.2
  11. ;; Package-Commit: 3ac940e97f3d03e48ca9d7fcd74916a9b01c72f3
  12. ;; Created: Mon Jul 10 15:17:36 2017 (+0200)
  13. ;; Version: 0.1.1
  14. ;; Package-Requires: ((emacs "25.1"))
  15. ;; URL: https://github.com/volrath/treepy.el
  16. ;;
  17. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  18. ;;
  19. ;;; Commentary:
  20. ;;
  21. ;; Generic tools for recursive and iterative tree traversal based on
  22. ;; clojure.walk and clojure.zip respectively. Depends on `map', a map
  23. ;; manipulation library built in Emacs 25.1. All functions are prefixed
  24. ;; with "treepy-"
  25. ;;
  26. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  27. ;;
  28. ;; This program is free software: you can redistribute it and/or modify
  29. ;; it under the terms of the GNU General Public License as published by
  30. ;; the Free Software Foundation, either version 3 of the License, or (at
  31. ;; your option) any later version.
  32. ;;
  33. ;; This program is distributed in the hope that it will be useful, but
  34. ;; WITHOUT ANY WARRANTY; without even the implied warranty of
  35. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  36. ;; General Public License for more details.
  37. ;;
  38. ;; You should have received a copy of the GNU General Public License
  39. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  40. ;;
  41. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  42. ;;
  43. ;;; Code:
  44. (require 'map)
  45. (require 'cl-lib)
  46. ;;; Walk (recursive tree traversal)
  47. (defun treepy-walk (inner outer form)
  48. "Using INNER and OUTER, traverse FORM, an arbitrary data structure.
  49. INNER and OUTER are functions. Apply INNER to each element of
  50. FORM, building up a data structure of the same type, then apply
  51. OUTER to the result. Recognize cons, lists, alists, vectors and
  52. hash tables."
  53. (cond
  54. ((and (listp form) (cdr form) (atom (cdr form))) (funcall outer (cons (funcall inner (car form))
  55. (funcall inner (cdr form)))))
  56. ((listp form) (funcall outer (mapcar inner form)))
  57. ((vectorp form) (funcall outer (apply #'vector (mapcar inner form))))
  58. ((hash-table-p form) (funcall outer (map-apply (lambda (k v) (funcall inner (cons k v))) form)))
  59. (t (funcall outer form))))
  60. (defun treepy-postwalk (f form)
  61. "Perform a depth-first, post-order traversal of F applied to FORM.
  62. Call F on each sub-form, use F's return value in place of the
  63. original. Recognize cons, lists, alists, vectors and
  64. hash tables."
  65. (treepy-walk (apply-partially #'treepy-postwalk f) f form))
  66. (defun treepy-prewalk (f form)
  67. "Perform a depth-first, pre-order traversal of F applied to FORM.
  68. Like `treepy-postwalk'."
  69. (treepy-walk (apply-partially #'treepy-prewalk f) #'identity (funcall f form)))
  70. (defun treepy-postwalk-demo (form)
  71. "Demonstrate the behavior of `treepy-postwalk' for FORM.
  72. Return a list of each form as it is walked."
  73. (let ((walk nil))
  74. (treepy-postwalk (lambda (x) (push x walk) x)
  75. form)
  76. (reverse walk)))
  77. (defun treepy-prewalk-demo (form)
  78. "Demonstrate the behavior of `treepy-prewalk' for FORM.
  79. Return a list of each form as it is walked."
  80. (let ((walk nil))
  81. (treepy-prewalk (lambda (x) (push x walk) x)
  82. form)
  83. (reverse walk)))
  84. (defun treepy-postwalk-replace (smap form &optional testfn)
  85. "Use SMAP to transform FORM by doing replacing operations.
  86. Recursively replace in FORM keys in SMAP with their values. Does
  87. replacement at the leaves of the tree first. The optional TESTFN
  88. parameter is the function to be used by `map-contains-key'."
  89. (treepy-postwalk (lambda (x) (if (map-contains-key smap x testfn) (map-elt smap x) x))
  90. form))
  91. (defun treepy-prewalk-replace (smap form &optional testfn)
  92. "Use SMAP to transform FORM by doing replacing operations.
  93. Recursively replace in FORM keys in SMAP with their values. Does
  94. replacement at the root of the tree first. The optional TESTFN
  95. parameter is the function to be used by `map-contains-key'."
  96. (treepy-prewalk (lambda (x) (if (map-contains-key smap x testfn) (map-elt smap x) x))
  97. form))
  98. ;;; Zipper (iterative tree traversal)
  99. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  100. (defun treepy--context (loc &optional key)
  101. "Return context for this LOC.
  102. If KEY is given, only return this key's value in context."
  103. (let ((context (cdr (car loc))))
  104. (if (and context key)
  105. (map-elt context key)
  106. context)))
  107. (defun treepy--context-assoc-1 (context k v)
  108. "Assoc in CONTEXT a key K with a value V."
  109. (if (map-contains-key context k)
  110. (mapcar (lambda (entry)
  111. (if (equal (car entry) k)
  112. (cons k v)
  113. entry))
  114. context)
  115. (cons (cons k v) context)))
  116. (defun treepy--context-assoc (context &rest kvs)
  117. "Immutable map association in CONTEXT using KVS."
  118. (seq-reduce (lambda (context kv)
  119. (seq-let [k v] kv
  120. (treepy--context-assoc-1 context k v)))
  121. (seq-partition kvs 2) context))
  122. (defun treepy--meta (loc &optional key)
  123. "Return meta information for this LOC.
  124. If KEY is given, only return this key's value in meta
  125. information."
  126. (let ((meta (cdr loc)))
  127. (if key
  128. (map-elt meta key)
  129. meta)))
  130. (defun treepy--with-meta (obj meta)
  131. "Bind OBJ with some META information."
  132. (cons obj meta))
  133. (defun treepy--join-children (left-children right-children)
  134. "Return a joining of LEFT-CHILDREN and RIGHT-CHILDREN.
  135. Reverses LEFT-CHILDREN so that they are correctly ordered as in
  136. the tree."
  137. (append (reverse left-children) right-children))
  138. (defmacro treepy--with-loc (loc vars &rest body)
  139. "Create a lexical context using LOC VARS.
  140. Execute BODY in this context."
  141. (declare (indent defun))
  142. (let ((lex-ctx (mapcar (lambda (v)
  143. (cl-case v
  144. ('node `(node (treepy-node ,loc)))
  145. ('context `(context (treepy--context ,loc)))
  146. (t `(,v (treepy--context ,loc (quote ,(intern (concat ":" (symbol-name v)))))))))
  147. vars)))
  148. `(let* (,@lex-ctx) ,@body)))
  149. ;;;; Construction
  150. (defun treepy-zipper (branchp children make-node root)
  151. "Create a new zipper structure.
  152. BRANCHP is a function that, given a node, returns t if it can
  153. have children, even if it currently doesn't.
  154. CHILDREN is a function that, given a branch node, returns a seq
  155. of its children.
  156. MAKE-NODE is a function that, given an existing node and a seq of
  157. children, returns a new branch node with the supplied children.
  158. ROOT is the root node."
  159. (treepy--with-meta
  160. (cons root nil)
  161. `((:branchp . ,branchp) (:children . ,children) (:make-node . ,make-node))))
  162. (defun treepy-list-zip (root)
  163. "Return a zipper for nested lists, given a ROOT list."
  164. (let ((make-node (lambda (_ children) children)))
  165. (treepy-zipper #'listp #'identity make-node root)))
  166. (defun treepy-vector-zip (root)
  167. "Return a zipper for nested vectors, given a ROOT vector."
  168. (let ((make-node (lambda (_ children) (apply #'vector children)))
  169. (children (lambda (cs) (seq-into cs 'list))))
  170. (treepy-zipper #'vectorp children make-node root)))
  171. ;;;; Context
  172. (defun treepy-node (loc)
  173. "Return the node at LOC."
  174. (caar loc))
  175. (defun treepy-branch-p (loc)
  176. "Return t if the node at LOC is a branch."
  177. (funcall (treepy--meta loc ':branchp) (treepy-node loc)))
  178. (defun treepy-children (loc)
  179. "Return a children list of the node at LOC, which must be a branch."
  180. (if (treepy-branch-p loc)
  181. (funcall (treepy--meta loc ':children) (treepy-node loc))
  182. (error "Called children on a leaf node")))
  183. (defun treepy-make-node (loc node children)
  184. "Return a new branch node.
  185. Given an existing LOC, NODE and new CHILDREN, creates a new LOC
  186. with them. The LOC is only used to supply the constructor."
  187. (funcall (treepy--meta loc ':make-node) node children))
  188. (defun treepy-path (loc)
  189. "Return a list of nodes leading to the given LOC."
  190. (reverse (treepy--context loc ':pnodes)))
  191. (defun treepy-lefts (loc)
  192. "Return a list of the left siblings of this LOC."
  193. (reverse (treepy--context loc ':l)))
  194. (defun treepy-rights (loc)
  195. "Return a list of the right siblings of this LOC."
  196. (treepy--context loc ':r))
  197. ;;;; Navigation
  198. (defun treepy-down (loc)
  199. "Return the loc of the leftmost child of the node at this LOC.
  200. nil if no children."
  201. (when (treepy-branch-p loc)
  202. (let ((children (treepy-children loc)))
  203. (treepy--with-loc loc (node context pnodes)
  204. (seq-let [c &rest cs] children
  205. (when children
  206. (treepy--with-meta
  207. `(,c . ((:l . ,nil)
  208. (:pnodes . ,(if context (cons node pnodes) (list node)))
  209. (:ppath . ,context)
  210. (:r . ,cs)))
  211. (treepy--meta loc))))))))
  212. (defun treepy-up (loc)
  213. "Return the loc of the parent of the node at this LOC.
  214. nil if at the top."
  215. (treepy--with-loc loc (node pnodes ppath changed? l r)
  216. (when pnodes
  217. (let ((pnode (car pnodes)))
  218. (treepy--with-meta
  219. (if changed?
  220. (cons (treepy-make-node loc pnode (treepy--join-children l (cons node r)))
  221. (and ppath (treepy--context-assoc ppath ':changed? t)))
  222. (cons pnode ppath))
  223. (treepy--meta loc))))))
  224. (defun treepy-root (loc)
  225. "Zip from LOC all the way up and return the root node.
  226. Reflect any alterations to the tree."
  227. (if (equal :end (treepy--context loc))
  228. (treepy-node loc)
  229. (let ((p loc))
  230. (while (setq p (treepy-up p))
  231. (setq loc p))
  232. (treepy-node loc))))
  233. (defun treepy-right (loc)
  234. "Return the loc of the right sibling of the node at this LOC.
  235. nil if there's no more right sibilings."
  236. (treepy--with-loc loc (node context l r)
  237. (let ((r (if (listp r)
  238. r
  239. ;; If `r' is not a list (or nil), then we're dealing with a non
  240. ;; nil cdr ending list.
  241. (cons r nil))))
  242. (seq-let [cr &rest rnext] r
  243. (when (and context r)
  244. (treepy--with-meta
  245. (cons cr
  246. (treepy--context-assoc context
  247. ':l (cons node l)
  248. ':r rnext))
  249. (treepy--meta loc)))))))
  250. (defun treepy-rightmost (loc)
  251. "Return the loc of the rightmost sibling of the node at this LOC.
  252. If LOC is already the rightmost sibling, return self."
  253. (treepy--with-loc loc (node context l r)
  254. (if (and context r)
  255. (treepy--with-meta
  256. (cons (car (last r))
  257. (treepy--context-assoc context
  258. ':l (treepy--join-children l (cons node (butlast r)))
  259. ':r nil))
  260. (treepy--meta loc))
  261. loc)))
  262. (defun treepy-left (loc)
  263. "Return the loc of the left sibling of the node at this LOC.
  264. nil if no more left sibilings."
  265. (treepy--with-loc loc (node context l r)
  266. (when (and context l)
  267. (seq-let [cl &rest lnext] l
  268. (treepy--with-meta
  269. (cons cl
  270. (treepy--context-assoc context
  271. ':l lnext
  272. ':r (cons node r)))
  273. (treepy--meta loc))))))
  274. (defun treepy-leftmost (loc)
  275. "Return the loc of the leftmost sibling of the node at this LOC.
  276. If LOC is already the leftmost sibling, return self."
  277. (treepy--with-loc loc (node context l r)
  278. (if (and context l)
  279. (treepy--with-meta
  280. (cons (car (last l))
  281. (treepy--context-assoc context
  282. ':l []
  283. ':r (treepy--join-children (butlast l) (cons node r))))
  284. (treepy--meta loc))
  285. loc)))
  286. (defun treepy-leftmost-descendant (loc)
  287. "Return the leftmost descendant of the given LOC.
  288. \(ie, down repeatedly)."
  289. (while (treepy-branch-p loc)
  290. (setq loc (treepy-down loc)))
  291. loc)
  292. ;;;; Modification
  293. (defun treepy-insert-left (loc item)
  294. "Insert as the left sibling of this LOC'S node the ITEM.
  295. Return same loc with sibilings updated."
  296. (treepy--with-loc loc (node context l)
  297. (if (not context)
  298. (error "Insert at top")
  299. (treepy--with-meta
  300. (cons node
  301. (treepy--context-assoc context
  302. ':l (cons item l)
  303. ':changed? t))
  304. (treepy--meta loc)))))
  305. (defun treepy-insert-right (loc item)
  306. "Insert as the right sibling of this LOC's node the ITEM.
  307. Return same loc with sibilings updated."
  308. (treepy--with-loc loc (node context r)
  309. (if (not context)
  310. (error "Insert at top")
  311. (treepy--with-meta
  312. (cons node
  313. (treepy--context-assoc context
  314. ':r (cons item r)
  315. ':changed? t))
  316. (treepy--meta loc)))))
  317. (defun treepy-replace (loc node)
  318. "Replace the node in this LOC with the given NODE, without moving."
  319. (let ((context (treepy--context loc)))
  320. (treepy--with-meta
  321. (cons node
  322. (treepy--context-assoc context
  323. ':changed? t))
  324. (treepy--meta loc))))
  325. (defun treepy-edit (loc f &rest args)
  326. "Replace the node at this LOC with the value of (F node ARGS)."
  327. (treepy-replace loc (apply f (treepy-node loc) args)))
  328. (defun treepy-insert-child (loc item)
  329. "Insert as the leftmost child of this LOC's node the ITEM.
  330. Return same loc with children updated."
  331. (treepy-replace loc (treepy-make-node loc (treepy-node loc) (cons item (treepy-children loc)))))
  332. (defun treepy-append-child (loc item)
  333. "Insert as the rightmost child of this LOC'S node the ITEM.
  334. Return same loc with children updated."
  335. (treepy-replace loc (treepy-make-node loc (treepy-node loc) (append (treepy-children loc) `(,item))))) ;; TODO: check performance
  336. (defun treepy-remove (loc)
  337. "Remove the node at LOC.
  338. Return the loc that would have preceded it in a depth-first
  339. walk."
  340. (treepy--with-loc loc (context pnodes ppath l r)
  341. (if (not context)
  342. (error "Remove at top")
  343. (if (> (length l) 0)
  344. (let ((nloc (treepy--with-meta (cons (car l)
  345. (treepy--context-assoc context
  346. ':l (cdr l)
  347. ':changed? t))
  348. (treepy--meta loc)))
  349. (child nil))
  350. (while (setq child (and (treepy-branch-p nloc) (treepy-children nloc)))
  351. (setq nloc (treepy-rightmost child)))
  352. nloc)
  353. (treepy--with-meta
  354. (cons (treepy-make-node loc (car pnodes) r)
  355. (and ppath (treepy--context-assoc context ':changed? t)))
  356. (treepy--meta loc))))))
  357. ;;;; Enumeration
  358. (defun treepy--preorder-next (loc)
  359. "Move to the next LOC in the hierarchy, depth-first in preorder.
  360. When reaching the end, returns a distinguished loc detectable via
  361. `treepy-end-p'. If already at the end, stays there."
  362. (if (equal :end (treepy--context loc))
  363. loc
  364. (let ((cloc loc))
  365. (or
  366. (and (treepy-branch-p cloc) (treepy-down cloc))
  367. (treepy-right cloc)
  368. (let ((p cloc)
  369. (pr nil))
  370. (while (and (treepy-up p) (not (setq pr (treepy-right (treepy-up p)))))
  371. (setq p (treepy-up p)))
  372. (or pr (cons (cons (treepy-node p) :end) nil)))))))
  373. (defun treepy--postorder-next (loc)
  374. "Move to the next LOC in the hierarchy, depth-first in postorder.
  375. When reaching the end, returns a distinguished loc detectable via
  376. `treepy-end-p'. If already at the end, stays there."
  377. (if (equal :end (treepy--context loc))
  378. loc
  379. (if (null (treepy-up loc))
  380. (cons (cons (treepy-node loc) :end) nil)
  381. (or (let ((rloc (treepy-right loc)))
  382. (and rloc (treepy-leftmost-descendant rloc)))
  383. (treepy-up loc)))))
  384. (defun treepy-next (loc &optional order)
  385. "Move to the next LOC in the hierarchy, depth-first.
  386. Use ORDER if given. Possible values for ORDER are `:preorder' and
  387. `:postorder', defaults to the former."
  388. (cl-case (or order ':preorder)
  389. (':preorder (treepy--preorder-next loc))
  390. (':postorder (treepy--postorder-next loc))
  391. (t (error "Unrecognized order"))))
  392. (defun treepy--preorder-prev (loc)
  393. "Move to the previous LOC in the hierarchy, depth-first preorder.
  394. If already at the root, returns nil."
  395. (let ((lloc (treepy-left loc))
  396. (child nil))
  397. (if lloc
  398. (progn
  399. (while (setq child (and (treepy-branch-p lloc) (treepy-children lloc)))
  400. (setq lloc (treepy-rightmost child)))
  401. lloc)
  402. (treepy-up loc))))
  403. (defun treepy--postorder-prev (loc)
  404. "Move to the previous LOC in the hierarchy, depth-first postorder.
  405. If already at the root, returns nil."
  406. (if (treepy-branch-p loc)
  407. (treepy-rightmost (treepy-down loc))
  408. (progn
  409. (while (not (treepy-left loc))
  410. (setq loc (treepy-up loc)))
  411. (treepy-left loc))))
  412. (defun treepy-prev (loc &optional order)
  413. "Move to the previous LOC in the hierarchy, depth-first.
  414. Use ORDER if given. Possible values for ORDER are `:preorder' and `:postorder',
  415. defaults to the former."
  416. (cl-case (or order ':preorder)
  417. (':preorder (treepy--preorder-prev loc))
  418. (':postorder (treepy--postorder-prev loc))
  419. (t (error "Unrecognized order"))))
  420. (defun treepy-end-p (loc)
  421. "Return t if LOC represents the end of a depth-first walk."
  422. (equal :end (treepy--context loc)))
  423. (provide 'treepy)
  424. ;;; treepy.el ends here