Initial Commit
[packages] / xemacs-packages / semantic / wisent / wisent-python.el
1 ;;; wisent-python.el --- Semantic support for Python
2 ;;
3 ;; Copyright (C) 2002, 2004, 2006, 2007 Richard Kim
4 ;;
5 ;; Author: Richard Kim <ryk@dspwiz.com>
6 ;; Maintainer: Richard Kim <ryk@dspwiz.com>
7 ;; Created: June 2002
8 ;; Keywords: syntax
9 ;; X-RCS: $Id: wisent-python.el,v 1.1 2007-11-26 15:12:34 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 ;; This library contains Semantic support code for the Python
31 ;; programming language.  The LALR grammar used to parse Python
32 ;; sources is in the wisent-python.wy file.
33 ;;
34 ;; The official website for the Python language is at
35 ;; <http://python.org/>.
36 ;;
37 ;; An X/Emacs major mode for editing Python source code is available
38 ;; at <http://sourceforge.net/projects/python-mode/>.
39 ;;
40 ;;; Code:
41
42 (require 'semantic-wisent)
43 (require 'wisent-python-wy)
44 \f
45 ;;; Lexical analysis
46 ;;
47
48 ;; Python strings are delimited by either single quotes or double
49 ;; quotes, e.g., "I'm a string" and 'I too am s string'.
50 ;; In addition a string can have either a 'r' and/or 'u' prefix.
51 ;; The 'r' prefix means raw, i.e., normal backslash substitutions are
52 ;; to be suppressed.  For example, r"01\n34" is a string with six
53 ;; characters 0, 1, \, n, 3 and 4.  The 'u' prefix means the following
54 ;; string is a unicode.
55 (defconst wisent-python-string-re
56   (concat (regexp-opt '("r" "u" "ur" "R" "U" "UR" "Ur" "uR") t)
57           "?['\"]")
58   "Regexp matching beginning of a python string.")
59
60 (defvar wisent-python-EXPANDING-block nil
61   "Non-nil when expanding a paren block for Python lexical analyzer.")
62
63 (defun wisent-python-implicit-line-joining-p ()
64   "Return non-nil if implicit line joining is active.
65 That is, if inside an expressions in parentheses, square brackets or
66 curly braces."
67   wisent-python-EXPANDING-block)
68
69 (defsubst wisent-python-forward-string ()
70   "Move point at the end of the python string at point."
71   (when (looking-at wisent-python-string-re)
72      ;; skip the prefix
73     (and (match-end 1) (goto-char (match-end 1)))
74     ;; skip the quoted part
75     (cond
76      ((looking-at "\"\"\"[^\"]")
77       (search-forward "\"\"\"" nil nil 2))
78      ((looking-at "'''[^']")
79       (search-forward "'''" nil nil 2))
80      ((forward-sexp 1)))))
81
82 (defun wisent-python-forward-line ()
83   "Move point to the beginning of the next logical line.
84 Usually this is simply the next physical line unless strings,
85 implicit/explicit line continuation, blank lines, or comment lines are
86 encountered.  This function skips over such items so that the point is
87 at the beginning of the next logical line.  If the current logical
88 line ends at the end of the buffer, leave the point there."
89   (while (not (eolp))
90     (when (= (point)
91              (progn
92                (cond
93                 ;; Skip over python strings.
94                 ((looking-at wisent-python-string-re)
95                  (wisent-python-forward-string))
96                 ;; At a comment start just goto end of line.
97                 ((looking-at "\\s<")
98                  (end-of-line))
99                 ;; Skip over generic lists and strings.
100                 ((looking-at "\\(\\s(\\|\\s\"\\)")
101                  (forward-sexp 1))
102                 ;; At the explicit line continuation character
103                 ;; (backslash) move to next line.
104                 ((looking-at "\\s\\")
105                  (forward-line 1))
106                 ;; Skip over white space, word, symbol, punctuation,
107                 ;; and paired delimiter (backquote) characters.
108                 ((skip-syntax-forward "-w_.$)")))
109                (point)))
110       (error "python-forward-line endless loop detected")))
111   ;; The point is at eol, skip blank and comment lines.
112   (forward-comment (point-max))
113   ;; Goto the beginning of the next line.
114   (or (eobp) (beginning-of-line)))
115
116 (defun wisent-python-forward-line-skip-indented ()
117   "Move point to the next logical line, skipping indented lines.
118 That is the next line whose indentation is less than or equal to the
119 identation of the current line."
120   (let ((indent (current-indentation)))
121     (while (progn (wisent-python-forward-line)
122                   (and (not (eobp))
123                        (> (current-indentation) indent))))))
124
125 (defun wisent-python-end-of-block ()
126   "Move point to the end of the current block."
127   (let ((indent (current-indentation)))
128     (while (and (not (eobp)) (>= (current-indentation) indent))
129       (wisent-python-forward-line-skip-indented))
130     ;; Don't include final comments in current block bounds
131     (forward-comment (- (point-max)))
132     (or (bolp) (forward-line 1))
133     ))
134
135 ;; Indentation stack, what the Python (2.3) language spec. says:
136 ;;
137 ;; The indentation levels of consecutive lines are used to generate
138 ;; INDENT and DEDENT tokens, using a stack, as follows.
139 ;;
140 ;; Before the first line of the file is read, a single zero is pushed
141 ;; on the stack; this will never be popped off again. The numbers
142 ;; pushed on the stack will always be strictly increasing from bottom
143 ;; to top. At the beginning of each logical line, the line's
144 ;; indentation level is compared to the top of the stack. If it is
145 ;; equal, nothing happens. If it is larger, it is pushed on the stack,
146 ;; and one INDENT token is generated. If it is smaller, it must be one
147 ;; of the numbers occurring on the stack; all numbers on the stack
148 ;; that are larger are popped off, and for each number popped off a
149 ;; DEDENT token is generated. At the end of the file, a DEDENT token
150 ;; is generated for each number remaining on the stack that is larger
151 ;; than zero.
152 (defvar wisent-python-indent-stack)
153
154 (define-lex-analyzer wisent-python-lex-beginning-of-line
155   "Detect and create python indentation tokens at beginning of line."
156   (and
157    (bolp) (not (wisent-python-implicit-line-joining-p))
158    (let ((last-indent (car wisent-python-indent-stack))
159          (last-pos (point))
160          (curr-indent (current-indentation)))
161      (skip-syntax-forward "-")
162      (cond
163       ;; Skip comments and blank lines. No change in indentation.
164       ((or (eolp) (looking-at semantic-lex-comment-regex))
165        (forward-comment (point-max))
166        (or (eobp) (beginning-of-line))
167        (setq semantic-lex-end-point (point))
168        ;; Loop lexer to handle the next line.
169        t)
170       ;; No change in indentation.
171       ((= curr-indent last-indent)
172        (setq semantic-lex-end-point (point))
173        ;; Try next analyzers.
174        nil)
175       ;; Indentation increased
176       ((> curr-indent last-indent)
177        (if (or (not semantic-lex-maximum-depth)
178                (< semantic-lex-current-depth semantic-lex-maximum-depth))
179            (progn
180              ;; Return an INDENT lexical token
181              (setq semantic-lex-current-depth (1+ semantic-lex-current-depth))
182              (push curr-indent wisent-python-indent-stack)
183              (semantic-lex-push-token
184               (semantic-lex-token 'INDENT last-pos (point))))
185          ;; Add an INDENT_BLOCK token
186          (semantic-lex-push-token
187           (semantic-lex-token
188            'INDENT_BLOCK
189            (progn (beginning-of-line) (point))
190            (semantic-lex-unterminated-syntax-protection 'INDENT_BLOCK
191              (wisent-python-end-of-block)
192              (point)))))
193        ;; Loop lexer to handle tokens in current line.
194        t)
195       ;; Indentation decreased
196       (t
197        ;; Pop items from indentation stack
198        (while (< curr-indent last-indent)
199          (pop wisent-python-indent-stack)
200          (setq semantic-lex-current-depth (1- semantic-lex-current-depth)
201                last-indent (car wisent-python-indent-stack))
202          (semantic-lex-push-token
203           (semantic-lex-token 'DEDENT last-pos (point))))
204        ;; If pos did not change, then we must return nil so that
205        ;; other lexical analyzers can be run.
206        (/= last-pos (point)))
207       )))
208   ;; All the work was done in the above analyzer matching condition.
209   )
210
211 (define-lex-regex-analyzer wisent-python-lex-end-of-line
212   "Detect and create python newline tokens.
213 Just skip the newline character if the following line is an implicit
214 continuation of current line."
215   "\\(\n\\|\\s>\\)"
216   (if (wisent-python-implicit-line-joining-p)
217       (setq semantic-lex-end-point (match-end 0))
218     (semantic-lex-push-token
219      (semantic-lex-token 'NEWLINE (point) (match-end 0)))))
220
221 (define-lex-regex-analyzer wisent-python-lex-string
222   "Detect and create python string tokens."
223   wisent-python-string-re
224   (semantic-lex-push-token
225    (semantic-lex-token
226     'STRING_LITERAL
227     (point)
228     (semantic-lex-unterminated-syntax-protection 'STRING_LITERAL
229       (wisent-python-forward-string)
230       (point)))))
231
232 (define-lex-regex-analyzer wisent-python-lex-ignore-backslash
233   "Detect and skip over backslash (explicit line joining) tokens.
234 A backslash must be the last token of a physical line, it is illegal
235 elsewhere on a line outside a string literal."
236   "\\s\\\\s-*$"
237   ;; Skip over the detected backslash and go to the first
238   ;; non-whitespace character in the next physical line.
239   (forward-line)
240   (skip-syntax-forward "-")
241   (setq semantic-lex-end-point (point)))
242
243 (define-lex wisent-python-lexer
244   "Lexical Analyzer for Python code."
245   ;; Must analyze beginning of line first to handle indentation.
246   wisent-python-lex-beginning-of-line
247   wisent-python-lex-end-of-line
248   ;; Must analyze string before symbol to handle string prefix.
249   wisent-python-lex-string
250   ;; Analyzers auto-generated from grammar.
251   wisent-python-wy--<number>-regexp-analyzer
252   wisent-python-wy--<keyword>-keyword-analyzer
253   wisent-python-wy--<symbol>-regexp-analyzer
254   wisent-python-wy--<block>-block-analyzer
255   wisent-python-wy--<punctuation>-string-analyzer
256   ;; Ignored things.
257   wisent-python-lex-ignore-backslash
258   semantic-lex-ignore-whitespace
259   semantic-lex-ignore-comments
260   ;; Signal error on unhandled syntax.
261   semantic-lex-default-action)
262 \f
263 ;;; Overridden Semantic API.
264 ;;
265 (define-mode-local-override semantic-lex python-mode
266   (start end &optional depth length)
267   "Lexically analyze python code in current buffer.
268 See the function `semantic-lex' for the meaning of the START, END,
269 DEPTH and LENGTH arguments.
270 This function calls `wisent-python-lexer' to actually perform the
271 lexical analysis, then emits the necessary python DEDENT tokens from
272 what remains in the `wisent-python-indent-stack'."
273   (let* ((wisent-python-indent-stack (list 0))
274          (stream (wisent-python-lexer start end depth length))
275          (semantic-lex-token-stream nil))
276     ;; Emit DEDENT tokens if something remains in the INDENT stack.
277     (while (> (pop wisent-python-indent-stack) 0)
278       (semantic-lex-push-token (semantic-lex-token 'DEDENT end end)))
279     (nconc stream (nreverse semantic-lex-token-stream))))
280
281 (define-mode-local-override semantic-get-local-variables python-mode ()
282   "Get the local variables based on point's context.
283 To be implemented for python!  For now just return nil."
284   nil)
285
286 ;;; Enable Semantic in `python-mode'.
287 ;;
288
289 ;;;###autoload
290 (defun wisent-python-default-setup ()
291   "Setup buffer for parse."
292   (wisent-python-wy--install-parser)
293   (set (make-local-variable 'parse-sexp-ignore-comments) t)
294   (setq
295    ;; Character used to separation a parent/child relationship
296    semantic-type-relation-separator-character '(".")
297    semantic-command-separation-character ";"
298    ;; The following is no more necessary as semantic-lex is overriden
299    ;; in python-mode.
300    ;; semantic-lex-analyzer 'wisent-python-lexer
301
302    ;; Semantic to take over from the one provided by python.
303    ;; The python one, if it uses the senator advice, will hang
304    ;; Emacs unrecoverably.
305    imenu-create-index-function 'semantic-create-imenu-index
306
307    ;; I need a python guru to update this list:
308    semantic-symbol->name-assoc-list-for-type-parts '((variable . "Variables")
309                                                      (function . "Methods"))
310    semantic-symbol->name-assoc-list '((type . "Classes")
311                                       (variable . "Variables")
312                                       (function . "Functions")
313                                       (include  . "Imports")
314                                       (package  . "Package")
315                                       (code . "Code")))
316    )
317
318 ;;;###autoload
319 (add-hook 'python-mode-hook 'wisent-python-default-setup)
320 \f
321 ;;; Test
322 ;;
323 (defun wisent-python-lex-buffer ()
324   "Run `wisent-python-lexer' on current buffer."
325   (interactive)
326   (semantic-lex-init)
327   (let ((token-stream (semantic-lex (point-min) (point-max) 0)))
328     (with-current-buffer (get-buffer-create "*wisent-python-lexer*")
329       (erase-buffer)
330       (pp token-stream (current-buffer))
331       (goto-char (point-min))
332       (pop-to-buffer (current-buffer)))))
333
334 (provide 'wisent-python)
335
336 ;;; wisent-python.el ends here