Repository navigation
Expand file tree
/
Copy pathmole-context.el
More file actions
72 lines (58 loc) · 2.43 KB
/
Copy pathmole-context.el
File metadata and controls
72 lines (58 loc) · 2.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
;;; mole-context.el --- Cacheable alists -*- lexical-binding: t -*-
;; Copyright (C) 2018 Felipe Ochoa
;; Author: Felipe Ochoa <felipe@fov.space>
;; URL: https://github.com/felipeochoa/mole/
;; Created: 13 Dec 2017
;; Package-Requires: ((emacs "25.2"))
;; Version: 0.1
;; Keywords: maint
;; This program is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <https://www.gnu.org/licenses/>.
;; This file is not part of GNU Emacs.
;;; Commentary:
;;; This file includes utility functions for creating, updating, and
;;; comparing small key-value stores where the store itself is easily
;;; cacheable. These stores are used in the mole packrat parser to
;;; efficiently cache parse results that may be context dependent.
;;; Code:
(defvar mole-context-compare--default (cons nil (make-symbol "not-found"))
"Value used to distinguish not found from nil.")
(defun mole-context-compare (c1 c2)
"Return t if C1 and C2 are equivalent contexts."
(or (eq c1 c2)
(and (= (length c1) (length c2))
(let ((res t))
(while (and res c1)
(setq res (eq (cdar c1)
(cdr (or (assq (caar c1) c2)
mole-context-compare--default)))
c1 (cdr c1)))
res))))
(defsubst mole-context-get (ctx key)
"Return the CTX's value for KEY."
(cdr (assq key ctx)))
(defun mole-context-set (ctx key val)
"Return a new context like CTX, but with KEY set to VAL."
(cons
(cons key val)
(cond
((null ctx) nil)
((eq (caar ctx) key) (cdr ctx))
(t (let ((tail ctx) (i 0) (res ctx))
(while (setq i (1+ i) tail (cdr tail))
(when (eq key (caar tail))
(setq res nil)
(dotimes (_ i) (push (pop ctx) res))
(setq tail nil
res (nconc (nreverse res) (cdr tail)))))
res)))))
(provide 'mole-context)
;;; mole-context.el ends here