]> code.delx.au - gnu-emacs-elpa/blob - packages/wisi/wisi.el
* wcheck-mode: New package.
[gnu-emacs-elpa] / packages / wisi / wisi.el
1 ;;; wisi.el --- Utilities for implementing an indentation/navigation engine using a generalized LALR parser
2 ;;
3 ;; Copyright (C) 2012 - 2014 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Stephen Leake <stephen_leake@member.fsf.org>
6 ;; Version: 1.0.4
7 ;; package-requires: ((cl-lib "0.4") (emacs "24.2"))
8 ;; URL: http://stephe-leake.org/emacs/ada-mode/emacs-ada-mode.html
9 ;;
10 ;; This file is part of GNU Emacs.
11 ;;
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
16 ;;
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
21 ;;
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24 ;;
25
26 ;;; Commentary:
27
28 ;;;; History: first experimental version Oct 2012
29 ;;
30 ;;;; indentation algorithm overview
31 ;;
32 ;; This design is inspired in part by experience writing a SMIE
33 ;; indentation engine for Ada, and the wisent parser.
34 ;;
35 ;; The general approach to indenting a given token is to find the
36 ;; start of the statement it is part of, or some other relevant point
37 ;; in the statement, and indent relative to that. So we need a parser
38 ;; that lets us find statement indent points from arbitrary places in
39 ;; the code.
40 ;;
41 ;; For example, the grammar for Ada as represented by the EBNF in LRM
42 ;; Annex P is not LALR(1), so we use a generalized LALR(1) parser (see
43 ;; wisi-parse, wisi-compile).
44 ;;
45 ;; The parser actions cache indentation and other information as text
46 ;; properties of tokens in statements.
47 ;;
48 ;; An indentation engine moves text in the buffer, as does user
49 ;; editing, so we can't rely on character positions remaining
50 ;; constant. So the parser actions use markers to store
51 ;; positions. Text properties also move with the text.
52 ;;
53 ;; The stored information includes a marker at each statement indent
54 ;; point. Thus, the indentation algorithm is: find the previous token
55 ;; with cached information, and either indent from it, or fetch from
56 ;; it the marker for a previous statement indent point, and indent
57 ;; relative to that.
58 ;;
59 ;; Since we have a cache (the text properties), we need to consider
60 ;; when to invalidate it. Ideally, we invalidate only when a change to
61 ;; the buffer would change the result of a parse that crosses that
62 ;; change, or starts after that change. Changes in whitespace
63 ;; (indentation and newlines) do not affect an Ada parse. Other
64 ;; languages are sensitive to newlines (Bash for example) or
65 ;; indentation (Python). Adding comments does not change a parse,
66 ;; unless code is commented out. For now we invalidate the cache after
67 ;; the edit point if the change involves anything other than
68 ;; whitespace.
69 ;;
70 ;;;; comparison to the SMIE parser
71 ;;
72 ;; The central problem to be solved in building the SMIE parser is
73 ;; grammar precedence conflicts; the general solution is refining
74 ;; keywords so that each new keyword can be assigned a unique
75 ;; precedence. This means ad hoc code must be written to determine the
76 ;; correct refinement for each language keyword from the surrounding
77 ;; tokens. In effect, for a complex language like Ada, the knowledge
78 ;; of the language grammar is mostly embedded in the refinement code;
79 ;; only a small amount is in the refined grammar. Implementing a SMIE
80 ;; parser for a new language involves the same amount of work as the
81 ;; first language.
82 ;;
83 ;; Using a generalized LALR parser avoids that particular problem;
84 ;; assuming the language is already defined by a grammar, it is only a
85 ;; matter of a format change to teach the wisi parser the
86 ;; language. The problem in a wisi indentation engine is caching the
87 ;; output of the parser in a useful way, since we can't start the
88 ;; parser from arbitrary places in the code (as we can with the SMIE
89 ;; parser). A second problem is determining when to invalidate the
90 ;; cache. But these problems are independent of the language being
91 ;; parsed, so once we have one wisi indentation engine working,
92 ;; adapting it to new languages should be quite simple.
93 ;;
94 ;; The SMIE parser does not find the start of each statement, only the
95 ;; first language keyword in each statement; additional code must be
96 ;; written to find the statement start and indent points. The wisi
97 ;; parser finds the statement start and indent points directly.
98 ;;
99 ;; In SMIE, it is best if each grammar rule is a complete statement,
100 ;; so forward-sexp will traverse the entire statement. If nested
101 ;; non-terminals are used, forward-sexp may stop inside one of the
102 ;; nested non-terminals. This problem does not occur with the wisi
103 ;; parser.
104 ;;
105 ;; A downside of the wisi parser is conflicts in the grammar; they can
106 ;; be much more difficult to resolve than in the SMIE parser. The
107 ;; generalized parser helps by handling conflicts, but it does so by
108 ;; running multiple parsers in parallel, persuing each choice in the
109 ;; conflict. If the conflict is due to a genuine ambiguity, both paths
110 ;; will succeed, which causes the parse to fail, since it is not clear
111 ;; which set of text properties to store. Even if one branch
112 ;; ultimately fails, running parallel parsers over large sections of
113 ;; code is slow. Finally, this approach can lead to exponential growth
114 ;; in the number of parsers. So grammar conflicts must still be
115 ;; analyzed and minimized.
116 ;;
117 ;; In addition, the complete grammar must be specified; in smie, it is
118 ;; often possible to specify a subset of the grammar.
119 ;;
120 ;;;; grammar compiler and parser
121 ;;
122 ;; Since we are using a generalized LALR(1) parser, we cannot use any
123 ;; of the wisent grammar functions. We use OpenToken wisi-generate
124 ;; to compile BNF to Elisp source (similar to
125 ;; semantic-grammar-create-package), and wisi-compile-grammar to
126 ;; compile that to the parser table.
127 ;;
128 ;; Semantic provides a complex lexer, more complicated than we need
129 ;; for indentation. So we use the elisp lexer, which consists of
130 ;; `forward-comment', `skip-syntax-forward', and `scan-sexp'. We wrap
131 ;; that in functions that return tokens in the form wisi-parse
132 ;; expects.
133 ;;
134 ;;;; code style
135 ;;
136 ;; 'wisi' was originally short for "wisent indentation engine", but
137 ;; now is just a name.
138 ;;
139 ;; not using lexical-binding because we support Emacs 23
140 ;;
141 ;;;;;
142
143 ;;; Code:
144
145 (require 'cl-lib)
146 (require 'wisi-parse)
147
148 ;; WORKAROUND: for some reason, this condition doesn't work in batch mode!
149 ;; (when (and (= emacs-major-version 24)
150 ;; (= emacs-minor-version 2))
151 (require 'wisi-compat-24.2)
152 ;;)
153
154 ;;;; lexer
155
156 (defvar-local wisi-class-list nil)
157 (defvar-local wisi-keyword-table nil)
158 (defvar-local wisi-punctuation-table nil)
159 (defvar-local wisi-punctuation-table-max-length 0)
160 (defvar-local wisi-string-double-term nil);; string delimited by double quotes
161 (defvar-local wisi-string-quote-escape-doubled nil
162 "Non-nil if a string delimiter is escaped by doubling it (as in Ada).")
163 (defvar-local wisi-string-quote-escape nil
164 "Cons '(delim . character) where 'character' escapes quotes in strings delimited by 'delim'.")
165 (defvar-local wisi-string-single-term nil) ;; string delimited by single quotes
166 (defvar-local wisi-symbol-term nil)
167
168 (defun wisi-forward-token (&optional text-only)
169 "Move point forward across one token, skipping leading whitespace and comments.
170 Return the corresponding token, in a format determined by TEXT-ONLY:
171 TEXT-ONLY t: text
172 TEXT-ONLY nil: (token text start . end)
173 where:
174 `token' is a token symbol (not string) from `wisi-punctuation-table',
175 `wisi-keyword-table', `wisi-string-double-term', `wisi-string-double-term' or `wisi-symbol-term'.
176
177 `text' is the token text from the buffer
178
179 `start, end' are the character positions in the buffer of the start
180 and end of the token text.
181
182 If at end of buffer, returns `wisent-eoi-term'."
183 (forward-comment (point-max))
184 ;; skips leading whitespace, comment, trailing whitespace.
185
186 (let ((start (point))
187 ;; (info "(elisp)Syntax Table Internals" "*info elisp syntax*")
188 (syntax (syntax-class (syntax-after (point))))
189 token-id token-text)
190 (cond
191 ((eobp)
192 (setq token-text "")
193 (setq token-id wisent-eoi-term))
194
195 ((eq syntax 1)
196 ;; punctuation. Find the longest matching string in wisi-punctuation-table
197 (forward-char 1)
198 (let ((next-point (point))
199 temp-text temp-id done)
200 (while (not done)
201 (setq temp-text (buffer-substring-no-properties start (point)))
202 (setq temp-id (car (rassoc temp-text wisi-punctuation-table)))
203 (when temp-id
204 (setq token-text temp-text
205 token-id temp-id
206 next-point (point)))
207 (if (or
208 (eobp)
209 (= (- (point) start) wisi-punctuation-table-max-length))
210 (setq done t)
211 (forward-char 1))
212 )
213 (goto-char next-point)))
214
215 ((memq syntax '(4 5)) ;; open, close parenthesis
216 (forward-char 1)
217 (setq token-text (buffer-substring-no-properties start (point)))
218 (setq token-id (symbol-value (intern-soft token-text wisi-keyword-table))))
219
220 ((eq syntax 7)
221 ;; string quote, either single or double. we assume point is before the start quote, not the end quote
222 (let ((delim (char-after (point)))
223 (forward-sexp-function nil))
224 (forward-sexp)
225 ;; point is now after the end quote; check for an escaped quote
226 (while (or
227 (and wisi-string-quote-escape-doubled
228 (eq (char-after (point)) delim))
229 (and (eq delim (car wisi-string-quote-escape))
230 (eq (char-before (1- (point))) (cdr wisi-string-quote-escape))))
231 (forward-sexp))
232 (setq token-text (buffer-substring-no-properties start (point)))
233 (setq token-id (if (= delim ?\") wisi-string-double-term wisi-string-single-term))))
234
235 (t ;; assuming word syntax
236 (skip-syntax-forward "w_'")
237 (setq token-text (buffer-substring-no-properties start (point)))
238 (setq token-id
239 (or (symbol-value (intern-soft (downcase token-text) wisi-keyword-table))
240 wisi-symbol-term)))
241 );; cond
242
243 (unless token-id
244 (error (wisi-error-msg "unrecognized token '%s'" (buffer-substring-no-properties start (point)))))
245
246 (if text-only
247 token-text
248 (cons token-id (cons token-text (cons start (point)))))
249 ))
250
251 (defun wisi-backward-token ()
252 "Move point backward across one token, skipping whitespace and comments.
253 Return (nil text start . end) - same structure as
254 wisi-forward-token, but does not look up symbol."
255 (forward-comment (- (point)))
256 ;; skips leading whitespace, comment, trailing whitespace.
257
258 ;; (info "(elisp)Syntax Table Internals" "*info elisp syntax*")
259 (let ((end (point))
260 (syntax (syntax-class (syntax-after (1- (point))))))
261 (cond
262 ((bobp) nil)
263
264 ((memq syntax '(4 5)) ;; open, close parenthesis
265 (backward-char 1))
266
267 ((eq syntax 7)
268 ;; a string quote. we assume we are after the end quote, not the start quote
269 (let ((forward-sexp-function nil))
270 (forward-sexp -1)))
271
272 (t
273 (if (zerop (skip-syntax-backward "."))
274 (skip-syntax-backward "w_'")))
275 )
276 (cons nil (cons (buffer-substring-no-properties (point) end) (cons (point) end)))
277 ))
278
279 ;;;; token info cache
280 ;;
281 ;; the cache stores the results of parsing as text properties on
282 ;; keywords, for use by the indention and motion engines.
283
284 (cl-defstruct
285 (wisi-cache
286 (:constructor wisi-cache-create)
287 (:copier nil))
288 nonterm;; nonterminal from parse (set by wisi-statement-action)
289
290 token
291 ;; terminal symbol from wisi-keyword-table or
292 ;; wisi-punctuation-table, or lower-level nonterminal from parse
293 ;; (set by wisi-statement-action)
294
295 last ;; pos of last char in token, relative to first (0 indexed)
296
297 class
298 ;; arbitrary lisp symbol, used for indentation and navigation.
299 ;; some classes are defined by wisi:
300 ;;
301 ;; 'block-middle - a block keyword (ie: if then else end), not at the start of a statement
302 ;;
303 ;; 'block-start - a block keyword at the start of a statement
304 ;;
305 ;; 'statement-start - the start of a statement
306 ;;
307 ;; 'open-paren
308 ;;
309 ;; others are language-specific
310
311 containing
312 ;; Marker at the containing keyword for this token.
313 ;; A containing keyword is an indent point; the start of a
314 ;; statement, or 'begin', 'then' or 'else' for a block of
315 ;; statements, etc.
316 ;; nil only for first token in buffer
317
318 prev ;; marker at previous motion token in statement; nil if none
319 next ;; marker at next motion token in statement; nil if none
320 end ;; marker at token at end of current statement
321 )
322
323 (defvar-local wisi-cache-max 0
324 "Maximimum position in buffer where wisi token cache is valid.")
325
326 (defvar-local wisi-parse-table nil)
327
328 (defvar-local wisi-parse-failed nil
329 "Non-nil when a recent parse has failed - cleared when parse succeeds.")
330
331 (defvar-local wisi-parse-try nil
332 "Non-nil when parse is needed - cleared when parse succeeds.")
333
334 (defvar-local wisi-change-need-invalidate nil)
335
336 (defun wisi-invalidate-cache()
337 "Invalidate the wisi token cache for the current buffer.
338 Also invalidate the Emacs syntax cache."
339 (interactive)
340 (setq wisi-cache-max 0)
341 (setq wisi-parse-try t)
342 (syntax-ppss-flush-cache (point-min))
343 (with-silent-modifications
344 (remove-text-properties (point-min) (point-max) '(wisi-cache))))
345
346 (defun wisi-before-change (begin end)
347 "For `before-change-functions'."
348 ;; begin . end is range of text being deleted
349
350 ;; If jit-lock-after-change is before wisi-after-change in
351 ;; after-change-functions, it might use any invalid caches in the
352 ;; inserted text.
353 ;;
354 ;; So we check for that here, and ensure it is after
355 ;; wisi-after-change, which deletes the invalid caches
356 (when (boundp 'jit-lock-mode)
357 (when (memq 'wisi-after-change (memq 'jit-lock-after-change after-change-functions))
358 (setq after-change-functions (delete 'wisi-after-change after-change-functions))
359 (add-hook 'after-change-functions 'wisi-after-change nil t))
360 )
361
362 (save-excursion
363 ;; don't invalidate parse for whitespace, string, or comment changes
364 (let (;; (info "(elisp)Parser State")
365 (state (syntax-ppss begin)))
366 ;; syntax-ppss has moved point to "begin".
367 (cond
368 ((or
369 (nth 3 state); in string
370 (nth 4 state)); in comment
371 ;; FIXME: check that entire range is in comment or string
372 (setq wisi-change-need-invalidate nil))
373
374 ((progn
375 (skip-syntax-forward " " end);; does not skip newline
376 (eq (point) end))
377 (setq wisi-change-need-invalidate nil))
378
379 (t (setq wisi-change-need-invalidate t))
380 ))))
381
382 (defun wisi-after-change (begin end length)
383 "For `after-change-functions'."
384 ;; begin . end is range of text being inserted (may be empty)
385
386 ;; (syntax-ppss-flush-cache begin) is in before-change-functions
387
388 (cond
389 (wisi-parse-failed
390 ;; The parse was failing, probably due to bad syntax; this change
391 ;; may have fixed it, so try reparse.
392 (setq wisi-parse-try t)
393
394 ;; remove 'wisi-cache on inserted text, which could have caches
395 ;; from before the failed parse, and are in any case invalid.
396 (with-silent-modifications
397 (remove-text-properties begin end '(wisi-cache)))
398 )
399
400 ((>= wisi-cache-max begin)
401 ;; The parse had succeeded past the start of the inserted
402 ;; text.
403 (save-excursion
404 (let ((need-invalidate t)
405 ;; (info "(elisp)Parser State")
406 (state (syntax-ppss begin)))
407 ;; syntax-ppss has moved point to "begin".
408 (cond
409 (wisi-change-need-invalidate
410 ;; wisi-before change determined the removed text alters the
411 ;; parse
412 nil)
413
414 ((or
415 (nth 3 state); in string
416 (nth 4 state)); in comment
417 ;; FIXME: insert newline in comment to create non-comment!?
418 ;; or paste a chunk of code
419 ;; => check that all of change region is comment or string
420 (setq need-invalidate nil)
421 ;; no caches to remove
422 )
423
424 ((progn
425 (skip-syntax-forward " " end);; does not skip newlines
426 (eq (point) end))
427 (setq need-invalidate nil))
428
429 (t nil)
430 )
431
432 (if need-invalidate
433 ;; The inserted or deleted text could alter the parse;
434 ;; wisi-invalidate-cache removes all 'wisi-cache.
435 (wisi-invalidate-cache)
436
437 ;; else move cache-max by the net change length. We don't
438 ;; need to delete 'wisi-cache in the inserted text, because
439 ;; if there were any it would not pass the above.
440 (setq wisi-cache-max
441 (+ wisi-cache-max (- end begin length))))
442 )
443 ))
444
445 (t
446 ;; parse never attempted, or only done to before BEGIN. Just
447 ;; remove 'wisi-cache
448 (with-silent-modifications
449 (remove-text-properties begin end '(wisi-cache)))
450 )
451 ))
452
453 (defun wisi-get-cache (pos)
454 "Return `wisi-cache' struct from the `wisi-cache' text property at POS.
455 If accessing cache at a marker for a token as set by `wisi-cache-tokens', POS must be (1- mark)."
456 (get-text-property pos 'wisi-cache))
457
458 (defvar-local wisi-parse-error-msg nil)
459
460 (defun wisi-goto-error ()
461 "Move point to position in last error message (if any)."
462 (when (string-match ":\\([0-9]+\\):\\([0-9]+\\):" wisi-parse-error-msg)
463 (let ((line (string-to-number (match-string 1 wisi-parse-error-msg)))
464 (col (string-to-number (match-string 2 wisi-parse-error-msg))))
465 (goto-char (point-min))
466 (forward-line (1- line))
467 (forward-char col))))
468
469 (defun wisi-show-parse-error ()
470 "Show last wisi-parse error."
471 (interactive)
472 (if wisi-parse-failed
473 (progn
474 (message wisi-parse-error-msg)
475 (wisi-goto-error))
476 (message "parse succeeded")))
477
478 (defun wisi-validate-cache (pos)
479 "Ensure cached data is valid at least up to POS in current buffer."
480 (let ((msg (format "wisi: parsing %s:%d ..." (buffer-name) (line-number-at-pos))))
481 (when (and wisi-parse-try
482 (< wisi-cache-max pos))
483 (when (> wisi-debug 0)
484 (message msg))
485
486 (setq wisi-parse-try nil)
487 (setq wisi-parse-error-msg nil)
488 (save-excursion
489 (goto-char wisi-cache-max)
490 (if (> wisi-debug 1)
491 ;; let debugger stop in wisi-parse
492 (progn
493 (wisi-parse wisi-parse-table 'wisi-forward-token)
494 (setq wisi-cache-max (point))
495 (setq wisi-parse-failed nil))
496 ;; else capture errors from bad syntax, so higher level functions can try to continue
497 (condition-case err
498 (progn
499 (wisi-parse wisi-parse-table 'wisi-forward-token)
500 (setq wisi-cache-max (point))
501 (setq wisi-parse-failed nil))
502 (wisi-parse-error
503 (setq wisi-parse-failed t)
504 (setq wisi-parse-error-msg (cdr err)))
505 )))
506 (if wisi-parse-error-msg
507 ;; error
508 (when (> wisi-debug 0)
509 (message "%s error" msg)
510 (wisi-goto-error)
511 (error wisi-parse-error-msg))
512 ;; no msg; success
513 (when (> wisi-debug 0)
514 (message "%s done" msg)))
515 )))
516
517 (defun wisi-get-containing-cache (cache)
518 "Return cache from (wisi-cache-containing CACHE)."
519 (let ((containing (wisi-cache-containing cache)))
520 (and containing
521 (wisi-get-cache (1- containing)))))
522
523 (defun wisi-cache-text (cache)
524 "Return property-less buffer substring designated by cache.
525 Point must be at cache."
526 (buffer-substring-no-properties (point) (+ (point) (wisi-cache-last cache))))
527
528 ;;;; parse actions
529
530 (defun wisi-set-end (tokens end-mark)
531 "Set END-MARK on all unset caches in TOKENS."
532 (let ((tokens-t tokens))
533 (while tokens-t
534 (let* ((token (pop tokens-t))
535 (region (cddr token))
536 cache)
537 (when region
538 (goto-char (car region))
539 (setq cache (wisi-get-cache (car region)))
540 (when (not cache)
541 ;; token is non-terminal; first terminal doesn't have cache.
542 (setq cache (wisi-forward-cache)))
543 (while (and cache
544 (< (point) (cdr region)))
545 (if (not (wisi-cache-end cache))
546 (setf (wisi-cache-end cache) end-mark)
547 (goto-char (wisi-cache-end cache))
548 )
549 (setq cache (wisi-forward-cache))
550 ))
551 ))
552 ))
553
554 (defvar wisi-tokens nil);; keep byte-compiler happy; `wisi-tokens' is bound in action created by wisi-semantic-action
555 (defun wisi-statement-action (&rest pairs)
556 "Cache information in text properties of tokens.
557 Intended as a grammar non-terminal action.
558
559 PAIRS is of the form [TOKEN-NUMBER CLASS] ... where TOKEN-NUMBER
560 is the (1 indexed) token number in the production, CLASS is the wisi class of
561 that token. Use in a grammar action as:
562 (wisi-statement-action 1 'statement-start 7 'statement-end)"
563 (save-excursion
564 (let ((first-item t)
565 first-keyword-mark
566 (override-start nil))
567 (while pairs
568 (let* ((number (1- (pop pairs)))
569 (region (cddr (nth number wisi-tokens)));; wisi-tokens is let-bound in wisi-parse-reduce
570 (token (car (nth number wisi-tokens)))
571 (class (pop pairs))
572 (mark
573 ;; Marker one char into token, so indent-line-to
574 ;; inserts space before the mark, not after
575 (when region (copy-marker (1+ (car region)))))
576 cache)
577
578 (unless (memq class wisi-class-list)
579 (error "%s not in wisi-class-list" class))
580
581 (if region
582 (progn
583 (if (setq cache (wisi-get-cache (car region)))
584 ;; We are processing a previously set non-terminal; ie generic_formal_part in
585 ;;
586 ;; generic_package_declaration : generic_formal_part package_specification SEMICOLON
587 ;; (wisi-statement-action 1 'block-start 2 'block-middle 3 'statement-end)
588 ;;
589 ;; or simple_statement in
590 ;;
591 ;; statement : label_opt simple_statement
592 ;;
593 ;; override nonterm, class and containing
594 (progn
595 (cl-case (wisi-cache-class cache)
596 (block-start
597 (setf (wisi-cache-class cache)
598 (cond
599 ((eq override-start nil)
600 (cond
601 ((memq class '(block-start statement-start)) 'block-start)
602 (t 'block-middle)))
603
604 ((memq override-start '(block-start statement-start)) 'block-start)
605
606 (t (error "unexpected override-start"))
607 )))
608 (t
609 (setf (wisi-cache-class cache) (or override-start class)))
610 )
611 (setf (wisi-cache-nonterm cache) $nterm)
612 (setf (wisi-cache-containing cache) first-keyword-mark))
613
614 ;; else create new cache
615 (with-silent-modifications
616 (put-text-property
617 (car region)
618 (1+ (car region))
619 'wisi-cache
620 (wisi-cache-create
621 :nonterm $nterm;; $nterm defined in wisi-semantic-action
622 :token token
623 :last (- (cdr region) (car region))
624 :class (or override-start class)
625 :containing first-keyword-mark)
626 )))
627
628 (when first-item
629 (setq first-item nil)
630 (when (or override-start
631 (memq class '(block-middle block-start statement-start)))
632 (setq override-start nil)
633 (setq first-keyword-mark mark)))
634
635 (when (eq class 'statement-end)
636 (wisi-set-end wisi-tokens (copy-marker (1+ (car region)))))
637 )
638
639 ;; region is nil when a production is empty; if the first
640 ;; token is a start, override the class on the next token.
641 (when (and first-item
642 (memq class '(block-middle block-start statement-start)))
643 (setq override-start class)))
644 ))
645 )))
646
647 (defun wisi-containing-action (containing-token contained-token)
648 "Set containing marks in all tokens in CONTAINED-TOKEN with null containing mark to marker pointing to CONTAINING-TOKEN.
649 If CONTAINING-TOKEN is empty, the next token number is used."
650 ;; wisi-tokens is is bound in action created by wisi-semantic-action
651 (let* ((containing-region (cddr (nth (1- containing-token) wisi-tokens)))
652 (contained-region (cddr (nth (1- contained-token) wisi-tokens))))
653
654 (unless containing-region ;;
655 (signal 'wisi-parse-error
656 (wisi-error-msg
657 "wisi-containing-action: containing-region '%s' is empty. grammar error; bad action"
658 (nth 1 (nth (1- containing-token) wisi-tokens)))))
659
660 (unless (or (not contained-region) ;; contained-token is empty
661 (wisi-get-cache (car containing-region)))
662 (signal 'wisi-parse-error
663 (wisi-error-msg
664 "wisi-containing-action: containing-token '%s' has no cache. grammar error; missing action"
665 (nth 1 (nth (1- containing-token) wisi-tokens)))))
666
667 (while (not containing-region)
668 ;; containing-token is empty; use next
669 (setq containing-region (cddr (nth containing-token wisi-tokens))))
670
671 (when contained-region
672 ;; nil when empty production, may not contain any caches
673 (save-excursion
674 (goto-char (cdr contained-region))
675 (let ((cache (wisi-backward-cache))
676 (mark (copy-marker (1+ (car containing-region)))))
677 (while cache
678
679 ;; skip blocks that are already marked
680 (while (and (>= (point) (car contained-region))
681 (markerp (wisi-cache-containing cache)))
682 (goto-char (1- (wisi-cache-containing cache)))
683 (setq cache (wisi-get-cache (point))))
684
685 (if (or (and (= (car containing-region) (car contained-region))
686 (<= (point) (car contained-region)))
687 (< (point) (car contained-region)))
688 ;; done
689 (setq cache nil)
690
691 ;; else set mark, loop
692 (setf (wisi-cache-containing cache) mark)
693 (setq cache (wisi-backward-cache)))
694 ))))))
695
696 (defun wisi-motion-action (&rest token-numbers)
697 "Set prev/next marks in all tokens given by TOKEN-NUMBERS.
698 Each TOKEN-NUMBERS is one of:
699
700 number: the token number; mark that token
701
702 list (number token_id):
703 list (number (token_id token_id)):
704 mark all tokens with token_id in the nonterminal given by the number."
705 (save-excursion
706 (let (prev-keyword-mark
707 prev-cache
708 cache
709 mark)
710 (while token-numbers
711 (let ((token-number (pop token-numbers))
712 target-token
713 region)
714 (cond
715 ((numberp token-number)
716 (setq target-token nil)
717 (setq region (cddr (nth (1- token-number) wisi-tokens)))
718 (when region
719 (setq cache (wisi-get-cache (car region)))
720 (setq mark (copy-marker (1+ (car region))))
721
722 (when (and prev-keyword-mark
723 cache
724 (null (wisi-cache-prev cache)))
725 (setf (wisi-cache-prev cache) prev-keyword-mark)
726 (setf (wisi-cache-next prev-cache) mark))
727
728 (setq prev-keyword-mark mark)
729 (setq prev-cache cache)
730 ))
731
732 ((listp token-number)
733 ;; token-number may contain 0, 1, or more token_id; token_id may be a list
734 ;; the corresponding region may be empty
735 ;; there must have been a prev keyword
736 (setq target-token (cadr token-number))
737 (when (not (listp target-token))
738 (setq target-token (list target-token)))
739 (setq token-number (car token-number))
740 (setq region (cddr (nth (1- token-number) wisi-tokens)))
741 (when region ;; not an empty token
742 (goto-char (car region))
743 (while (wisi-forward-find-token target-token (cdr region) t)
744 (setq cache (wisi-get-cache (point)))
745 (setq mark (copy-marker (1+ (point))))
746
747 (when (null (wisi-cache-prev cache))
748 (setf (wisi-cache-prev cache) prev-keyword-mark)
749 (setf (wisi-cache-next prev-cache) mark)
750 (setq prev-keyword-mark mark)
751 (setq prev-cache cache))
752
753 (wisi-forward-token);; don't find same token again
754 ))
755 )
756
757 (t
758 (error "unexpected token-number %s" token-number))
759 )
760
761 ))
762 )))
763
764 ;;;; motion
765 (defun wisi-backward-cache ()
766 "Move point backward to the beginning of the first token preceding point that has a cache.
767 Returns cache, or nil if at beginning of buffer."
768 (let (cache pos)
769 (setq pos (previous-single-property-change (point) 'wisi-cache))
770 ;; There are three cases:
771 ;;
772 ;; 1) caches separated by non-cache chars: 'if ... then'
773 ;; pos is before 'f', cache is on 'i'
774 ;;
775 ;; 2) caches not separated: ');'
776 ;; pos is before ';', cache is on ';'
777 ;;
778 ;; 3) at bob; pos is nil
779 ;;
780 (if pos
781 (progn
782 (setq cache (get-text-property pos 'wisi-cache))
783 (if cache
784 ;; case 2
785 (goto-char pos)
786 ;; case 1
787 (setq cache (get-text-property (1- pos) 'wisi-cache))
788 (goto-char (1- pos))))
789 ;; at bob
790 (goto-char (point-min))
791 (setq cache nil))
792 cache
793 ))
794
795 (defun wisi-forward-cache ()
796 "Move point forward to the beginning of the first token after point that has a cache.
797 Returns cache, or nil if at end of buffer."
798 (let (cache pos)
799 (when (get-text-property (point) 'wisi-cache)
800 ;; on a cache; get past it
801 (goto-char (1+ (point))))
802
803 (setq cache (get-text-property (point) 'wisi-cache))
804 (if cache
805 nil
806
807 (setq pos (next-single-property-change (point) 'wisi-cache))
808 (if pos
809 (progn
810 (goto-char pos)
811 (setq cache (get-text-property pos 'wisi-cache)))
812 ;; at eob
813 (goto-char (point-max))
814 (setq cache nil))
815 )
816 cache
817 ))
818
819 (defun wisi-forward-find-class (class limit)
820 "Search forward for a token that has a cache with CLASS.
821 Return cache, or nil if at end of buffer.
822 If LIMIT (a buffer position) is reached, throw an error."
823 (let ((cache (wisi-forward-cache)))
824 (while (not (eq class (wisi-cache-class cache)))
825 (setq cache (wisi-forward-cache))
826 (when (>= (point) limit)
827 (error "cache with class %s not found" class)))
828 cache))
829
830 (defun wisi-forward-find-token (token limit &optional noerror)
831 "Search forward for a token that has a cache with TOKEN.
832 If point is at a matching token, return that token.
833 TOKEN may be a list; stop on any cache that has a member of the list.
834 Return cache, or nil if at end of buffer.
835 If LIMIT (a buffer position) is reached, then if NOERROR is nil, throw an
836 error, if non-nil, return nil."
837 (let ((token-list (cond
838 ((listp token) token)
839 (t (list token))))
840 (cache (wisi-get-cache (point)))
841 (done nil))
842 (while (not (or done
843 (and cache
844 (memq (wisi-cache-token cache) token-list))))
845 (setq cache (wisi-forward-cache))
846 (when (>= (point) limit)
847 (if noerror
848 (progn
849 (setq done t)
850 (setq cache nil))
851 (error "cache with token %s not found" token))))
852 cache))
853
854 (defun wisi-forward-find-nonterm (nonterm limit)
855 "Search forward for a token that has a cache with NONTERM.
856 NONTERM may be a list; stop on any cache that has a member of the list.
857 Return cache, or nil if at end of buffer.
858 If LIMIT (a buffer position) is reached, throw an error."
859 (let ((nonterm-list (cond
860 ((listp nonterm) nonterm)
861 (t (list nonterm))))
862 (cache (wisi-forward-cache)))
863 (while (not (memq (wisi-cache-nonterm cache) nonterm-list))
864 (setq cache (wisi-forward-cache))
865 (when (>= (point) limit)
866 (error "cache with nonterm %s not found" nonterm)))
867 cache))
868
869 (defun wisi-goto-cache-next (cache)
870 (goto-char (1- (wisi-cache-next cache)))
871 (wisi-get-cache (point))
872 )
873
874 (defun wisi-forward-statement-keyword ()
875 "If not at a cached token, move forward to next
876 cache. Otherwise move to cache-next, or next cache if nil.
877 Return cache found."
878 (wisi-validate-cache (point-max))
879 (let ((cache (wisi-get-cache (point))))
880 (if cache
881 (let ((next (wisi-cache-next cache)))
882 (if next
883 (goto-char (1- next))
884 (wisi-forward-token)
885 (wisi-forward-cache)))
886 (wisi-forward-cache))
887 )
888 (wisi-get-cache (point))
889 )
890
891 (defun wisi-backward-statement-keyword ()
892 "If not at a cached token, move backward to prev
893 cache. Otherwise move to cache-prev, or prev cache if nil."
894 (wisi-validate-cache (point-max))
895 (let ((cache (wisi-get-cache (point))))
896 (if cache
897 (let ((prev (wisi-cache-prev cache)))
898 (if prev
899 (goto-char (1- prev))
900 (wisi-backward-cache)))
901 (wisi-backward-cache))
902 ))
903
904 (defun wisi-goto-containing (cache &optional error)
905 "Move point to containing token for CACHE, return cache at that point."
906 (cond
907 ((markerp (wisi-cache-containing cache))
908 (goto-char (1- (wisi-cache-containing cache)))
909 (wisi-get-cache (point)))
910 (t
911 (when error
912 (error "already at outermost containing token")))
913 ))
914
915 (defun wisi-goto-containing-paren (cache)
916 "Move point to just after the open-paren containing CACHE.
917 Return cache for paren, or nil if no containing paren."
918 (while (and cache
919 (not (eq (wisi-cache-class cache) 'open-paren)))
920 (setq cache (wisi-goto-containing cache)))
921 (when cache
922 (forward-char 1))
923 cache)
924
925 (defun wisi-goto-start (cache)
926 "Move point to containing ancestor of CACHE that has class block-start or statement-start.
927 Return start cache."
928 (when
929 ;; cache nil at bob
930 (while (and cache
931 (not (memq (wisi-cache-class cache) '(block-start statement-start))))
932 (setq cache (wisi-goto-containing cache)))
933 )
934 cache)
935
936 (defun wisi-goto-end-1 (cache)
937 (goto-char (1- (wisi-cache-end cache))))
938
939 (defun wisi-goto-end ()
940 "Move point to token at end of statement point is in or before."
941 (interactive)
942 (wisi-validate-cache (point-max))
943 (let ((cache (or (wisi-get-cache (point))
944 (wisi-forward-cache))))
945 (when (wisi-cache-end cache)
946 ;; nil when cache is statement-end
947 (wisi-goto-end-1 cache))
948 ))
949
950 (defun wisi-next-statement-cache (cache)
951 "Move point to CACHE-next, return cache; error if nil."
952 (when (not (markerp (wisi-cache-next cache)))
953 (error "no next statement cache"))
954 (goto-char (1- (wisi-cache-next cache)))
955 (wisi-get-cache (point)))
956
957 (defun wisi-prev-statement-cache (cache)
958 "Move point to CACHE-next, return cache; error if nil."
959 (when (not (markerp (wisi-cache-prev cache)))
960 (error "no prev statement cache"))
961 (goto-char (1- (wisi-cache-prev cache)))
962 (wisi-get-cache (point)))
963
964 ;;;; indentation
965
966 (defun wisi-comment-indent ()
967 "For `comment-indent-function'. Indent single line comment to
968 the comment on the previous line."
969 ;; This should only be called by comment-indent-new-line or
970 ;; fill-comment-paragraph, so there will be a preceding comment line
971 ;; that we can trust.
972 (save-excursion
973 (forward-comment -1)
974 (if (looking-at comment-start)
975 (current-column)
976 (error "wisi-comment-indent called after non-comment"))))
977
978 (defun wisi-indent-current (offset)
979 "Return indentation OFFSET relative to indentation of current line."
980 (+ (current-indentation) offset)
981 )
982
983 (defun wisi-indent-paren (offset)
984 "Return indentation OFFSET relative to preceding open paren."
985 (save-excursion
986 (goto-char (nth 1 (syntax-ppss)))
987 (+ (current-column) offset)))
988
989 (defun wisi-indent-start (offset cache)
990 "Return indentation of OFFSET relative to containing ancestor
991 of CACHE with class statement-start or block-start."
992 (wisi-goto-start cache)
993 (+ (current-indentation) offset))
994
995 (defun wisi-indent-statement ()
996 "Indent region given by `wisi-goto-start' on cache at or before point, then wisi-cache-end."
997 ;; force reparse, in case parser got confused
998 (let ((wisi-parse-try t))
999 (wisi-validate-cache (point)))
1000
1001 (save-excursion
1002 (let ((cache (or (wisi-get-cache (point))
1003 (wisi-backward-cache))))
1004 (when cache
1005 ;; can be nil if in header comment
1006 (let ((start (progn (wisi-goto-start cache) (point)))
1007 (end (progn
1008 (when (wisi-cache-end cache)
1009 ;; nil when cache is statement-end
1010 (goto-char (1- (wisi-cache-end cache))))
1011 (point))))
1012 (indent-region start end)
1013 ))
1014 )))
1015
1016 (defvar-local wisi-indent-calculate-functions nil
1017 "Functions to calculate indentation. Each called with point
1018 before a token at the beginning of a line (at current
1019 indentation); return indentation column for that token, or
1020 nil. May move point. Calling stops when first function returns
1021 non-nil.")
1022
1023 (defvar-local wisi-post-parse-fail-hook
1024 "Function to reindent portion of buffer.
1025 Called from `wisi-indent-line' when a parse succeeds after
1026 failing; assumes user was editing code that is now syntactically
1027 correct. Must leave point at indentation of current line.")
1028
1029 (defvar-local wisi-indent-failed nil
1030 "Non-nil when wisi-indent-line fails due to parse failing; cleared when indent succeeds.")
1031
1032 (defun wisi-indent-line ()
1033 "Indent current line using the wisi indentation engine."
1034 (interactive)
1035
1036 (let* ((savep (point))
1037 (indent
1038 (or (save-excursion
1039 (wisi-validate-cache (point))
1040 (back-to-indentation)
1041 (when (>= (point) savep) (setq savep nil))
1042 (if wisi-parse-failed
1043 (progn
1044 ;; parse failed. Assume user is editing; indent to previous line, fix it after parse succeeds
1045 (setq wisi-indent-failed t)
1046 (forward-line -1);; safe at bob
1047 (back-to-indentation)
1048 (current-column))
1049
1050 ;; else parse succeeded
1051 (when wisi-indent-failed
1052 (setq wisi-indent-failed nil)
1053 (run-hooks 'wisi-post-parse-fail-hook))
1054 (with-demoted-errors
1055 (or (run-hook-with-args-until-success 'wisi-indent-calculate-functions) 0))
1056 )))))
1057 (if savep
1058 ;; point was inside line text; leave it there
1059 (save-excursion (indent-line-to indent))
1060 ;; point was before line text; move to start of text
1061 (indent-line-to indent))
1062 ))
1063
1064 ;;;; debug
1065 (defun wisi-parse-buffer ()
1066 (interactive)
1067 (syntax-propertize (point-max))
1068 (wisi-invalidate-cache)
1069 (wisi-validate-cache (point-max)))
1070
1071 (defun wisi-show-cache ()
1072 "Show cache at point."
1073 (interactive)
1074 (message "%s" (wisi-get-cache (point))))
1075
1076 (defun wisi-show-token ()
1077 "Move forward across one keyword, show token_id."
1078 (interactive)
1079 (let ((token (wisi-forward-token)))
1080 (message "%s" (car token))))
1081
1082 (defun wisi-show-containing-or-previous-cache ()
1083 (interactive)
1084 (let ((cache (wisi-get-cache (point))))
1085 (if cache
1086 (message "containing %s" (wisi-goto-containing cache t))
1087 (message "previous %s" (wisi-backward-cache)))
1088 ))
1089
1090 ;;;;; setup
1091
1092 (defun wisi-setup (indent-calculate post-parse-fail class-list keyword-table token-table parse-table)
1093 "Set up a buffer for parsing files with wisi."
1094 (setq wisi-class-list class-list)
1095 (setq wisi-string-double-term (car (symbol-value (intern-soft "string-double" token-table))))
1096 (setq wisi-string-single-term (car (symbol-value (intern-soft "string-single" token-table))))
1097 (setq wisi-symbol-term (car (symbol-value (intern-soft "symbol" token-table))))
1098
1099 (setq wisi-punctuation-table (symbol-value (intern-soft "punctuation" token-table)))
1100 (setq wisi-punctuation-table-max-length 0)
1101 (let (fail)
1102 (dolist (item wisi-punctuation-table)
1103 (when item ;; default matcher can be nil
1104
1105 ;; check that all chars used in punctuation tokens have punctuation syntax
1106 (mapc (lambda (char)
1107 (when (not (= ?. (char-syntax char)))
1108 (setq fail t)
1109 (message "in %s, %c does not have punctuation syntax"
1110 (car item) char)))
1111 (cdr item))
1112
1113 (when (< wisi-punctuation-table-max-length (length (cdr item)))
1114 (setq wisi-punctuation-table-max-length (length (cdr item)))))
1115 )
1116 (when fail
1117 (error "aborting due to punctuation errors")))
1118
1119 (setq wisi-keyword-table keyword-table)
1120 (setq wisi-parse-table parse-table)
1121
1122 (setq wisi-indent-calculate-functions indent-calculate)
1123 (set (make-local-variable 'indent-line-function) 'wisi-indent-line)
1124
1125 (setq wisi-post-parse-fail-hook post-parse-fail)
1126 (setq wisi-indent-failed nil)
1127
1128 (add-hook 'before-change-functions 'wisi-before-change nil t)
1129 (add-hook 'after-change-functions 'wisi-after-change nil t)
1130
1131 ;; WORKAROUND: sometimes the first time font-lock is run,
1132 ;; syntax-propertize is not run properly, so we run it here
1133 (syntax-propertize (point-max))
1134
1135 (wisi-invalidate-cache)
1136 )
1137
1138 (provide 'wisi)
1139 ;;; wisi.el ends here