Initial Commit
[packages] / xemacs-packages / semantic / bovine / bovine-grammar.el
1 ;;; bovine-grammar.el --- Bovine's input grammar mode
2 ;;
3 ;; Copyright (C) 2002, 2003, 2004, 2007 David Ponce
4 ;;
5 ;; Author: David Ponce <david@dponce.com>
6 ;; Maintainer: David Ponce <david@dponce.com>
7 ;; Created: 26 Aug 2002
8 ;; Keywords: syntax
9 ;; X-RCS: $Id: bovine-grammar.el,v 1.1 2007-11-26 15:11:50 michaels Exp $
10 ;;
11 ;; This file is not part of GNU Emacs.
12 ;;
13 ;; This program is free software; you can redistribute it and/or
14 ;; modify it under the terms of the GNU General Public License as
15 ;; published by the Free Software Foundation; either version 2, or (at
16 ;; your option) any later version.
17 ;;
18 ;; This software is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
21 ;; General Public License for more details.
22 ;;
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
25 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
26 ;; Boston, MA 02110-1301, USA.
27
28 ;;; Commentary:
29 ;;
30 ;; Major mode for editing Bovine's input grammar (.by) files.
31
32 ;;; History:
33 ;;
34
35 ;;; Code:
36 (require 'derived)
37
38 (require 'semantic-grammar)
39 ;; XEmacs change: circular dependency
40 ;; (require 'bovine-grammar-macros)
41
42 ;; Cache of macro definitions currently in use.
43 (defvar bovine--grammar-macros nil)
44
45 (defun bovine-grammar-expand-form (form quotemode &optional inplace)
46   "Expand FORM into a new one suitable to the bovine parser.
47 FORM is a list in which we are substituting.
48 Argument QUOTEMODE is non-nil if we are in backquote mode.
49 When non-nil, optional argument INPLACE indicates that FORM is being
50 expanded from elsewhere."
51   (when (eq (car form) 'quote)
52     (setq form (cdr form))
53     (cond
54      ((and (= (length form) 1) (listp (car form)))
55       (insert "\n(append")
56       (bovine-grammar-expand-form (car form) quotemode nil)
57       (insert ")")
58       (setq form nil inplace nil)
59       )
60      ((and (= (length form) 1) (symbolp (car form)))
61       (insert "\n'" (symbol-name (car form)))
62       (setq form nil inplace nil)
63       )
64      (t
65       (insert "\n(list")
66       (setq inplace t)
67       )))
68   (let ((macro (assq (car form) bovine--grammar-macros))
69         inlist first n q x val)
70     (if macro
71         (bovine-grammar-expand-form
72          (apply (cdr macro) (cdr form))
73          quotemode t)
74       (if inplace (insert "\n("))
75       (while form
76         (setq first (car form)
77               form  (cdr form))
78         (cond
79          ((eq first nil)
80           (when (and (not inlist) (not inplace))
81             (insert "\n(list")
82             (setq inlist t))
83           (insert " nil")
84           )
85          ((listp first)
86           ;;(let ((fn (and (symbolp (caar form)) (fboundp (caar form)))))
87           (when (and (not inlist) (not inplace))
88             (insert "\n(list")
89             (setq inlist t))
90           ;;(if (and inplace (not fn) (not (eq (caar form) 'EXPAND)))
91           ;;    (insert " (append"))
92           (bovine-grammar-expand-form
93            first quotemode t) ;;(and fn (not (eq fn 'quote))))
94           ;;(if (and inplace (not fn) (not (eq (caar form) 'EXPAND)))
95           ;;    (insert  ")"))
96           ;;)
97           )
98          ((symbolp first)
99           (setq n (symbol-name first)   ;the name
100                 q quotemode             ;implied quote flag
101                 x nil)                  ;expand flag
102           (if (eq (aref n 0) ?,)
103               (if quotemode
104                   ;; backquote mode needs the @
105                   (if (eq (aref n 1) ?@)
106                       (setq n (substring n 2)
107                             q nil
108                             x t)
109                     ;; non backquote mode behaves normally.
110                     (setq n (substring n 1)
111                           q nil))
112                 (setq n (substring n 1)
113                       x t)))
114           (if (string= n "")
115               (progn
116                 ;; We expand only the next item in place (a list?)
117                 ;; A regular inline-list...
118                 (bovine-grammar-expand-form (car form) quotemode t)
119                 (setq form (cdr form)))
120             (if (and (eq (aref n 0) ?$)
121                      ;; Don't expand $ tokens in implied quote mode.
122                      ;; This acts like quoting in other symbols.
123                      (not q))
124                 (progn
125                   (cond
126                    ((and (not x) (not inlist) (not inplace))
127                     (insert "\n(list"))
128                    ((and x inlist (not inplace))
129                     (insert ")")
130                     (setq inlist nil)))
131                   (insert "\n(nth " (int-to-string
132                                      (1- (string-to-number
133                                           (substring n 1))))
134                           " vals)")
135                   (and (not x) (not inplace)
136                        (setq inlist t)))
137               
138               (when (and (not inlist) (not inplace))
139                 (insert "\n(list")
140                 (setq inlist t))
141               (or (char-equal (char-before) ?\()
142                   (insert " "))
143               (insert (if (or inplace (eq first t))
144                           "" "'")
145                       n))) ;; " "
146           )
147          (t
148           (when (and (not inlist) (not inplace))
149             (insert "\n(list")
150             (setq inlist t))
151           (insert (format "\n%S" first))
152           )
153          ))
154       (if inlist (insert ")"))
155       (if inplace (insert ")")))
156     ))
157
158 (defun bovine-grammar-expand-action (textform quotemode)
159   "Expand semantic action string TEXTFORM into Lisp code.
160 QUOTEMODE is the mode in which quoted symbols are slurred."
161   (if (string= "" textform)
162       nil
163     (let ((sexp (read textform)))
164       ;; We converted the lambda string into a list.  Now write it
165       ;; out as the bovine lambda expression, and do macro-like
166       ;; conversion upon it.
167       (insert "\n")
168       (cond
169        ((eq (car sexp) 'EXPAND)
170         (insert ",(lambda (vals start end)")
171         ;; The EXPAND macro definition is mandatory
172         (bovine-grammar-expand-form
173          (apply (cdr (assq 'EXPAND bovine--grammar-macros)) (cdr sexp))
174          quotemode t)
175         )
176        ((and (listp (car sexp)) (eq (caar sexp) 'EVAL))
177         ;; The user wants to evaluate the following args.
178         ;; Use a simpler expander
179         )
180        (t
181         (insert ",(semantic-lambda")
182         (bovine-grammar-expand-form sexp quotemode)
183         ))
184       (insert ")\n"))))
185
186 (defun bovine-grammar-parsetable-builder ()
187   "Return the parser table expression as a string value.
188 The format of a bovine parser table is:
189
190  ( ( NONTERMINAL-SYMBOL1 MATCH-LIST1 )
191    ( NONTERMINAL-SYMBOL2 MATCH-LIST2 )
192    ...
193    ( NONTERMINAL-SYMBOLn MATCH-LISTn )
194  
195 Where each NONTERMINAL-SYMBOL is an artificial symbol which can appear
196 in any child state.  As a starting place, one of the NONTERMINAL-SYMBOLS
197 must be `bovine-toplevel'.
198
199 A MATCH-LIST is a list of possible matches of the form:
200
201  ( STATE-LIST1
202    STATE-LIST2
203    ...
204    STATE-LISTN )
205
206 where STATE-LIST is of the form:
207   ( TYPE1 [ \"VALUE1\" ] TYPE2 [ \"VALUE2\" ] ... LAMBDA )
208
209 where TYPE is one of the returned types of the token stream.
210 VALUE is a value, or range of values to match against.  For
211 example, a SYMBOL might need to match \"foo\".  Some TYPES will not
212 have matching criteria.
213
214 LAMBDA is a lambda expression which is evaled with the text of the
215 type when it is found.  It is passed the list of all buffer text
216 elements found since the last lambda expression.  It should return a
217 semantic element (see below.)
218
219 For consistency between languages, try to use common return values
220 from your parser.  Please reference the chapter \"Writing Parsers\" in
221 the \"Language Support Developer's Guide -\" in the semantic texinfo
222 manual."
223   (let* ((start      (semantic-grammar-start))
224          (scopestart (semantic-grammar-scopestart))
225          (quotemode  (semantic-grammar-quotemode))
226          (tags       (semantic-find-tags-by-class
227                       'token (current-buffer)))
228          (nterms     (semantic-find-tags-by-class
229                       'nonterminal (current-buffer)))
230          ;; Setup the cache of macro definitions.
231          (bovine--grammar-macros (semantic-grammar-macros))
232          nterm rules items item actn prec tag type regex)
233
234     ;; Check some trivial things
235     (cond
236      ((null nterms)
237       (error "Bad input grammar"))
238      (start
239       (if (cdr start)
240           (message "Extra start symbols %S ignored" (cdr start)))
241       (setq start (symbol-name (car start)))
242       (unless (semantic-find-first-tag-by-name start nterms)
243         (error "start symbol `%s' has no rule" start)))
244      (t
245       ;; Default to the first grammar rule.
246       (setq start (semantic-tag-name (car nterms)))))
247     (when scopestart
248       (setq scopestart (symbol-name scopestart))
249       (unless (semantic-find-first-tag-by-name scopestart nterms)
250         (error "scopestart symbol `%s' has no rule" scopestart)))
251
252     ;; Generate the grammar Lisp form.
253     (with-temp-buffer
254       (erase-buffer)
255       (insert "`(")
256       ;; Insert the start/scopestart rules
257       (insert "\n(bovine-toplevel \n("
258               start
259               ")\n) ;; end bovine-toplevel\n")
260       (when scopestart
261         (insert "\n(bovine-inner-scope \n("
262                 scopestart
263                 ")\n) ;; end bovine-inner-scope\n"))
264       ;; Process each nonterminal
265       (while nterms
266         (setq nterm  (car nterms)
267               ;; We can't use the override form because the current buffer
268               ;; is not the originator of the tag.
269               rules  (semantic-tag-components-semantic-grammar-mode nterm)
270               nterm  (semantic-tag-name nterm)
271               nterms (cdr nterms))
272         (when (member nterm '("bovine-toplevel" "bovine-inner-scope"))
273           (error "`%s' is a reserved internal name" nterm))
274         (insert "\n(" nterm)
275         ;; Process each rule
276         (while rules
277           (setq items (semantic-tag-get-attribute (car rules) :value)
278                 prec  (semantic-tag-get-attribute (car rules) :prec)
279                 actn  (semantic-tag-get-attribute (car rules) :expr)
280                 rules (cdr rules))
281           ;; Process each item
282           (insert "\n(")
283           (if (null items)
284               ;; EMPTY rule
285               (insert ";;EMPTY" (if actn "" "\n"))
286             ;; Expand items
287             (while items
288               (setq item  (car items)
289                     items (cdr items))
290               (if (consp item) ;; mid-rule action
291                   (message "Mid-rule action %S ignored" item)
292                 (or (char-equal (char-before) ?\()
293                     (insert "\n"))
294                 (cond
295                  ((member item '("bovine-toplevel" "bovine-inner-scope"))
296                   (error "`%s' is a reserved internal name" item))
297                  ;; Replace ITEM by its %token definition.
298                  ;; If a '%token TYPE ITEM [REGEX]' definition exists
299                  ;; in the grammar, ITEM is replaced by TYPE [REGEX].
300                  ((setq tag (semantic-find-first-tag-by-name
301                              item tags)
302                         type  (semantic-tag-get-attribute tag :type))
303                   (insert type)
304                   (if (setq regex (semantic-tag-get-attribute tag :value))
305                       (insert (format "\n%S" regex))))
306                  ;; Don't change ITEM
307                  (t
308                   (insert (semantic-grammar-item-text item)))
309                  ))))
310           (if prec
311               (message "%%prec %S ignored" prec))
312           (if actn
313               (bovine-grammar-expand-action actn quotemode))
314           (insert ")"))
315         (insert "\n) ;; end " nterm "\n"))
316       (insert ")\n")
317       (buffer-string))))
318
319 (defun bovine-grammar-setupcode-builder ()
320   "Return the text of the setup code."
321   (format
322    "(setq semantic--parse-table %s\n\
323           semantic-debug-parser-source %S\n\
324           semantic-debug-parser-class 'semantic-bovine-debug-parser
325           semantic-flex-keywords-obarray %s\n\
326           %s)"
327    (semantic-grammar-parsetable)
328    (buffer-name)
329    (semantic-grammar-keywordtable)
330    (let ((mode (semantic-grammar-languagemode)))
331      ;; Is there more than one major mode?
332      (if (and (listp mode) (> (length mode) 1))
333          (format "semantic-equivalent-major-modes '%S\n" mode)
334        ""))))
335
336 (defvar bovine-grammar-menu
337   '("BY Grammar"
338     )
339   "BY mode specific grammar menu.
340 Menu items are appended to the common grammar menu.")
341
342 ;;;###autoload
343 (define-derived-mode bovine-grammar-mode semantic-grammar-mode "BY"
344   "Major mode for editing Bovine grammars."
345   (semantic-grammar-setup-menu bovine-grammar-menu)
346   (semantic-install-function-overrides
347    '((grammar-parsetable-builder . bovine-grammar-parsetable-builder)
348      (grammar-setupcode-builder  . bovine-grammar-setupcode-builder)
349      )))
350
351 ;;;###autoload
352 (add-to-list 'auto-mode-alist '("\\.by$" . bovine-grammar-mode))
353
354 ;;;###autoload
355 (eval-after-load "speedbar"
356   '(speedbar-add-supported-extension ".by"))
357
358 (provide 'bovine-grammar)
359
360 ;;; bovine-grammar.el ends here