Skip to content

Instantly share code, notes, and snippets.

@felipeochoa
Last active September 4, 2018 14:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save felipeochoa/fbf31ea8279b64865a03d2a2e046dc4b to your computer and use it in GitHub Desktop.
Save felipeochoa/fbf31ea8279b64865a03d2a2e046dc4b to your computer and use it in GitHub Desktop.
Helper for debugging js2 ast
(defsubst js2-node-very-short-name (n)
"Return the very short name of node N as a string, e.g. `if'."
(replace-regexp-in-string "-node$" ""
(replace-regexp-in-string "^js2-" ""
(js2-node-short-name n))))
(defun debug-js2-ast ()
(interactive)
(if-let ((buf (current-buffer))
(top js2-mode-ast))
(progn
(pop-to-buffer "*js2-ast*")
(erase-buffer)
(let ((depth 0))
(js2-visit-ast
top
(lambda (node end-p)
(if end-p
(progn (cl-decf depth) (delete-char -1) (insert ")\n"))
(let* ((start (js2-node-abs-pos node))
(end (js2-node-abs-end node))
(s (replace-regexp-in-string "\\s-+" " "
(with-current-buffer buf
(buffer-substring-no-properties start end)))))
(insert (make-string (* 2 depth) ?\ )
"("
(js2-node-very-short-name node)
(format " %d %d" start end))
(when (< (current-column) 80)
(insert (format " %S"
(if (< (length s) (- 90 (current-column)))
s
(concat
(substring s 0 5)
"..."
(substring s -5))))))
(insert "\n"))
(cl-incf depth))))))
(error "No AST found")))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment