Subject: bug#17514: 24.3.91; enhancement: byte-optimize looking-at-p

From: Shigeru Fukaya <[email-masked]>
Date: Sat, 17 May 2014 07:07:43 +0900

looking-at-p is now a core function.
I think (looking-at-p "a") can be safely optimized to
(eq (following-char) ?a).
I found there are 8 such codes in the current trunk, and some more possibly
changable to looking-at-p from lookin-at.

I made an experimental byte-optimization code.

(defun byte-optimize-looking-at-p (form)
  (or (if (and (= (length form) 2)
               (stringp (nth 1 form)))
          (if (equal (nth 1 form) "")
              ;; (looking-at-p "")
              t
            (let ((c (byte-optimize-regexp-to-char (nth 1 form))))
              (if c
                  (list 'eq (list 'following-char) c)))))
      ;; fallback to original defsubst expansion
      (byte-compile-inline-expand form)))

(defun byte-optimize-regexp-to-char (regexp)
  (let* ((special '(?\[ ?* ?. ?\\ ?? ?+ ?^ ?$))
         (len (length regexp))
         (c (aref regexp (1- len))))
    (cond
     ;; don't accept '\0'.
     ;; as (following-char) at eob returns 0.
     ((eq c ?\0) nil)
     ;; "a" -> ?a
     ((= len 1) (unless (memq c special) c))
     ;; "\\." -> ?.  (only special characters, so far)
     ((= len 2) (when (and (eq (aref regexp 0) ?\\)
                           (memq c special))
                  c)))))

(put 'looking-at-p 'byte-optimizer 'byte-optimize-looking-at-p)
(put 'looking-at-p 'side-effect-free t)

-- Shigeru