cache.scm 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. ;;;; cache.scm --- cache the results of parsing
  2. ;;;;
  3. ;;;; Copyright (C) 2010, 2011 Free Software Foundation, Inc.
  4. ;;;;
  5. ;;;; This library is free software; you can redistribute it and/or
  6. ;;;; modify it under the terms of the GNU Lesser General Public
  7. ;;;; License as published by the Free Software Foundation; either
  8. ;;;; version 3 of the License, or (at your option) any later version.
  9. ;;;;
  10. ;;;; This library is distributed in the hope that it will be useful,
  11. ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  13. ;;;; Lesser General Public License for more details.
  14. ;;;;
  15. ;;;; You should have received a copy of the GNU Lesser General Public
  16. ;;;; License along with this library; if not, write to the Free Software
  17. ;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  18. ;;;;
  19. (define-module (ice-9 peg cache)
  20. #:export (cg-cached-parser))
  21. ;; The results of parsing using a nonterminal are cached. Think of it like a
  22. ;; hash with no conflict resolution. Process for deciding on the cache size
  23. ;; wasn't very scientific; just ran the benchmarks and stopped a little after
  24. ;; the point of diminishing returns on my box.
  25. (define *cache-size* 512)
  26. (define (make-cache)
  27. (make-vector *cache-size* #f))
  28. ;; given a syntax object which is a parser function, returns syntax
  29. ;; which, if evaluated, will become a parser function that uses a cache.
  30. (define (cg-cached-parser parser)
  31. #`(let ((cache (make-cache)))
  32. (lambda (str strlen at)
  33. (let* ((vref (vector-ref cache (modulo at *cache-size*))))
  34. ;; Check to see whether the value is cached.
  35. (if (and vref (eq? (car vref) str) (= (cadr vref) at))
  36. (caddr vref);; If it is return it.
  37. (let ((fres ;; Else calculate it and cache it.
  38. (#,parser str strlen at)))
  39. (vector-set! cache (modulo at *cache-size*)
  40. (list str at fres))
  41. fres))))))