aboutsummaryrefslogtreecommitdiffstats
path: root/extras/libparser-mode.el
blob: a97eb1f80bbe5f33b96d41e57a8c723b06baf342 (plain) (blame)
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
73
74
75
76
77
78
79
; See LICENSE file for copyright and license details.

(defvar libparser-mode-syntax-table
  (let ((st (make-syntax-table)))
    (modify-syntax-entry ?\" "\"" st)
    (modify-syntax-entry ?\\ "\\" st)

    (modify-syntax-entry ?\( "(" st)
    (modify-syntax-entry ?\) ")" st)
    (modify-syntax-entry ?\[ "(" st)
    (modify-syntax-entry ?\] ")" st)
    (modify-syntax-entry ?\{ "(" st)
    (modify-syntax-entry ?\} ")" st)
    (modify-syntax-entry ?\< "(" st)
    (modify-syntax-entry ?\> ")" st)

    (modify-syntax-entry ?\, "." st)
    (modify-syntax-entry ?\; "." st)
    (modify-syntax-entry ?! "." st)
    (modify-syntax-entry ?? "." st)

    (modify-syntax-entry ?\| "." st)
    (modify-syntax-entry ?= "." st)
    (modify-syntax-entry ?+ "." st)
    (modify-syntax-entry ?- "." st)

    st
  )
)

; TODO "*)" inside quotes in comments should not be recognised
(defun libparser--syntax-propertize (start end)
  (goto-char start)
  (while (search-forward "(*" end t)
    (unless (nth 3 (syntax-ppss))
      (put-text-property (match-beginning 0)
                          (1+ (match-beginning 0))
                         'syntax-table (string-to-syntax "<"))
      (put-text-property (1+ (match-beginning 0)) (match-end 0)
                         'syntax-table (string-to-syntax "<"))))
  (goto-char start)
  (while (search-forward "*)" end t)
    (unless (nth 3 (syntax-ppss))
      (put-text-property (1+ (match-beginning 0)) (match-end 0)
                         'syntax-table (string-to-syntax ">"))))
)

(defconst libparser-font-lock-keywords
  `(
    ; TODO only inside < > (identifier otherwise); or even better, colour whole < >
    ("\\_<0[xX][0-9A-Fa-f]+\\_>" . font-lock-constant-face)
    ("\\_<[0-9]+\\_>"            . font-lock-constant-face)

    ("\\_<[A-Za-z0-9][A-Za-z0-9_-]*\\_>-*" . font-lock-variable-name-face)
    ; _-prefixed identifiers are not coloured

    ("[=;]"       . font-lock-keyword-face)
    ("[][!?+{}-]" . font-lock-keyword-face)
    ; concatenations (,) and alternations (|) are not coloured

    ("[()]" . font-lock-bracket-face)
  )
)

(define-derived-mode libparser-mode prog-mode "libparser"
  "Major mode for libparser grammar files."
  :syntax-table libparser-mode-syntax-table

  (setq-local syntax-propertize-function #'libparser--syntax-propertize)

  (setq-local font-lock-defaults
              '(libparser-font-lock-keywords)
  )

  (setq-local comment-start "(*")
  (setq-local comment-end "*)")
)

(provide 'libparser-mode)