1 ;;; lmc.el --- Little Man Computer in Elisp
3 ;; Copyright (C) 2011 Free Software Foundation, Inc.
5 ;; Author: Stefan Monnier <monnier@iro.umontreal.ca>
7 ;; This program is free software; you can redistribute it and/or modify
8 ;; it under the terms of the GNU General Public License as published by
9 ;; the Free Software Foundation, either version 3 of the License, or
10 ;; (at your option) any later version.
12 ;; This program is distributed in the hope that it will be useful,
13 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
14 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 ;; GNU General Public License for more details.
17 ;; You should have received a copy of the GNU General Public License
18 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
22 ;; A simulator for the Little Man Computer.
23 ;; http://en.wikipedia.org/wiki/Little_man_computer
25 ;; The simulator uses a plain editable buffer, so you can edit the machine
26 ;; words just like any other text, and every word can be given a name (label)
27 ;; which can also be edited in the normal way. Additionally to the labels it
28 ;; shows the disassembled meaning of instruction words. Of course, it can't
29 ;; always know which words are meant to be code rather than data, so it relies
30 ;; on information from the assembler to do that, and otherwise just marks every
31 ;; word it executes as being "code".
33 ;; The assembly uses a slightly different (Lispish) syntax where comments start
34 ;; with ";", and each instruction needs to be wrapped in parentheses.
35 ;; Other than that it's the same assembly as documented elsewhere
36 ;; (accepts a few mnemonic variants, such as IN/INP, STA/STO, BR/BRA).
37 ;; Another difference is that the DAT mnemonic accepts any number of words
38 ;; rather than just one.
40 ;; So the assembly (stored in files with extension ".elmc") looks like:
43 ;; (BR label2) ;Useless extra jump.
45 ;; (LDA data1) ;Cleverest part of the algorithm.
51 ;; data2 (DAT 050 060 070)
53 ;; And actually, since the assembler re-uses the Emacs Lisp reader to parse the
54 ;; code, you can use binary, octal, and hexadecimal constants as well, using
55 ;; the notations #b101010, #o277, and #x5F respectively.
57 ;; The lmc-asm-mode supports the usual editing features such as label
58 ;; completion, mnemonic completion, jumping to a label, automatic indentation,
63 (eval-when-compile (require 'cl))
68 (defvar lmc--pc 0 "Program counter for LMC.")
69 (make-variable-buffer-local 'lmc--pc)
71 (defvar lmc-acc 0 "Accumulator for LMC.")
72 (make-variable-buffer-local 'lmc--acc)
74 ;; (defun lmc-check (cmds)
77 ;; ((pred symbolp)) ;A label.
78 ;; (`(,(or `IN `OUT `HLT `COB))) ;Arity-0 opcode.
79 ;; (`(,(or `LDA `STO `ADD `SUB `BR `BRZ `BRP `DAT) ;Arity-1 opcode.
80 ;; ,(or (pred lmc--numberp) (pred symbolp))))
81 ;; (_ (error "Unknown instruction %S" cmd)))))
83 (defun lmc--numberp (n max)
85 (or (and (or (natnump n) (error "%S is not a positive integer" n))
86 (or (< n max) (error "%S is too large" n))))))
88 (defun lmc--resolve (arg labels max)
89 (if (lmc--numberp arg max) arg
90 (or (cdr (assq arg labels))
91 (error (if (symbolp arg)
93 "Arg %S is neither a label nor a number")
96 (defconst lmc-mnemonic-1-table '((LDA . 5)
103 "Mnemonic table for arity-1 instructions.")
105 (defconst lmc-mnemonic-0-table '((HLT . 000) (COB . 000)
106 (IN . 901) (INP . 901)
108 "Mnemonic table for arity-0 instructions.")
110 (defun lmc--assemble (cmds)
111 ;; FIXME: Move to error position upon error.
114 ;; First pass, resolve labels to their positions.
116 (setq cmd (cdr cmd)) ;Ignore position info at this stage.
118 (assq cmd lmc-mnemonic-0-table))
119 (setq pos (+ pos (if (eq (car cmd) 'DAT)
120 (1- (length cmd)) 1)))
121 ;; (assert (symbolp cmd))
122 (if (assq cmd labels)
123 (error "Duplicate label %S" cmd)
124 (push (cons cmd pos) labels))))
125 ;; Second pass, do the actual assembly.
129 (lambda (w &optional code)
130 (push (list w ll code) words) (setq ll nil))))
132 (goto-char (pop cmd)) ;Move to start of CMD, in case of error.
134 ((assq cmd lmc-mnemonic-0-table)
135 (funcall newword (cdr (assq cmd lmc-mnemonic-0-table)) 'code))
136 ((and (null (cdr-safe cmd))
137 (assq (car-safe cmd) lmc-mnemonic-0-table))
138 (funcall newword (cdr (assq (car cmd) lmc-mnemonic-0-table)) 'code))
139 ((eq (car-safe cmd) 'DAT)
140 (dolist (arg (cdr cmd))
141 (funcall newword (lmc--resolve arg labels 1000))))
142 ((assq (car-safe cmd) lmc-mnemonic-1-table)
144 (+ (* 100 (cdr (assq (car cmd) lmc-mnemonic-1-table)))
145 (lmc--resolve (nth 1 cmd) labels 100))
147 ((and cmd (symbolp cmd))
148 (assert (eq (cdr (assq cmd labels)) (length words)))
150 (t (error "Invalid instruction %S" cmd))))
153 ;; (defvar lmc-label-width 8)
155 (defun lmc--load-word (word addr)
157 (insert (propertize (format " %02d:\t" addr)
161 (let ((word (car word))
164 (let ((basepos (point))
165 (base (current-column)))
166 (if (and label (symbolp label))
167 (insert (symbol-name label)))
168 ;; (when (>= (current-column) (+ base tab-width))
169 ;; (while (>= (current-column) (+ base tab-width -1))
172 ;; (put-text-property basepos (point)
173 ;; 'help-echo (symbol-name label)))
174 ;; (insert (propertize
175 ;; (make-string (1+ (- lmc-label-width (current-column))) ?\s)
176 ;; 'display '(space :align-to (1+ lmc-label-width))))
177 (insert (eval-when-compile (propertize "\t"
179 'rear-nonsticky t))))
180 (insert (format " %03d" word))
182 (eval-when-compile (propertize "\n"
186 (eval-when-compile (propertize "\n"
188 'rear-nonsticky t))))))
190 (defun lmc-disassemble-word (word)
191 (let ((code (car (rassq (/ word 100) lmc-mnemonic-1-table))))
193 (code (list code (mod word 100)))
194 ((rassq word lmc-mnemonic-0-table)
195 (list (car (rassq word lmc-mnemonic-0-table)))))))
197 (defun lmc-addr->point (addr)
198 (goto-char (point-min))
201 (defun lmc-point->addr ()
202 (- (count-lines (point-min) (point)) (if (bolp) 0 1)))
204 (defun lmc-get-word (&optional addr fix)
208 (lmc-addr->point addr))
210 ((re-search-forward "\t.*\t \\([0-9][0-9][0-9]\\)$"
211 (line-end-position) t)
212 (string-to-number (match-string 1)))
213 ((re-search-forward "\t.*\t\\(.*\\)$" (line-end-position) t)
214 (let ((n (string-to-number (match-string 1))))
215 (unless (integerp n) (setq n (truncate n)))
216 (setq n (mod n 1000))
218 (replace-match (format " %03d" n) t t nil 1))
222 (defconst lmc-label-re "^\\([^\t\n]*\\)\t\\(.*\\)\t *[0-9]")
224 (defvar lmc-label-table nil)
226 (defun lmc-record-label (addr label)
227 (let ((old (aref lmc-label-table addr)))
228 (unless (and old (equal (car old) label))
229 ;; (message "recordlabel %S = %S" addr label)
230 (aset lmc-label-table addr (list label))
234 (lambda (buf refaddrs)
235 (with-current-buffer buf
237 ;; (message "refreshlabel in %S" refaddrs)
238 (dolist (refaddr refaddrs)
239 (lmc-addr->point (1+ refaddr))
241 (let ((inhibit-read-only t))
242 (put-text-property (1- (point)) (point)
243 'fontified nil)))))))
244 (current-buffer) (cdr old))))))
246 (defun lmc-get-label (addr)
250 (lmc-addr->point addr) ;; )
251 (let ((label (when (re-search-forward lmc-label-re nil t)
252 (if (> (match-end 2) (match-beginning 2))
254 (lmc-record-label addr label)
258 (defun lmc-font-lock-opcode ()
260 (when (get-text-property (line-end-position) 'lmc-code)
261 (let* ((word (lmc-get-word))
262 (code (lmc-disassemble-word word)))
264 (when (integerp (nth 1 code))
265 (let* ((addr (nth 1 code))
266 (label (lmc-get-label addr)))
267 (pushnew (lmc-point->addr)
268 (cdr (aref lmc-label-table addr)))
270 (setf (nth 1 code) label))))
272 (line-end-position) (1+ (line-end-position))
274 (format (eval-when-compile
275 (concat (propertize "\t" 'cursor t)
276 (propertize "%s" 'face font-lock-comment-face)
278 (or code '(Invalid opcode)))))
281 (defun lmc-font-lock-label ()
282 (lmc-record-label (lmc-point->addr)
283 (if (> (match-end 2) (match-beginning 2))
286 ;; ;; Replace any TAB found in label.
287 ;; (goto-char (match-beginning 2))
288 ;; (while (progn (skip-chars-forward "^\t" (match-end 2))
289 ;; (< (point) (match-end 2)))
290 ;; (insert " ") (delete-char 1))
291 ;; Truncate label's display if needed.
292 (move-to-column (1- (* 2 tab-width)))
293 (when (> (match-end 2) (point))
295 (put-text-property (match-beginning 2) (match-end 2)
296 'help-echo (match-string 2))
297 (put-text-property (point) (match-end 2) 'display "…")))
298 font-lock-constant-face)
300 (defconst lmc-font-lock-keywords
302 (1 'hexl-address-region)
303 (2 (lmc-font-lock-label)))
304 (".$" (0 (lmc-font-lock-opcode)))))
306 (defun lmc-after-change (beg end len)
307 (unless inhibit-read-only
309 ;; Replace any TAB or NL inserted, which could interfere with parsing.
311 (while (progn (skip-chars-forward "^\t\n" end)
313 (insert " ") (delete-char 1)))))
315 (defvar lmc-pc 0 "LMC program counter.")
316 (make-variable-buffer-local 'lmc-pc)
317 (defvar lmc-acc nil "LMC accumulator.")
318 (make-variable-buffer-local 'lmc-acc)
319 (defvar lmc-output nil "Past LMC output,")
320 (make-variable-buffer-local 'lmc-output)
322 (defvar lmc--stopped nil "State where we stopped.")
323 (make-variable-buffer-local 'lmc--stopped)
325 (defun lmc-update-pc ()
326 (setq lmc-pc (mod lmc-pc 100))
327 (lmc-addr->point lmc-pc)
328 (move-marker overlay-arrow-position (point))
329 (re-search-forward "\t.*\t *" nil t)
330 (unless (get-text-property (line-end-position) 'lmc-code)
331 (let ((inhibit-read-only t))
332 (put-text-property (line-end-position)
333 (min (1+ (line-end-position)) (point-max))
337 (list (buffer-chars-modified-tick) lmc-acc lmc-pc))
338 (defun lmc-stopped-p ()
339 (equal (lmc--state) lmc--stopped))
341 ;; FIXME: Add tool-bar to LMC-Sim.
344 (let ((map (make-sparse-keymap)))
345 (define-key map "\C-c\C-s" 'lmc-step)
346 (define-key map "\C-c\C-r" 'lmc-run)
347 (define-key map "\C-c\C-l" 'lmc-load-file)
348 (define-key map "\C-c\C-a" 'lmc-set-acc)
349 (define-key map "\C-c\C-p" 'lmc-set-pc)
352 (easy-menu-define lmc-menu lmc-mode-map "Menu for LMC-Sim."
354 ["Step" lmc-step (not (lmc-stopped-p))]
355 ["Run" lmc-run (not (lmc-stopped-p))]
356 ["Load file" lmc-load-file]
358 ["Set Program Counter" lmc-set-pc]
359 ["Set Accumulator" lmc-set-acc]))
361 (defvar lmc-tool-bar-map
362 (let ((map (make-sparse-keymap)))
363 (tool-bar-local-item "gud/next" 'lmc-step 'step map
364 :label "step" ;; :vert-only t
365 :enable '(not (lmc-stopped-p))
367 (tool-bar-local-item "gud/run" 'lmc-run 'run map
368 :label "run" ;; :vert-only t
369 :enable '(not (lmc-stopped-p))
373 (define-derived-mode lmc-mode fundamental-mode "LMC-Sim"
374 "The simulator of the Little Man Computer."
375 (set (make-local-variable 'truncate-lines) t)
376 (set (make-local-variable 'truncate-partial-width-windows) t)
377 (set (make-local-variable 'tab-width) 10)
378 (set (make-local-variable 'font-lock-defaults)
379 '(lmc-font-lock-keywords t))
380 (set (make-local-variable 'font-lock-extra-managed-props)
381 '(display help-echo))
382 (set (make-local-variable 'tool-bar-map) lmc-tool-bar-map)
383 (add-hook 'after-change-functions #'lmc-after-change nil t)
384 (set (make-local-variable 'lmc-label-table) (make-vector 100 nil))
385 (set (make-local-variable 'overlay-arrow-position) (point-min-marker))
387 ;; (overwrite-mode 1)
388 (set (make-local-variable 'header-line-format)
390 (:eval (format ,(propertize "%02d"
391 'mouse-face 'mode-line-highlight
392 'help-echo "mouse-2: set the Program Counter"
394 ;; I'm having problems with mouse-2 to
395 ;; mouse-1 remapping in the mode-line and
396 ;; header-line, so I over-do it a bit.
400 (down-mouse-1 . ignore)
401 (mouse-2 . lmc-set-pc)
402 (mouse-1 . lmc-set-pc))))
405 (:eval (format ,(propertize "%03d"
406 'mouse-face 'mode-line-highlight
407 'help-echo "mouse-2: set the Accumulator"
410 ;; I'm having problems with mouse-2 to
411 ;; mouse-1 remapping in the mode-line and
412 ;; header-line, so I over-do it a bit.
415 (down-mouse-1 . ignore)
416 (mouse-2 . lmc-set-acc)
417 (mouse-1 . lmc-set-acc))))
420 (:eval (if lmc-output (format "%s" lmc-output) "()"))))
423 (defun lmc-set-pc (pc)
424 "Set the Program Counter."
425 (interactive (list (read-number "New PC: " lmc-pc)))
429 (defun lmc-set-acc (acc)
430 "Set the Accumulator."
431 (interactive (list (read-number "New Accumulator: " lmc-acc)))
432 (setq lmc-acc (mod acc 1000)))
434 (defun lmc-load (words)
435 (pop-to-buffer "*LMC-Sim*")
437 (let ((inhibit-read-only t)
441 (setq lmc-output nil)
444 (lmc--load-word word addr)
445 (setq addr (1+ addr)))
447 (lmc--load-word '(0) addr)
448 (setq addr (1+ addr))))
451 (defvar lmc-store-flash t)
453 (defun lmc-store-word (addr word)
455 (lmc-addr->point addr)
456 (if (not (re-search-forward "\t.*\t\\(.*\\)$" (line-end-position) t))
457 (error "Missing memory cell %S" addr)
458 (when lmc-store-flash
459 (with-silent-modifications
460 (put-text-property (match-beginning 1) (point)
463 (replace-match (format " %03d" word) t t nil 1)
464 (when lmc-store-flash
466 (with-silent-modifications
467 (put-text-property (match-beginning 1) (point)
470 (with-silent-modifications
471 (put-text-property (match-beginning 1) (point)
476 "Execute one LMC instruction."
478 (let* ((inst (lmc-get-word lmc-pc 'fix))
479 (code (lmc-disassemble-word inst)))
481 (HLT (if (lmc-stopped-p)
482 (error "Already halted")
483 (setq lmc--stopped (lmc--state))
484 (force-mode-line-update)
486 (IN (setq lmc-acc (mod (read-number "Enter a number") 1000))
488 (OUT (message "Output: %03d" lmc-acc)
489 (push (format "%03d" lmc-acc) lmc-output)
491 (LDA (setq lmc-acc (lmc-get-word (nth 1 code)))
493 (STO (lmc-store-word (nth 1 code) lmc-acc)
495 (ADD (setq lmc-acc (mod (+ lmc-acc (lmc-get-word (nth 1 code)))
498 (SUB (setq lmc-acc (mod (- lmc-acc (lmc-get-word (nth 1 code)))
501 (BR (setq lmc-pc (nth 1 code)))
502 (BRZ (setq lmc-pc (if (zerop lmc-acc)
505 (BRP (setq lmc-pc (if (< lmc-acc 500)
508 ((nil) (error "Invalid instruction %S" inst))
509 (t (error "%S not implemented" code))))
513 "Run the code until hitting a HLT.
514 The machine will also stop if the user presses a key."
516 (while (not (or (input-pending-p) (lmc-stopped-p)))
520 ;;; The LMC assembly language editor.
522 (defvar lmc-asm-mode-map
523 (let ((map (make-sparse-keymap)))
524 ;; FIXME: Add "load" and "assemble" buttons.
525 (define-key map "\C-c\C-l" 'lmc-asm-load)
526 (define-key map "\C-c\C-a" 'lmc-asm-assemble)
529 (easy-menu-define lmc-asm-menu lmc-asm-mode-map
530 "Menu for the LMC-Asm mode."
532 ["Assemble" lmc-asm-assemble]
533 ["Load into Simulator" lmc-asm-load]))
536 (defconst lmc-asm-mnemonic-names
537 (mapcar #'symbol-name
538 (append (mapcar #'car lmc-mnemonic-1-table)
539 (mapcar #'car lmc-mnemonic-0-table)
542 (defconst lmc-asm-mnemonic-names-re (regexp-opt lmc-asm-mnemonic-names))
544 (defvar lmc-asm-font-lock-keywords
545 `(("^[ \t]*\\(?:\\sw\\|\\s_\\)+"
546 (0 (if (zerop (nth 0 (syntax-ppss))) font-lock-constant-face)))
547 (,(concat "(\\(" lmc-asm-mnemonic-names-re "\\_>\\)")
548 (1 font-lock-keyword-face))))
550 (defvar lmc-asm-imenu-generic-expression
551 '((nil "^\\(\\(?:\\sw\\|\\s_\\)+\\)" 1)))
553 (defvar lmc-asm-outline-regexp "^\\(?:\\sw\\|\\s_\\)")
555 ;; We use the ".elmc" extension since the syntax is not identical to
556 ;; the usual ".lmc" syntax.
558 (add-to-list 'auto-mode-alist '("\\.elmc\\'" . lmc-asm-mode))
561 (define-derived-mode lmc-asm-mode fundamental-mode "LMC-Asm"
562 "Major mode to edit LMC assembly code."
563 :syntax-table emacs-lisp-mode-syntax-table
564 (set (make-local-variable 'font-lock-defaults)
565 '(lmc-asm-font-lock-keywords))
566 (set (make-local-variable 'indent-line-function)
567 #'lmc-asm-indent-line)
568 (set (make-local-variable 'indent-tabs-mode) t)
569 (set (make-local-variable 'imenu-generic-expression)
570 lmc-asm-imenu-generic-expression)
571 (set (make-local-variable 'outline-regexp) lmc-asm-outline-regexp)
572 (add-hook 'completion-at-point-functions #'lmc-asm-completion nil t)
573 (set (make-local-variable 'comment-start) ";")
574 (set (make-local-variable 'comment-start-skip)
575 "\\(\\(^\\|[^\\\\\n]\\)\\(\\\\\\\\\\)*\\);+ *")
578 (defun lmc-asm-labels (string)
580 ;; We don't want to count the label being completed as a completion
581 ;; candidate, so let's keep track of the original position of point and
582 ;; skip any label nearby.
583 (let ((point (point)))
584 (goto-char (point-min))
586 (re (concat "\\(^\\|(" lmc-asm-mnemonic-names-re "[ \t]+" "\\)"
587 (regexp-quote string) "\\(?:\\sw\\|\\s_\\)"
588 (if (> (length string) 0) "*" "+"))))
589 (while (re-search-forward re nil t)
590 (when (or (< point (match-end 1))
591 (> (match-beginning 1) point))
592 (push (buffer-substring-no-properties
593 (match-end 1) (match-end 0)) ls)))
596 (defun lmc-asm-completion ()
598 (let ((ppss (syntax-ppss)))
600 ((nth 8 ppss) nil) ;Inside string or comment.
601 ((zerop (nth 0 ppss))
602 (skip-syntax-backward "w_")
603 (when (save-excursion (skip-chars-backward " \t") (bolp))
605 (save-excursion (skip-syntax-forward "w_") (point))
606 (completion-table-dynamic #'lmc-asm-labels))))
607 ((= 1 (nth 0 ppss)) ;Inside paren.
608 (skip-syntax-backward "w_")
610 (save-excursion (skip-syntax-forward "w_") (point))
611 (if (eq (char-before) ?\()
612 lmc-asm-mnemonic-names
613 (completion-table-dynamic #'lmc-asm-labels))))))))
615 (defun lmc-asm-indentation ()
617 (back-to-indentation)
619 ((> (nth 0 (syntax-ppss)) 0) nil)
620 ((looking-at "(") tab-width)
621 ((not (looking-at comment-start-skip)) 0)
622 ((not (looking-at "\\s<\\s<")) nil)
623 ((save-excursion (forward-comment (- (point))) (bobp)) 0)
624 (t (forward-comment (point-max)) (lmc-asm-indentation)))))
626 (defun lmc-asm-indent-line (&optional arg)
628 (back-to-indentation)
629 (when (and (zerop (nth 0 (syntax-ppss)))
630 (looking-at (concat lmc-asm-mnemonic-names-re "\\_>")))
631 ;; Apparently the user forgot to parenthesize the instruction.
633 (if (assq (read (current-buffer)) lmc-mnemonic-0-table)
635 (let ((eol (line-end-position)))
637 (read (current-buffer))
638 (when (<= (point) eol)
640 (let ((indent (lmc-asm-indentation)))
642 ((null indent) (lisp-indent-line arg))
644 (let ((left-margin indent)) (indent-to-left-margin))
646 ;; Indent code (if any) after a label.
649 (when (looking-at "\\(?:\\sw\\|\\s_\\)+\\([ \t]*\\)(")
650 (goto-char (match-beginning 1))
651 (if (< (current-column) tab-width)
652 (unless (save-excursion
653 (goto-char (match-end 1))
654 (= (current-column) tab-width))
655 (delete-region (match-beginning 1) (match-end 1))
656 (indent-to tab-width))
657 (unless (equal (match-string 1) " ")
658 (delete-region (match-beginning 1) (match-end 1))
659 (insert " "))))))))))
661 (defun lmc-asm-read ()
663 (initialpos (point)))
664 (goto-char (point-min))
665 (while (progn (forward-comment (point-max))
667 (let ((start (point)))
669 (push (cons (point) (read (current-buffer))) prog)
670 (end-of-file (goto-char start) (signal 'end-of-file nil)))))
671 (goto-char initialpos)
674 (defun lmc-asm-load ()
675 "Load current buffer into the LMC simulator."
677 (let ((initialpos (point))
678 (window (if (eq (current-buffer) (window-buffer)) (selected-window))))
680 (lmc-load (lmc--assemble (lmc-asm-read))))
681 (goto-char initialpos)
682 (if (and window (eq (current-buffer) (window-buffer window)))
683 (set-window-point window (point)))))
685 (defun lmc-asm-assemble ()
686 "Assemble current buffer to check syntax."
688 (let ((initialpos (point)))
689 (lmc--assemble (lmc-asm-read))
690 (goto-char initialpos)
691 (message "No errors found")))
693 (defun lmc-load-file (file)
694 "Load FILE into the LMC simulator."
696 (list (read-file-name "Load LMC file: " nil nil t nil
698 (or (file-directory-p file)
699 (string-match-p "\\.elmc\\'" file))))))
700 (let ((exists (find-buffer-visiting file))
701 (buf (find-file-noselect file)))
703 (with-current-buffer buf
706 (error (error "Error at line %d: %s" (line-number-at-pos)
707 (error-message-string err)))))
708 (unless exists (kill-buffer buf)))))