id
int64
0
45.1k
file_name
stringlengths
4
68
file_path
stringlengths
14
193
content
stringlengths
32
9.62M
size
int64
32
9.62M
language
stringclasses
1 value
extension
stringclasses
6 values
total_lines
int64
1
136k
avg_line_length
float64
3
903k
max_line_length
int64
3
4.51M
alphanum_fraction
float64
0
1
repo_name
stringclasses
779 values
repo_stars
int64
0
882
repo_forks
int64
0
108
repo_open_issues
int64
0
90
repo_license
stringclasses
8 values
repo_extraction_date
stringclasses
146 values
sha
stringlengths
64
64
__index_level_0__
int64
0
45.1k
exdup_ids_cmlisp_stkv2
sequencelengths
1
47
190
push-to-checkout.sample
jscl-project_jscl/.git/hooks/push-to-checkout.sample
#!/bin/sh # An example hook script to update a checked-out tree on a git push. # # This hook is invoked by git-receive-pack(1) when it reacts to git # push and updates reference(s) in its repository, and when the push # tries to update the branch that is currently checked out and the # receive.denyCurrentBranch configuration variable is set to # updateInstead. # # By default, such a push is refused if the working tree and the index # of the remote repository has any difference from the currently # checked out commit; when both the working tree and the index match # the current commit, they are updated to match the newly pushed tip # of the branch. This hook is to be used to override the default # behaviour; however the code below reimplements the default behaviour # as a starting point for convenient modification. # # The hook receives the commit with which the tip of the current # branch is going to be updated: commit=$1 # It can exit with a non-zero status to refuse the push (when it does # so, it must not modify the index or the working tree). die () { echo >&2 "$*" exit 1 } # Or it can make any necessary changes to the working tree and to the # index to bring them to the desired state when the tip of the current # branch is updated to the new commit, and exit with a zero status. # # For example, the hook can simply run git read-tree -u -m HEAD "$1" # in order to emulate git fetch that is run in the reverse direction # with git push, as the two-tree form of git read-tree -u -m is # essentially the same as git switch or git checkout that switches # branches while keeping the local changes in the working tree that do # not interfere with the difference between the branches. # The below is a more-or-less exact translation to shell of the C code # for the default behaviour for git's push-to-checkout hook defined in # the push_to_deploy() function in builtin/receive-pack.c. # # Note that the hook will be executed from the repository directory, # not from the working tree, so if you want to perform operations on # the working tree, you will have to adapt your code accordingly, e.g. # by adding "cd .." or using relative paths. if ! git update-index -q --ignore-submodules --refresh then die "Up-to-date check failed" fi if ! git diff-files --quiet --ignore-submodules -- then die "Working directory has unstaged changes" fi # This is a rough translation of: # # head_has_history() ? "HEAD" : EMPTY_TREE_SHA1_HEX if git cat-file -e HEAD 2>/dev/null then head=HEAD else head=$(git hash-object -t tree --stdin </dev/null) fi if ! git diff-index --quiet --cached --ignore-submodules $head -- then die "Working directory has staged changes" fi if ! git read-tree -u -m "$commit" then die "Could not update working tree to new HEAD" fi
2,783
Common Lisp
.l
69
39.086957
70
0.765619
jscl-project/jscl
882
108
90
GPL-3.0
9/19/2024, 11:24:04 AM (Europe/Amsterdam)
b64782338acdf03da0bcd49c3173a6b7b0103c313a9b9af13f948c47dd586555
190
[ -1 ]
191
pre-merge-commit.sample
jscl-project_jscl/.git/hooks/pre-merge-commit.sample
#!/bin/sh # # An example hook script to verify what is about to be committed. # Called by "git merge" with no arguments. The hook should # exit with non-zero status after issuing an appropriate message to # stderr if it wants to stop the merge commit. # # To enable this hook, rename this file to "pre-merge-commit". . git-sh-setup test -x "$GIT_DIR/hooks/pre-commit" && exec "$GIT_DIR/hooks/pre-commit" :
416
Common Lisp
.l
12
32.916667
67
0.73201
jscl-project/jscl
882
108
90
GPL-3.0
9/19/2024, 11:24:04 AM (Europe/Amsterdam)
e20a4b66791c1bf94f74a10c9bffba10a9d89e975d25c7d1f356b66a5b8d4014
191
[ -1 ]
192
pre-commit.sample
jscl-project_jscl/.git/hooks/pre-commit.sample
#!/bin/sh # # An example hook script to verify what is about to be committed. # Called by "git commit" with no arguments. The hook should # exit with non-zero status after issuing an appropriate message if # it wants to stop the commit. # # To enable this hook, rename this file to "pre-commit". if git rev-parse --verify HEAD >/dev/null 2>&1 then against=HEAD else # Initial commit: diff against an empty tree object against=$(git hash-object -t tree /dev/null) fi # If you want to allow non-ASCII filenames set this variable to true. allownonascii=$(git config --type=bool hooks.allownonascii) # Redirect output to stderr. exec 1>&2 # Cross platform projects tend to avoid non-ASCII filenames; prevent # them from being added to the repository. We exploit the fact that the # printable range starts at the space character and ends with tilde. if [ "$allownonascii" != "true" ] && # Note that the use of brackets around a tr range is ok here, (it's # even required, for portability to Solaris 10's /usr/bin/tr), since # the square bracket bytes happen to fall in the designated range. test $(git diff --cached --name-only --diff-filter=A -z $against | LC_ALL=C tr -d '[ -~]\0' | wc -c) != 0 then cat <<\EOF Error: Attempt to add a non-ASCII file name. This can cause problems if you want to work with people on other platforms. To be portable it is advisable to rename the file. If you know what you are doing you can disable this check using: git config hooks.allownonascii true EOF exit 1 fi # If there are whitespace errors, print the offending file names and fail. exec git diff-index --check --cached $against --
1,643
Common Lisp
.l
40
39.5
75
0.754078
jscl-project/jscl
882
108
90
GPL-3.0
9/19/2024, 11:24:04 AM (Europe/Amsterdam)
afcf3853569d8eb02ad1d533682bd9d246c6e321db04a1db4f46a8d126f9c5a7
192
[ -1 ]
193
applypatch-msg.sample
jscl-project_jscl/.git/hooks/applypatch-msg.sample
#!/bin/sh # # An example hook script to check the commit log message taken by # applypatch from an e-mail message. # # The hook should exit with non-zero status after issuing an # appropriate message if it wants to stop the commit. The hook is # allowed to edit the commit message file. # # To enable this hook, rename this file to "applypatch-msg". . git-sh-setup commitmsg="$(git rev-parse --git-path hooks/commit-msg)" test -x "$commitmsg" && exec "$commitmsg" ${1+"$@"} :
478
Common Lisp
.l
14
33.071429
66
0.736501
jscl-project/jscl
882
108
90
GPL-3.0
9/19/2024, 11:24:04 AM (Europe/Amsterdam)
015d2f3ca6c424d68097ecfa16bc677c9c9502988da26fc3818903dbdb1f76a0
193
[ -1 ]
194
commit-msg.sample
jscl-project_jscl/.git/hooks/commit-msg.sample
#!/bin/sh # # An example hook script to check the commit log message. # Called by "git commit" with one argument, the name of the file # that has the commit message. The hook should exit with non-zero # status after issuing an appropriate message if it wants to stop the # commit. The hook is allowed to edit the commit message file. # # To enable this hook, rename this file to "commit-msg". # Uncomment the below to add a Signed-off-by line to the message. # Doing this in a hook is a bad idea in general, but the prepare-commit-msg # hook is more suited to it. # # SOB=$(git var GIT_AUTHOR_IDENT | sed -n 's/^\(.*>\).*$/Signed-off-by: \1/p') # grep -qs "^$SOB" "$1" || echo "$SOB" >> "$1" # This example catches duplicate Signed-off-by lines. test "" = "$(grep '^Signed-off-by: ' "$1" | sort | uniq -c | sed -e '/^[ ]*1[ ]/d')" || { echo >&2 Duplicate Signed-off-by lines. exit 1 }
896
Common Lisp
.l
21
41.333333
78
0.680046
jscl-project/jscl
882
108
90
GPL-3.0
9/19/2024, 11:24:04 AM (Europe/Amsterdam)
5a8d6acdfb565bba6964d8ff79c01dc0bb92081113a9bd18c0a6ac9376c3c035
194
[ -1 ]
195
prepare-commit-msg.sample
jscl-project_jscl/.git/hooks/prepare-commit-msg.sample
#!/bin/sh # # An example hook script to prepare the commit log message. # Called by "git commit" with the name of the file that has the # commit message, followed by the description of the commit # message's source. The hook's purpose is to edit the commit # message file. If the hook fails with a non-zero status, # the commit is aborted. # # To enable this hook, rename this file to "prepare-commit-msg". # This hook includes three examples. The first one removes the # "# Please enter the commit message..." help message. # # The second includes the output of "git diff --name-status -r" # into the message, just before the "git status" output. It is # commented because it doesn't cope with --amend or with squashed # commits. # # The third example adds a Signed-off-by line to the message, that can # still be edited. This is rarely a good idea. COMMIT_MSG_FILE=$1 COMMIT_SOURCE=$2 SHA1=$3 /usr/bin/perl -i.bak -ne 'print unless(m/^. Please enter the commit message/..m/^#$/)' "$COMMIT_MSG_FILE" # case "$COMMIT_SOURCE,$SHA1" in # ,|template,) # /usr/bin/perl -i.bak -pe ' # print "\n" . `git diff --cached --name-status -r` # if /^#/ && $first++ == 0' "$COMMIT_MSG_FILE" ;; # *) ;; # esac # SOB=$(git var GIT_COMMITTER_IDENT | sed -n 's/^\(.*>\).*$/Signed-off-by: \1/p') # git interpret-trailers --in-place --trailer "$SOB" "$COMMIT_MSG_FILE" # if test -z "$COMMIT_SOURCE" # then # /usr/bin/perl -i.bak -pe 'print "\n" if !$first_line++' "$COMMIT_MSG_FILE" # fi
1,492
Common Lisp
.l
37
39.189189
105
0.686207
jscl-project/jscl
882
108
90
GPL-3.0
9/19/2024, 11:24:04 AM (Europe/Amsterdam)
db7e07ca49f5a5ee61c03d6bb8a3210777d4289f8052e2398949b5a0b1559a92
195
[ -1 ]
196
pre-rebase.sample
jscl-project_jscl/.git/hooks/pre-rebase.sample
#!/bin/sh # # Copyright (c) 2006, 2008 Junio C Hamano # # The "pre-rebase" hook is run just before "git rebase" starts doing # its job, and can prevent the command from running by exiting with # non-zero status. # # The hook is called with the following parameters: # # $1 -- the upstream the series was forked from. # $2 -- the branch being rebased (or empty when rebasing the current branch). # # This sample shows how to prevent topic branches that are already # merged to 'next' branch from getting rebased, because allowing it # would result in rebasing already published history. publish=next basebranch="$1" if test "$#" = 2 then topic="refs/heads/$2" else topic=`git symbolic-ref HEAD` || exit 0 ;# we do not interrupt rebasing detached HEAD fi case "$topic" in refs/heads/??/*) ;; *) exit 0 ;# we do not interrupt others. ;; esac # Now we are dealing with a topic branch being rebased # on top of master. Is it OK to rebase it? # Does the topic really exist? git show-ref -q "$topic" || { echo >&2 "No such branch $topic" exit 1 } # Is topic fully merged to master? not_in_master=`git rev-list --pretty=oneline ^master "$topic"` if test -z "$not_in_master" then echo >&2 "$topic is fully merged to master; better remove it." exit 1 ;# we could allow it, but there is no point. fi # Is topic ever merged to next? If so you should not be rebasing it. only_next_1=`git rev-list ^master "^$topic" ${publish} | sort` only_next_2=`git rev-list ^master ${publish} | sort` if test "$only_next_1" = "$only_next_2" then not_in_topic=`git rev-list "^$topic" master` if test -z "$not_in_topic" then echo >&2 "$topic is already up to date with master" exit 1 ;# we could allow it, but there is no point. else exit 0 fi else not_in_next=`git rev-list --pretty=oneline ^${publish} "$topic"` /usr/bin/perl -e ' my $topic = $ARGV[0]; my $msg = "* $topic has commits already merged to public branch:\n"; my (%not_in_next) = map { /^([0-9a-f]+) /; ($1 => 1); } split(/\n/, $ARGV[1]); for my $elem (map { /^([0-9a-f]+) (.*)$/; [$1 => $2]; } split(/\n/, $ARGV[2])) { if (!exists $not_in_next{$elem->[0]}) { if ($msg) { print STDERR $msg; undef $msg; } print STDERR " $elem->[1]\n"; } } ' "$topic" "$not_in_next" "$not_in_master" exit 1 fi <<\DOC_END This sample hook safeguards topic branches that have been published from being rewound. The workflow assumed here is: * Once a topic branch forks from "master", "master" is never merged into it again (either directly or indirectly). * Once a topic branch is fully cooked and merged into "master", it is deleted. If you need to build on top of it to correct earlier mistakes, a new topic branch is created by forking at the tip of the "master". This is not strictly necessary, but it makes it easier to keep your history simple. * Whenever you need to test or publish your changes to topic branches, merge them into "next" branch. The script, being an example, hardcodes the publish branch name to be "next", but it is trivial to make it configurable via $GIT_DIR/config mechanism. With this workflow, you would want to know: (1) ... if a topic branch has ever been merged to "next". Young topic branches can have stupid mistakes you would rather clean up before publishing, and things that have not been merged into other branches can be easily rebased without affecting other people. But once it is published, you would not want to rewind it. (2) ... if a topic branch has been fully merged to "master". Then you can delete it. More importantly, you should not build on top of it -- other people may already want to change things related to the topic as patches against your "master", so if you need further changes, it is better to fork the topic (perhaps with the same name) afresh from the tip of "master". Let's look at this example: o---o---o---o---o---o---o---o---o---o "next" / / / / / a---a---b A / / / / / / / / c---c---c---c B / / / / \ / / / / b---b C \ / / / / / \ / ---o---o---o---o---o---o---o---o---o---o---o "master" A, B and C are topic branches. * A has one fix since it was merged up to "next". * B has finished. It has been fully merged up to "master" and "next", and is ready to be deleted. * C has not merged to "next" at all. We would want to allow C to be rebased, refuse A, and encourage B to be deleted. To compute (1): git rev-list ^master ^topic next git rev-list ^master next if these match, topic has not merged in next at all. To compute (2): git rev-list master..topic if this is empty, it is fully merged to "master". DOC_END
4,898
Common Lisp
.l
138
32.804348
77
0.65701
jscl-project/jscl
882
108
90
GPL-3.0
9/19/2024, 11:24:04 AM (Europe/Amsterdam)
040e405fd5173e93508b0a7f089c8346242a6ddd0940443ffb838194eab5ec21
196
[ -1 ]
197
pre-push.sample
jscl-project_jscl/.git/hooks/pre-push.sample
#!/bin/sh # An example hook script to verify what is about to be pushed. Called by "git # push" after it has checked the remote status, but before anything has been # pushed. If this script exits with a non-zero status nothing will be pushed. # # This hook is called with the following parameters: # # $1 -- Name of the remote to which the push is being done # $2 -- URL to which the push is being done # # If pushing without using a named remote those arguments will be equal. # # Information about the commits which are being pushed is supplied as lines to # the standard input in the form: # # <local ref> <local oid> <remote ref> <remote oid> # # This sample shows how to prevent push of commits where the log message starts # with "WIP" (work in progress). remote="$1" url="$2" zero=$(git hash-object --stdin </dev/null | tr '[0-9a-f]' '0') while read local_ref local_oid remote_ref remote_oid do if test "$local_oid" = "$zero" then # Handle delete : else if test "$remote_oid" = "$zero" then # New branch, examine all commits range="$local_oid" else # Update to existing branch, examine new commits range="$remote_oid..$local_oid" fi # Check for WIP commit commit=$(git rev-list -n 1 --grep '^WIP' "$range") if test -n "$commit" then echo >&2 "Found WIP commit in $local_ref, not pushing" exit 1 fi fi done exit 0
1,374
Common Lisp
.l
47
27.170213
79
0.713096
jscl-project/jscl
882
108
90
GPL-3.0
9/19/2024, 11:24:04 AM (Europe/Amsterdam)
a8539795abe4186c7e05b5bc8fdec31fbeae352835bfc5bc74ddb6e822e09cee
197
[ -1 ]
198
package.lisp
whily_yalo/cc/package.lisp
;;;; -*- Mode: Lisp -*- ;;;; Author: ;;;; Yujian Zhang <[email protected]> ;;;; Description: ;;;; Package definition. ;;;; License: ;;;; GNU General Public License v2 ;;;; http://www.gnu.org/licenses/gpl-2.0.html ;;;; Copyright (C) 2009-2012 Yujian Zhang (defpackage #:cc (:use #:common-lisp) (:export #:asm #:*bootloader* #:test-cc #:write-kernel))
390
Common Lisp
.lisp
16
22.1875
49
0.600536
whily/yalo
571
32
1
GPL-2.0
9/19/2024, 11:24:32 AM (Europe/Amsterdam)
cc6af64105027810972e0608af77eefc9747473625bb330cff614c107c99c209
198
[ 125682 ]
199
keyboard.lisp
whily_yalo/cc/keyboard.lisp
;;;; -*- Mode: Lisp -*- ;;;; Author: ;;;; Yujian Zhang <[email protected]> ;;;; Description: ;;;; Keyboard handling mode functions. ;;;; BIOS interruptions are not used. ;;;; License: ;;;; GNU General Public License v2 ;;;; http://www.gnu.org/licenses/gpl-2.0.html ;;;; Copyright (C) 2015-2018 Yujian Zhang (in-package :cc) (defparameter *keyboard-constants* `( ;;; Keyboard related constants. Note that input and output are ;;; from keyboard's perspective, not from user/cpu's persepctive. (equ kbd-encoder-buf #x60) (equ kbd-encoder-cmd-reg #x60) (equ kbd-ctrl-status-reg #x64) (equ kbd-ctrl-cmd-reg #x64) (equ kbd-ctrl-status-mask-out-buf #x01) (equ kbd-ctrl-status-mask-in-buf #x02) (equ kbd-ctrl-status-mask-system #x04) (equ kbd-ctrl-status-mask-cmd-data #x08) (equ kbd-ctrl-status-mask-locked #x10) (equ kbd-ctrl-status-mask-aux-buf #x20) (equ kbd-ctrl-status-mask-timeout #x40) (equ kbd-ctrl-status-mask-parity #x80) (equ kbd-ctrl-cmd-disable-keyboard #xad) (equ kbd-ctrl-cmd-enable-keyboard #xae) (equ kbd-ctrl-cmd-read-output-port #xd0) (equ kbd-ctrl-cmd-write-output-port #xd1) (equ kbd-ctrl-cmd-enable-a20 #xdd) (equ kbd-ctrl-cmd-system-reset #xfe) (equ kbd-encoder-cmd-set-led #xed) (equ kbd-encoder-cmd-set-led-capslock-on #x4) (equ kbd-encoder-cmd-set-led-capslock-off #x0) (equ kbd-encoder-cmd-set-scan-code #xf0) (equ kbd-encoder-cmd-set-scan-code-1 #x1) (equ kbd-encoder-cmd-enable-scanning #xf4) (equ kbd-encoder-cmd-disable-scanning #xf5) (equ kbd-encoder-cmd-reset #xff) ;; Codes for key states and toggle stages. Defined by internal usage only. (equ kbd-left-shift #x80) (equ kbd-right-shift #x81) (equ kbd-left-ctrl #x82) (equ kbd-right-ctrl #x83) (equ kbd-left-alt #x84) (equ kbd-right-alt #x85) (equ kbd-capslock #x86) (equ kbd-numlock #x87) (equ kbd-ascii-a #x61) (equ kbd-ascii-q #x71) (equ kbd-ascii-z #x7a) ;; Test whether key is released or not. If highest bit is 1, then key ;; is released; otherwise pressed. (equ kbd-key-released-mask #x80) ;; Reset the highest bit (indicating key is released or not) to 0. ;; kbd-scancode-mask is 1's complement of kbd-key-released-mask (equ kbd-scancode-mask #x7f) )) (defparameter *keyboard-16* ;;; 16-bit keyboard code related to A20 enabling. `(;;; The following 4 functions are exactly same (except the label ;;; names) as those functions without -16 suffix, defined in ;;; *keyboard*. Function descriptions are not shown here. kbd-ctrl-send-cmd-16 (mov bl al) ; Save AL (call wait-kbd-in-buf-16) (mov al bl) (out kbd-ctrl-cmd-reg al) (ret) kbd-encoder-send-cmd-16 (mov bl al) ; Save AL (call wait-kbd-in-buf-16) (mov al bl) (out kbd-encoder-cmd-reg al) (ret) wait-kbd-in-buf-16 (in al kbd-ctrl-status-reg) ; Get status (test al kbd-ctrl-status-mask-in-buf) (jnz wait-kbd-in-buf-16) (ret) wait-kbd-out-buf-16 (in al kbd-ctrl-status-reg) ; Get status (test al kbd-ctrl-status-mask-out-buf) (jz wait-kbd-out-buf-16) (ret) )) (defparameter *keyboard* `( ;;; Initialize keyboard by set scan code set 1. ;;; Input: None ;;; Output: None ,@(def-fun 'init-keyboard nil `( ;; TODO: double check whether to use encoder-cmd or ctrl-cmd. ;; TODO: Enable init-keyboard in kernel. (mov dil kbd-encoder-cmd-reset) ,@(call-function 'kbd-encoder-send-cmd) (mov dil kbd-encoder-cmd-disable-scanning) ,@(call-function 'kbd-encoder-send-cmd) (mov dil kbd-encoder-cmd-set-scan-code) ,@(call-function 'kbd-encoder-send-cmd) (mov dil kbd-encoder-cmd-set-scan-code-1) ,@(call-function 'kbd-encoder-send-cmd) (mov dil kbd-encoder-cmd-enable-scanning) ,@(call-function 'kbd-encoder-send-cmd))) ;;; Turn on CapsLock LED. ;;; Input: None ;;; Output: None ,@(def-fun 'turn-on-capslock-led nil `( (mov dil kbd-encoder-cmd-set-led) ,@(call-function 'kbd-encoder-send-cmd) (mov dil kbd-encoder-cmd-set-led-capslock-on) ,@(call-function 'kbd-encoder-send-cmd) )) ;;; Send command byte to keyboard controller. ;;; Input: ;;; AL: command byte ;;; Output: None ;;; Modified registers: BL ,@(def-fun 'kbd-ctrl-send-cmd nil `( ,@(call-function 'wait-kbd-in-buf) (mov al dil) (out kbd-ctrl-cmd-reg al))) ;;; Send command byte to keyboard encoder. ;;; Input: ;;; DIL: command byte ;;; Output: None ;;; Modified registers: AL ,@(def-fun 'kbd-encoder-send-cmd nil `( ,@(call-function 'wait-kbd-in-buf) (mov al dil) (out kbd-encoder-cmd-reg al))) ;;; Wait until the keyboard controller input buffer empty, ;;; therefore command can be written ;;; Input: None ;;; Output: None ;;; Modified registers: AL ,@(def-fun 'wait-kbd-in-buf nil `( (in al kbd-ctrl-status-reg) ; Get status (test al kbd-ctrl-status-mask-in-buf) (jnz wait-kbd-in-buf))) ;;; Wait until the keyboard controller output buffer ready for ;;; reading. ;;; Input: None ;;; Output: None ;;; Modified registers: AL ,@(def-fun 'wait-kbd-out-buf nil `( (in al kbd-ctrl-status-reg) ; Get status (test al kbd-ctrl-status-mask-out-buf) (jz wait-kbd-out-buf))) ;;; Function getchar. Get keystroke from keyboard without echo. If ;;; keystroke is available, it is removed from keyboard buffer. ;;; Use polling method. TODO: use interrupt. ;;; So far only a few keys are scanned. TODO: support full set of scan code. ;;; TODO: handle key repetition. ;;; Input: None ;;; Output: ;;; AL: ASCII character (0 indicats a key is released or not handled) ;;; Modified registers: RSI, RDX ,@(def-fun 'getchar nil `( ,@(call-function 'wait-kbd-out-buf) (xor eax eax) ;; Use DL to store whether key is released or pressed. ;; Zero: key is pressed; otherwise released. (xor edx edx) (in al kbd-encoder-buf) ; Get key data (mov dl al) ;; After following instruction, DL stores whether key is released (#x80) ;; or pressed (#x0). (and dl kbd-key-released-mask) (and al kbd-scancode-mask) ;; Now highest bit of AL is 0, and we can index into scan code set table. (mov rsi scan-code-set-1) (add rsi rax) (lodsb) (cmp al kbd-left-shift) ;; kbd-left-shift is the first code for key and toggle states. (jb near .shutdown-check) (jnz .check-right-shift) (test dl dl) (setz (kbd-left-shift-status)) (jmp short .set-shift-status) .check-right-shift (cmp al kbd-right-shift) (jnz .check-capslock) (test dl dl) (setz (kbd-right-shift-status)) (jmp short .set-shift-status) .check-capslock (cmp al kbd-capslock) (jnz .check-left-ctrl) (test dl dl) ;; Ignore the release of Capslock key. (jnz near .clear-key) ;; Toggle kbd-capslock-status between 0 and 1. (xor byte (kbd-capslock-status) 1) ;; We don't call function `turn-on-capslock-led' since at ;; least in QEMU, it seems that even if guest OS does ;; nothing, Capslock LED is automatically adjusted. ;; Note: in host, if Capslock and Left Ctrl are swapped in file ~/.Xmodmap, ;; Bochs respects the change, while QEMU and VirtualBox still only recognize ;; old Capslock. .set-shift-status ;; Use DH to store the overall Shift status. (mov dh (kbd-left-shift-status)) (or dh (kbd-right-shift-status)) (mov (kbd-shift-status) dh) (xor dh (kbd-capslock-status)) (mov (kbd-to-upper-status) dh) (jmp near .clear-key) .check-left-ctrl (cmp al kbd-left-ctrl) (jnz .check-right-ctrl) (test dl dl) (setz (kbd-left-ctrl-status)) (jmp short .set-ctrl-status) .check-right-ctrl (cmp al kbd-right-ctrl) (jnz .check-left-alt) (test dl dl) (setz (kbd-right-ctrl-status)) .set-ctrl-status ;; Use DH to store the overall Ctrl status. (mov dh (kbd-left-ctrl-status)) (or dh (kbd-right-ctrl-status)) (mov (kbd-ctrl-status) dh) (jmp near .clear-key) .check-left-alt (cmp al kbd-left-alt) (jnz .check-right-alt) (test dl dl) (setz (kbd-left-alt-status)) (jmp short .set-alt-status) .check-right-alt (cmp al kbd-right-alt) (jnz near .clear-key) (test dl dl) (setz (kbd-right-alt-status)) .set-alt-status ;; Use DH to store the overall Alt status. (mov dh (kbd-left-alt-status)) (or dh (kbd-right-alt-status)) (mov (kbd-alt-status) dh) (jmp near .clear-key) .shutdown-check ;; For BOCHS only. Check whether Ctrl-Alt-q is pressed. (mov dh (kbd-ctrl-status)) (and dh (kbd-alt-status)) (test dh dh) (jz .translate-check) (cmp al kbd-ascii-q) (jnz .translate-check) ,@(call-function 'bochs-shutdown) ;; The computer should have been shutdown already. Just for completeness. (jmp short .done) .translate-check ;; For alphabetic characters (a-z), check kbd-to-upper-status (i.e. ;; both Shift and Capslock are checked). Note that we don't check A-Z ;; since table scan-code-set-1 only generates a-z. (cmp al kbd-ascii-a) (jb .non-alphabetic-characters) (cmp al kbd-ascii-z) (ja .non-alphabetic-characters) .alphabetic-characters (mov dh (kbd-to-upper-status)) (test dh dh) (jz .test-key-release) ; Translation not needed. (jmp short .translate) .non-alphabetic-characters (mov dh (kbd-shift-status)) (test dh dh) (jz .test-key-release) ; Translation not needed. .translate ;; Shift has been pressed (mov rsi lower-to-upper-table) (add rsi rax) (lodsb) .test-key-release (test dl dl) (jnz .done) .clear-key ;; Set AL to 0 if highest bit of DL is 1 as we don't handle key release for now. ;; Also set AL to 0 if keys for states and toggles are pressed/released. (xor eax eax) .done)) ;; Left Shift status: 0: released; 1: pressed kbd-left-shift-status (db 0) ;; Right Shift status: 0: released; 1: pressed kbd-right-shift-status (db 0) ;; Overall Shift status is 0 if all shift key are released else 1 ;; (i.e. if any of the Shift key is pressed). Note that for ;; non-alphabetic characters, only kbd-shift-status matters (i.e. ;; kbd-capslock-status does not have any influence). kbd-shift-status (db 0) ;; Capslock status: 0: off; 1: on. Note that different from Shift/Ctrl/Alt, ;; Capslock is a toggle when Capslock key is pressed. Release of Capslock key ;; is ignored. kbd-capslock-status (db 0) ;; Overall status of whether to translate characters from lower ;; case (including punctuations) to upper case. The Shift status ;; (kbd-shift-status) is XORed with Capslock status ;; (kbd-capslock-status) to determine whether lower-to-upper table ;; below should be used (if the XOR result is 1) for alphabetic ;; characters or not. kbd-to-upper-status (db 0) ;; Left Ctrl status: 0: released; 1: pressed kbd-left-ctrl-status (db 0) ;; Right Ctrl status: 0: released; 1: pressed kbd-right-ctrl-status (db 0) ;; Overall Ctrl status is 0 if all ctrl key are released else 1 ;; (i.e. if any of the Ctrl key is pressed). kbd-ctrl-status (db 0) ;; Left Alt status: 0: released; 1: pressed kbd-left-alt-status (db 0) ;; Right Alt status: 0: released; 1: pressed kbd-right-alt-status (db 0) ;; Overall Alt status is 0 if all alt key are released else 1 ;; (i.e. if any of the Alt key is pressed). kbd-alt-status (db 0) ;;; Table for Scan code set 1: http://wiki.osdev.org/Keyboard#Scan_Code_Set_1 ;;; Release code is not stored as it is simply the sum of pressed code and #x80 ;;; (as in http://www.win.tue.nl/~aeb/linux/kbd/scancodes-1.html#ss1.1) ;;; TODO: add right control and right shift. scan-code-set-1 (db 0 27 49 50 51 52 53 54 55 56 57 48 45 61 8 9 113 119 101 114 116 121 117 105 111 112 91 93 10 kbd-left-ctrl 97 115 100 102 103 104 106 107 108 59 39 96 kbd-left-shift 92 122 120 99 118 98 110 109 44 46 47 kbd-right-shift 0 kbd-left-alt 32 kbd-capslock 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ) ;;; Convert from lower case ASCII (index) to upper case ASCII (value) ;;; from https://en.wikipedia.org/wiki/ASCII#Character_set ;;; An example: index 0x30 is the ASCII code for '0', and the corresponding ;;; value is 0x29 (41 in decimal), which is the ASCII code for ;;; ')'. This corresponds to the relationship that ')' is the ;;; character when both Shift and '0' is pressed. lower-to-upper-table (db 0 0 0 0 0 0 0 0 8 9 10 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 32 0 0 0 0 0 0 34 0 0 0 0 60 95 62 63 41 33 64 35 36 37 94 38 42 40 0 58 0 43 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 123 124 125 0 0 126 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 0 0 0 0 0) ))
14,943
Common Lisp
.lisp
357
34.154062
92
0.577939
whily/yalo
571
32
1
GPL-2.0
9/19/2024, 11:24:32 AM (Europe/Amsterdam)
d0f0e09dcf100d6696f21b3b7c9e2a38df0a441ed6e25e636f125cf8d28e722a
199
[ 380199 ]
200
kernel.lisp
whily_yalo/cc/kernel.lisp
;;;; -*- Mode: Lisp -*- ;;;; Author: ;;;; Yujian Zhang <[email protected]> ;;;; Description: ;;;; 64 bit long mode kernel code. ;;;; License: ;;;; GNU General Public License v2 ;;;; http://www.gnu.org/licenses/gpl-2.0.html ;;;; Copyright (C) 2015-2018 Yujian Zhang (in-package :cc) (defparameter *kernel* `( ;;;==================== 64 bit long mode ==================== long-mode (bits 64) ;; Load constant definitions ,@*vga-text-constants* ;; Setup stack's linear address. See the related 16 bit code for reason. (mov rsp #x7ff00) ;; Reuse previous 32 bit GDT (as we don't consume more than 4 GB memory. So skip loading 64 bit GDT. ;; (lgdt (pgdt)) ;; Load 64 bit IDT. So far IDT has zero length, therefore any NMI causes a triple fault. ;;(lidt (idt)) ;; Move kernel to physical address #x100000, which is virtual address ;; #xffffffff80100000. (mov rsi kernel-before-relocation) (mov rdi kernel-physical-base) (mov rcx (- kernel-virtual-end kernel-virtual-start)) (rep movsb) ;; Jump to higher half kernel in 64 bit trampoline. (mov rdi kernel-virtual-start) (push rdi) (ret) ; Use push/ret together to implement a jmp. ;; Fill up to multiple of sectors, otherwise VirtualBox complains. (align 512) kernel-before-relocation (equ kernel-physical-base #x100000) (org (+ kernel-virtual-base kernel-physical-base)) kernel-virtual-start ;; Setup stack's linear address again. (mov rsp (+ kernel-virtual-start #x100000)) ,@(call-function 'unmap-lower-memory) ,@(call-function 'pmm-init) ,@(call-function 'clear) ;; Reload all data segments with null. (xor ax ax) (mov ss ax) (mov ds ax) (mov es ax) (mov fs ax) (mov gs ax) (mov rdi banner) ,@(call-function 'println) (jmp short read-start) banner (db "Start your journey on yalo v0.0.1!" 0) ;; So far this function is not called. Actually calling it ;; resulting in some issues ;; TODO ,@(call-function 'init-keyboard) ;;; REPL: read read-start (mov rdi repl) ,@(call-function 'print) (jmp short read) repl (db "REPL> " 0) (equ prompt-length (- $ repl 1)) read ,@(call-function 'getchar) (cmp al 10) (je eval-start) (cmp al 0) ; Non-printable character. (jz read) (cmp al ascii-backspace) (jnz .show) ,@(call-function 'backspace-char) (jmp short read) .show (mov dil al) ,@(call-function 'putchar) (jmp short read) ;;; REPL: eval eval-start ;;; REPL: print ,@(call-function 'printlf) ,@(call-function 'printlf) ;;; REPL: loop (jmp short read-start) ;; (bits 16) ;; no-bga-error ;; (mov si no-bga-message) ;; (call println-16) ;; .panic ;; (hlt) ;; (jmp short .panic) ;; no-bga-message (db "ERROR: BGA not available." 0) (bits 64) ;; Include 64 bit paging related functions from paging.lisp ,@*paging* ;; Include 64 bit memory related functions from memory.lisp ,@*memory* ;; Include content from bga.lisp. ;;,@*bga* ;; Include content from vga-text.lisp. ,@*vga-text* ;; Include content from keyboard.lisp. ,@*keyboard* ;; Include content from bitmap.lisp. ,@*bitmap* ;; Include content from bochs.lisp. ,@*bochs* ;; Function panic. Display error message and halt the computer. ,@(def-fun 'panic nil `( ,@(call-function 'println) .panic (hlt) (jmp short .panic))) ;; Fill up to multiple of sectors, otherwise VirtualBox complains. (align 512) kernel-virtual-end ;; This is the physical address of the end of the kernel. (equ kernel-physical-end (+ kernel-before-relocation (- kernel-virtual-end kernel-virtual-start))) ))
4,099
Common Lisp
.lisp
125
27.528
104
0.595274
whily/yalo
571
32
1
GPL-2.0
9/19/2024, 11:24:32 AM (Europe/Amsterdam)
04bbc3da6116072329420c8ea0460e0880b99587424867fbd3748cd423ceb619
200
[ 95961 ]
201
x86-64-syntax.lisp
whily_yalo/cc/x86-64-syntax.lisp
;;;; -*- Mode: Lisp -*- ;;;; Author: ;;;; Yujian Zhang <[email protected]> ;;;; Description: ;;;; Syntax tables for x86-64. ;;;; References: ;;;; [1] Intel 64 and IA-32 Architectures Software Developer's Manual ;;;; Volume 2, Instruction Set Reference, A-Z. June 2015 ;;;; License: ;;;; GNU General Public License v2 ;;;; http://www.gnu.org/licenses/gpl-2.0.html ;;;; Copyright (C) 2009-2015 Yujian Zhang (in-package :cc) (defun arith-syntax-1 (mnemonic 64bit-only?) "Return syntax table for arithmetic operations: adc/add/and/cmp/or/sbb/sub/xor." (let ((base ; Base opcode for operation on r/m8 r8. (ecase mnemonic (adc #x10) (add #x00) (and #x20) (cmp #x38) (or #x08) (sbb #x18) (sub #x28) (xor #x30))) (opcode ; Opcode used when one operand is immediate. (ecase mnemonic (adc '/2) (add '/0) (and '/4) (cmp '/7) (or '/1) (sbb '/3) (sub '/5) (xor '/6)))) (if 64bit-only? `(;; TODO: For imm8, encode with imm8 with generic r64 ;; (instead of rax) seems to save 3 bytes. ((,mnemonic rax imm32) . (rex.w ,(+ base #x05) id)) ((,mnemonic (r/m64 r64) (imm32 imm16)) . (rex.w #x81 ,opcode id)) ((,mnemonic qword m (imm32 imm16)) . (rex.w #x81 ,opcode id)) ((,mnemonic (r/m64 r64) imm8) . (rex.w #x83 ,opcode ib)) ((,mnemonic qword m imm8) . (rex.w #x83 ,opcode ib)) ((,mnemonic (r/m64 r64 m) r64) . (rex.w ,(+ base #x01) /r)) ((,mnemonic r64 (r/m64 r64 m)) . (rex.w ,(+ base #x03) /r))) `(((,mnemonic al imm8) . (,(+ base #x04) ib)) ((,mnemonic ax imm16) . (o16 ,(+ base #x05) iw)) ((,mnemonic eax imm32) . (o32 ,(+ base #x05) id)) ((,mnemonic (r/m8 r8) imm8) . (#x80 ,opcode ib)) ((,mnemonic byte m imm8) . (#x80 ,opcode ib)) ((,mnemonic (r/m16 r16) imm8) . (o16 #x83 ,opcode ib)) ((,mnemonic (r/m32 r32) imm8) . (o32 #x83 ,opcode ib)) ((,mnemonic word m imm8) . (o16 #x83 ,opcode ib)) ((,mnemonic dword m imm8) . (o32 #x83 ,opcode ib)) ((,mnemonic (r/m16 r16) imm16) . (o16 #x81 ,opcode iw)) ((,mnemonic word m imm16) . (o16 #x81 ,opcode iw)) ((,mnemonic (r/m32 r32) (imm32 imm16)) . (o32 #x81 ,opcode id)) ((,mnemonic dword m (imm32 imm16)) . (o32 #x81 ,opcode id)) ((,mnemonic r/m8 r8) . (,base /r)) ((,mnemonic (r/m16 r16 m) r16) . (o16 ,(+ base #x01) /r)) ((,mnemonic (r/m32 r32 m) r32) . (o32 ,(+ base #x01) /r)) ((,mnemonic r8 r/m8) . (,(+ base #x02) /r)) ((,mnemonic r16 (r/m16 r16 m)) . (o16 ,(+ base #x03) /r)) ((,mnemonic r32 (r/m32 r32 m)) . (o32 ,(+ base #x03) /r)))))) (defun arith-syntax-2 (mnemonic 64bit-only?) "Return syntax table for arithmetic operations: div/mul/neg/not." (let ((opcode (ecase mnemonic (div '/6) (mul '/4) (neg '/3) (not '/2)))) (if 64bit-only? `(((,mnemonic (r/m64 r64)) . (rex.w #xf7 ,opcode)) ((,mnemonic qword m) . (rex.w #xf7 ,opcode))) `(((,mnemonic (r/m8 r8)) . (#xf6 ,opcode)) ((,mnemonic byte m) . (#xf6 ,opcode)) ((,mnemonic (r/m16 r16)) . (o16 #xf7 ,opcode)) ((,mnemonic word m) . (o16 #xf7 ,opcode)) ((,mnemonic (r/m32 r32)) . (o32 #xf7 ,opcode)) ((,mnemonic dword m) . (o32 #xf7 ,opcode)))))) (defun shift-syntax (mnemonic 64bit-only?) "Return syntax table for shift operations: sal/sar/shl/shr." (let ((opcode (ecase mnemonic (sal '/4) (sar '/7) (shl '/4) (shr '/5)))) (if 64bit-only? `(((,mnemonic r64 1) . (rex.w #xd1 ,opcode)) ((,mnemonic qword m 1) . (rex.w #xd1 ,opcode)) ((,mnemonic r64 cl) . (rex.w #xd3 ,opcode)) ((,mnemonic qword m cl) . (rex.w #xd3 ,opcode)) ((,mnemonic r64 imm8) . (rex.w #xc1 ,opcode ib)) ((,mnemonic qword m imm8) . (rex.w #xc1 ,opcode ib))) `(((,mnemonic r8 1) . (#xd0 ,opcode)) ((,mnemonic byte m 1) . (#xd0 ,opcode)) ((,mnemonic r8 cl) . (#xd2 ,opcode)) ((,mnemonic byte m cl) . (#xd2 ,opcode)) ((,mnemonic r8 imm8) . (#xc0 ,opcode ib)) ((,mnemonic byte m imm8) . (#xc0 ,opcode ib)) ((,mnemonic r16 1) . (o16 #xd1 ,opcode)) ((,mnemonic word m 1) . (o16 #xd1 ,opcode)) ((,mnemonic r16 cl) . (o16 #xd3 ,opcode)) ((,mnemonic word m cl) . (o16 #xd3 ,opcode)) ((,mnemonic r16 imm8) . (o16 #xc1 ,opcode ib)) ((,mnemonic word m imm8) . (o16 #xc1 ,opcode ib)) ((,mnemonic r32 1) . (o32 #xd1 ,opcode)) ((,mnemonic dword m 1) . (o32 #xd1 ,opcode)) ((,mnemonic r32 cl) . (o32 #xd3 ,opcode)) ((,mnemonic dword m cl) . (o32 #xd3 ,opcode)) ((,mnemonic r32 imm8) . (o32 #xc1 ,opcode ib)) ((,mnemonic dword m imm8) . (o32 #xc1 ,opcode ib)))))) (defun bit-syntax (mnemonic 64bit-only?) "Return syntax table for arithmetic operations: bt/btc/btr/bts." (let ((base ; Base opcode for operation on r/m16, r16, r/m32, r32, r/m64, r64. (ecase mnemonic (bt #x0) (btc #x18) (btr #x10) (bts #x8))) (opcode ; Opcode used when one operand is immediate. (ecase mnemonic (bt '/4) (btc '/7) (btr '/6) (bts '/5)))) (if 64bit-only? `(((,mnemonic r/m64 r64) . (rex.w #x0f ,(+ base #xa3) /r)) ((,mnemonic r/m64 imm8) . (rex.w #x0f #xba ,opcode ib))) `(((,mnemonic r/m16 r16) . (o16 #x0f ,(+ base #xa3) /r)) ((,mnemonic r/m32 r32) . (o32 #x0f ,(+ base #xa3) /r)) ((,mnemonic r/m16 imm8) . (o16 #x0f #xba ,opcode ib)) ((,mnemonic r/m32 imm8) . (o32 #x0f #xba ,opcode ib)))))) ;;; Following are syntax tables for x86-64. For each entry, 1st part ;;; is the instruction type, 2nd part is the corresponding opcode. ;;; Note that for the 1st part, list may be used for the operand to ;;; match the type (e.g. imm8 converted to imm16). Note that the ;;; canonical form should be placed first (e.g. if the operand type ;;; should be imm16, place it as the car of the list). ;;; ;;; For details, ;;; refer to https://github.com/whily/yalo/blob/master/doc/AssemblyX64.md (defparameter *x86-64-syntax-common* `( ,@(arith-syntax-1 'adc nil) ,@(arith-syntax-1 'add nil) ,@(arith-syntax-1 'and nil) ((bswap r32) . (#x0f (+ #xc8 r))) ,@(bit-syntax 'bt nil) ,@(bit-syntax 'btc nil) ,@(bit-syntax 'btr nil) ,@(bit-syntax 'bts nil) ((bsf r16 r/m16) . (o16 #x0f #xbc /r)) ((bsf r32 r/m32) . (o32 #x0f #xbc /r)) ((bsr r16 r/m16) . (o16 #x0f #xbd /r)) ((bsr r32 r/m32) . (o32 #x0f #xbd /r)) ((call (imm32 imm64 imm16 imm8 label)) . (o32 #xe8 cd)) ;; Below is just an hack so that we can always use 32 bit operand ;; when operating in 32 bit mode. TODO. ;; As current assembler did not differentiate too much between 16 ;; bit and 32 bit mode, as we need 32 bit operand size for near ;; relative call in 32 bit, one SHOULD always use call32 below to ;; call function when working in 32 bit mode (so far in our ;; bootloader, 32 bit mode is transient as we just setup paging ;; and goes to 64 bit mode. ;; Warning: simply using `call` might result in stack corruption ;; (as 16 bit IP is pushed to stack instead of 32 bit), and memory exception ;; might occur when return using wrong EIP. ((call32 (imm32 imm64 imm16 imm8 label)) . (o32 #xe8 cd)) ((clc) . (#xf8)) ((cld) . (#xfc)) ((cli) . (#xfa)) ((cmovcc r16 r/m16) . (o16 #x0f (+ #x40 cc) /r)) ((cmovcc r32 r/m32) . (o32 #x0f (+ #x40 cc) /r)) ,@(arith-syntax-1 'cmp nil) ((cmpxchg r/m8 r8) . (#x0f #xb0 /r)) ((cmpxchg r/m16 r16) . (o16 #x0f #xb1 /r)) ((cmpxchg r/m32 r32) . (o32 #x0f #xb1 /r)) ((cmpxchg8b m) . (#x0f #xc7 /1)) ((cpuid) . (#x0f #xa2)) ((dec (r/m8 r8)) . (#xfe /1)) ((dec byte m) . (#xfe /1)) ((dec (r/m16 r16)) . (o16 #xff /1)) ((dec word m) . (o16 #xff /1)) ((dec (r/m32 r32)) . (o32 #xff /1)) ((dec dword m) . (o32 #xff /1)) ,@(arith-syntax-2 'div nil) ((hlt) . (#xf4)) ((in al imm8) . (#xe4 ib)) ((in ax imm8) . (#xe5 ib)) ((in al dx) . (#xec)) ((in ax dx) . (#xed)) ((inc (r/m8 r8)) . (#xfe /0)) ((inc byte m) . (#xfe /0)) ((inc (r/m16 r16)) . (o16 #xff /0)) ((inc word m) . (o16 #xff /0)) ((inc (r/m32 r32)) . (o32 #xff /0)) ((inc dword m) . (o32 #xff /0)) ((int 3) . (#xcc)) ((int imm8) . (#xcd ib)) ((invlpg m) . (#x0f #x01 /7)) ((jcc (imm8 label imm16 imm32 imm64)) . ((+ #x70 cc) cb)) ((jcc near (imm32 label imm8 imm16 imm64)) . (#x0f (+ #x80 cc) cd)) ((jecxz (imm8 label imm16 imm32 imm64)) . (a32 #xe3 cb)) ((jmp short (imm8 label imm16 imm32 imm64)) . (#xeb cb)) ((lgdt m) . (#x0f #x01 /2)) ((lidt m) . (#x0f #x01 /3)) ((lldt r/m16) . (#x0f #x00 /2)) ((lodsb) . (#xac)) ((lodsw) . (o16 #xad)) ((lodsd) . (o32 #xad)) ((loop (imm8 label imm16 imm32 imm64)) . (#xe2 cb)) ((mov r8 imm8) . ((+ #xb0 r) ib)) ((mov r16 (imm16 imm8 imm label)) . (o16 (+ #xb8 r) iw)) ((mov r32 (imm32 imm16 imm8 imm label)) . (o32 (+ #xb8 r) id)) ((mov r/m8 r8) . (#x88 /r)) ((mov r/m16 r16) . (o16 #x89 /r)) ((mov r/m32 r32) . (o32 #x89 /r)) ((mov r8 r/m8) . (#x8a /r)) ((mov r16 r/m16) . (o16 #x8b /r)) ((mov r32 r/m32) . (o32 #x8b /r)) ((mov byte m (imm8 imm label)) . (#xc6 /0 ib)) ((mov word m (imm16 imm8 imm label)) . (o16 #xc7 /0 iw)) ((mov dword m (imm32 imm16 imm8 imm label)) . (o32 #xc7 /0 id)) ((mov sreg r/m16) . (#x8e /r)) ((mov r/m16 sreg) . (#x8c /r)) ((movsb) . (#xa4)) ((movsw) . (o16 #xa5)) ((movsd) . (o32 #xa5)) ((movzx r16 r/m8) . (o16 #x0f #xb6 /r)) ((movzx r32 (r/m8 r8)) . (o32 #x0f #xb6 /r)) ((movzx r32 byte m) . (o32 #x0f #xb6 /r)) ((movzx r32 (r/m16 r16)) . (o32 #x0f #xb7 /r)) ((movzx r32 word m) . (o32 #x0f #xb7 /r)) ,@(arith-syntax-2 'mul nil) ,@(arith-syntax-2 'neg nil) ((nop) . (#x90)) ,@(arith-syntax-2 'not nil) ,@(arith-syntax-1 'or nil) ((out imm8 r8) . (#xe6 ib)) ; (out imm8 al) ((out imm8 r16) . (#xe7 ib)) ; (out imm8 ax) ((out dx al) . (#xee)) ((out dx ax) . (#xef)) ((pop r16) . (o16 (+ #x58 r))) ;; Note that for 64 bit mode, prefix #x66 should be used according ;; to section 4.2 (INSTRUCTIONS (N-Z)) of [1]. This is different from NASM. ((popf) . (o16 #x9d)) ((push r16) . (o16 (+ #x50 r))) ;; Note that for 64 bit mode, prefix #x66 should be used according ;; to section 4.2 (INSTRUCTIONS (N-Z)) of [1]. This is different from NASM. ((pushf) . (o16 #x9c)) ((ret) . (#xc3)) ((rdmsr) . (#x0f #x32)) ,@(shift-syntax 'sal nil) ,@(shift-syntax 'sar nil) ,@(shift-syntax 'shl nil) ,@(shift-syntax 'shr nil) ((stc) . (#xf9)) ((std) . (#xfd)) ((sti) . (#xfb)) ((stosb) . (#xaa)) ((stosw) . (o16 #xab)) ((stosd) . (o32 #xab)) ,@(arith-syntax-1 'sbb nil) ,@(arith-syntax-1 'sub nil) ((test al imm8) . (#xa8 ib)) ((test ax imm16) . (#xa9 iw)) ((test (r/m8 r8) imm8) . (#xf6 /0 ib)) ((test byte m imm8) . (#xf6 /0 ib)) ((test r/m16 imm16) . (#xf7 /0 iw)) ((test word m imm16) . (#xf7 /0 iw)) ((test r/m32 imm32) . (#xf7 /0 id)) ((test dword m imm32) . (#xf7 /0 id)) ((test r/m8 r8) . (#x84 /r)) ((test r/m16 r16) . (#x85 /r)) ((test r/m32 r32) . (#x85 /r)) ((wrmsr) . (#x0f #x30)) ((xadd r/m8 r8) . (#x0f #xc0 /r)) ((xadd r/m16 r16) . (o16 #x0f #xc1 /r)) ((xadd r/m32 r32) . (o32 #x0f #xc1 /r)) ((xchg r16 ax) . (o16 (+ #x90 r))) ((xchg r32 eax) . (o32 (+ #x90 r))) ((xchg r/m8 r8) . (#x86 /r)) ((xchg r8 r/m8) . (#x86 /r)) ((xchg r/m16 r16) . (o16 #x87 /r)) ((xchg r16 r/m16) . (o16 #x87 /r)) ((xchg r/m32 r32) . (o32 #x87 /r)) ((xchg r32 r/m32) . (o32 #x87 /r)) ,@(arith-syntax-1 'xor nil)) "Valid for both 16-bit and 64-bit modes.") (defparameter *x86-64-syntax-16/32-bit-only* `(((call (imm16 imm8 label)) . (o16 #xe8 cw)) ((dec r16) . (o16 (+ #x48 r))) ((dec r32) . (o32 (+ #x48 r))) ((inc r16) . (o16 (+ #x40 r))) ((inc r32) . (o32 (+ #x40 r))) ((jcxz (imm8 label imm16 imm32)) . (a16 #xe3 cb)) ((jmp near (imm16 label imm8 imm32)) . (#xe9 cw)) ((mov r32 cr0-cr7) . (#x0f #x20 /r)) ((mov cr0-cr7 r32) . (#x0f #x22 /r)) ((pop r32) . (o32 (+ #x58 r))) ((pop ss) . (#x17)) ((pop ds) . (#x1f)) ((pop es) . (#x07)) ((popfd) . (o32 #x9d)) ((push r32) . (o32 (+ #x50 r))) ((push cs) . (#x0e)) ((push ss) . (#x16)) ((push ds) . (#x1e)) ((push es) . (#x06)) ((pushfd) . (o32 #x9c))) "Valid for 16-bit mode only.") (defparameter *x86-64-syntax-64-bit-only* `( ,@(arith-syntax-1 'adc t) ,@(arith-syntax-1 'add t) ,@(arith-syntax-1 'and t) ((bswap r64) . (rex.w #x0f (+ #xc8 r))) ,@(bit-syntax 'bt t) ,@(bit-syntax 'btc t) ,@(bit-syntax 'btr t) ,@(bit-syntax 'bts t) ((bsf r64 r/m64) . (rex.w #x0f #xbc /r)) ((bsr r64 r/m64) . (rex.w #x0f #xbd /r)) ((cmovcc r64 r/m64) . (rex.w #x0f (+ #x40 cc) /r)) ((cmpxchg r/m64 r64) . (rex.w #x0f #xb1 /r)) ((cmpxchg16b m) . (rex.w #x0f #xc7 /1)) ,@(arith-syntax-1 'cmp t) ((dec (r/m64 r64)) . (rex.w #xff /1)) ((dec qword m) . (rex.w #xff /1)) ,@(arith-syntax-2 'div t) ((inc (r/m64 r64)) . (rex.w #xff /0)) ((inc qword m) . (rex.w #xff /0)) ((iretq) . (rex.w #xcf)) ;; The following instruction is available for 16/32 bit, but we only support it ;; in 64 bit for simplicity (there are already more compact `jmp near` in 16/32 bits.) ((jmp near (imm32 label imm8 imm16 imm64)) . (#xe9 cd)) ((jmp near r/m64) . (#xff /4)) ((jrcxz (imm8 label imm16 imm32 imm64)) . (#xe3 cb)) ((leave) . (#xc9)) ((lodsq) . (rex.w #xad)) ;; For the following two instructions (including the one commented out) ;; we use id instead of io (as in instruction manual) for imm32. ;; NASM generates same results. ;; The following instruction is handled in function match-instruction, ;; therefore commented out. ;; ((mov r64 -imm32) . (rex.w #xc7 /0 id)) ((mov qword m (imm32 imm16 imm8 imm label)) . (rex.w #xc7 /0 id)) ((mov r64 (imm32 imm16 imm8 imm)) . ((+ #xb8 r) id)) ((mov r64 (imm64 label)) . (rex.w (+ #xb8 r) io)) ((mov r/m64 r64) . (rex.w #x89 /r)) ((mov r64 r/m64) . (rex.w #x8b /r)) ((movsq) . (rex.w #xa5)) ((movzx r64 (r/m8 r8)) . (rex.w #x0f #xb6 /r)) ((movzx r64 byte m) . (rex.w #x0f #xb6 /r)) ((movzx r64 (r/m16 r16)) . (rex.w #x0f #xb7 /r)) ((movzx r64 word m) . (rex.w #x0f #xb7 /r)) ,@(arith-syntax-2 'mul t) ,@(arith-syntax-2 'neg t) ,@(arith-syntax-2 'not t) ,@(arith-syntax-1 'or t) ((pop r64) . ((+ #x58 r))) ((popcnt r64 r/m64) . (#xf3 rex.w #x0f #xb8 /r)) ((popfq) . (#x9d)) ((push r64) . ((+ #x50 r))) ((pushfq) . (#x9c)) ((setcc r/m8) . (#x0f (+ #x90 cc) /0)) ,@(shift-syntax 'sal t) ,@(shift-syntax 'sar t) ,@(shift-syntax 'shl t) ,@(shift-syntax 'shr t) ,@(arith-syntax-1 'sbb t) ((stosq) . (rex.w #xab)) ,@(arith-syntax-1 'sub t) ((syscall) . (#x0f #x05)) ((sysret) . (#x0f #x07)) ((test rax imm32) . (rex.w #xa9 id)) ((test r/m64 imm32) . (rex.w #xf7 /0 id)) ((test qword m imm32) . (rex.w #xf7 /0 id)) ((test r/m64 r64) . (rex.w #x85 /r)) ((xadd r/m64 r64) . (rex.w #x0f #xc1 /r)) ((xchg r64 rax) . (rex.w (+ #x90 r))) ((xchg r/m64 r64) . (rex.w #x87 /r)) ((xchg r64 r/m64) . (rex.w #x87 /r)) ,@(arith-syntax-1 'xor t))) (defparameter *x86-64-syntax-16/32-bit* (append *x86-64-syntax-16/32-bit-only* *x86-64-syntax-common*) "Syntax table for 16-bit mode.") (defparameter *x86-64-syntax-64-bit* (append *x86-64-syntax-64-bit-only* *x86-64-syntax-common*) "Syntax table for 64-bit mode.") (defun x86-64-syntax (bits) "Returns syntax table according to bit mode (16, 32 or 64)." (ecase bits ((16 32) *x86-64-syntax-16/32-bit*) (64 *x86-64-syntax-64-bit*)))
21,253
Common Lisp
.lisp
373
51.120643
90
0.405597
whily/yalo
571
32
1
GPL-2.0
9/19/2024, 11:24:32 AM (Europe/Amsterdam)
ba317b2abc227fdc49ec3699bf607bb06c1213ac0f2325669f631fe66e8abc91
201
[ 52321 ]
202
bga.lisp
whily_yalo/cc/bga.lisp
;;;; -*- Mode: Lisp -*- ;;;; Author: ;;;; Yujian Zhang <[email protected]> ;;;; Description: ;;;; Bochs VBE Extensions, see http://wiki.osdev.org/BGA ;;;; License: ;;;; GNU General Public License v2 ;;;; http://www.gnu.org/licenses/gpl-2.0.html ;;;; Copyright (C) 2012 Yujian Zhang (in-package :cc) (defparameter *bga* `( ;;; BGA constants (equ vbe-dispi-ioport-index #x1ce) (equ vbe-dispi-ioport-data #x1cf) (equ vbe-dispi-index-id 0) (equ vbe-dispi-index-xres 1) (equ vbe-dispi-index-yres 2) (equ vbe-dispi-index-bpp 3) (equ vbe-dispi-index-enable 4) (equ vbe-dispi-index-bank 5) (equ vbe-dispi-index-virt-width 6) (equ vbe-dispi-index-virt-height 7) (equ vbe-dispi-index-x-offset 8) (equ vbe-dispi-index-y-offset 9) ;; It seems that VirtualBox only supports BGA up to #xb0c4. See ;; http://www.virtualbox.org/svn/vbox/trunk/src/VBox/Devices/Graphics/BIOS/vbe_display_api.txt (equ vbe-dispi-id2 #xb0c2) (equ vbe-dispi-id4 #xb0c4) (equ vbe-dispi-id5 #xb0c5) (equ vbe-dispi-bpp-32 #x20) (equ vbe-dispi-enabled 1) (equ vbe-dispi-disabled 0) ;;; Write index/data to one BGA register. ;;; Input: ;;; AL: index value ;;; BX: data value ;;; Output: None ;;; Modified registers: DX bga-write-register (mov dx vbe-dispi-ioport-index) (out dx al) (mov dx vbe-dispi-ioport-data) (mov ax bx) (out dx ax) (ret) ;;; Read BGA register. ;;; Input: ;;; AL: index value ;;; Output: in AX ;;; Modified registers: DX bga-read-register (mov dx vbe-dispi-ioport-index) (out dx al) (mov dx vbe-dispi-ioport-data) (in ax dx) (ret) ;;; Check whether BGA is available. ;;; Input: None ;;; Output: CF is set if BGA is unavailable. bga-available (clc) (mov al vbe-dispi-index-id) (call bga-read-register) (cmp ax vbe-dispi-id2) (jb no-bga) (ret) no-bga (stc) (ret) ;;; Set BGA mode. set-bga-mode (mov al vbe-dispi-index-enable) (mov bx vbe-dispi-disabled) (call bga-write-register) (mov al vbe-dispi-index-xres) (mov bx 800) (call bga-write-register) (mov al vbe-dispi-index-yres) (mov bx 600) (call bga-write-register) (mov al vbe-dispi-index-bpp) (mov bx vbe-dispi-bpp-32) (call bga-write-register) (mov al vbe-dispi-index-enable) (mov bx vbe-dispi-enabled) (call bga-write-register) (ret)))
2,617
Common Lisp
.lisp
88
25.193182
100
0.600476
whily/yalo
571
32
1
GPL-2.0
9/19/2024, 11:24:32 AM (Europe/Amsterdam)
1535810053fc6f1fd39c0ed5349ba26bc7627b091b675bfadbd769140121630f
202
[ 226163 ]
203
memory.lisp
whily_yalo/cc/memory.lisp
;;;; -*- Mode: Lisp -*- ;;;; Author: ;;;; Yujian Zhang <[email protected]> ;;;; Description: ;;;; Memory management. ;;;; License: ;;;; GNU General Public License v2 ;;;; http://www.gnu.org/licenses/gpl-2.0.html ;;;; Copyright (C) 2015 Yujian Zhang (in-package :cc) (defparameter *memory-16* `( ;;; http://wiki.osdev.org/Detecting_Memory_(x86) ;;; http://www.brokenthorn.com/Resources/OSDev17.html ;;; Use INT 0x15, EAX=#xe820 BIOS function to get memory map. ;;; Modified registers: all registers are trashed except ESI. get-memory-map ;; String "SMAP". (equ mm-smap #x0534D4150) (equ mm-entry-size 24) (equ mm-start-addr 0) ;; Offset for the end address. Note that it is the length field after ;; the BIOS call, but the value is replaced with end address by this function. (equ mm-end-addr 8) (equ mm-memory-type 16) (equ mm-entries-offset 2) ;; Stores Number of memory map entries. This is the linear address. ;; Corresponding semgnet:offset is in mm-count-physical-segment ;; and mm-count-physical-offset (equ mm-count-physical-addr #x80000) ;; The following is the pair of segment:offset (equ mm-count-physical-segment (ash mm-count-physical-addr -4)) (equ mm-count-physical-offset (logand mm-count-physical-addr #xffff)) ;; Maximum number of entries. (equ mm-entry-max 20) ;; Starting address of the memory map entries. This is the linear address. ;; Corresponding semgent and offset is mm-count-physical-segment, and ;; mm-entries-physical-offset. (equ mm-entries-physical-addr (+ mm-count-physical-addr mm-entries-offset)) (equ mm-entries-physical-offset (logand mm-entries-physical-addr #xffff)) (push es) (mov ax mm-count-physical-segment) (mov es ax) (xor ebx ebx) ; Set EBX to 0 to start (mov di mm-entries-physical-offset) (xor bp bp) (mov edx mm-smap) ; Place "SMAP" into edx (mov eax #xe820) (es mov dword (di 20) 1) ; Force a valid ACPI 3.x entry (mov ecx mm-entry-size) (int #x15) (jc .fail) ; CF is set if the BIO function is not supported. (mov edx mm-smap) ; Some BIOSes may trash this register. (cmp eax edx) ; On success, EAX must have been rest to "SMAP" (jne .fail) (test ebx ebx) ; EBX = 0 implies that the list contains only 1 entry. (je .fail) (jmp short .jump-in) .loop (mov eax #xe820) ; EAX, ECX get trashed on every int #x15 call. (es mov dword (di 20) 1) ; Force a valid ACPI 3.x entry (mov ecx mm-entry-size) (int #x15) (jc .done) ; CF means the end of list. (mov edx mm-smap) ; Repair potentially trashed register. .jump-in (jcxz .skip-entry) ; Skip and 0 length entry. (cmp cl 20) ; Got a 24 byte ACPI 3.x response? (jbe .no-text) (es test byte (di 20) 1) ; Test whether the "ignore this data" bit is clear or not. (je .skip-entry) .no-text (es mov ecx (di 8)) ; Get lower 32 bit of memory region length. (es or ecx (di 12)) ; "Or" it with upper 32 bit to test for zero. (jz .skip-entry) ;; Got a good entry. Modify 64 bit length field into end address. ;; Subtract 1 from length. (es dec dword (di 8)) (es sbb dword (di 12) 0) ;; Then add base. (es mov eax (di)) (es add (di 8) eax) (es mov eax (di 4)) (es adc (di 12) eax) (inc bp) ; Increase entry count (add di mm-entry-size) ; Move to next entry. .skip-entry (test ebx ebx) ; If EBX is reset to 0, the list is complete. (jne .loop) (cmp bp mm-entry-max) ; If the actual memory count exceeds the limit, ; Memory data will be trashed by page tables. (jae .fail) .done (es mov (mm-count-physical-offset) bp) (clc) ; Clear CF (since .done lable is entered after "jc" instruction). (pop es) (ret) .fail (mov si .mm-error-message) (call println-16) .panic (hlt) (jmp short .panic) .mm-error-message (db "ERROR: memory map cannot be detected." 0) )) (defparameter *memory-32* `( ;;; Memory type constants. (equ memory-usable 1) (equ memory-reserved 2) (equ memory-acpi-reclaimable 3) (equ memory-acpi-nvs 4) (equ memory-bad 5) ;;; Get the maximum physical memory size, in bytes. Return the result in (EDX, EAX), ;;; where EDX stores the upper 32 bits. ;;; This is based on memory map detected with get-memory-map. ;;; TODO: for 32 bit operation, we don't need to get memory size as virtual ;;; memory management will be done in 64 bit mode. For page setup, we only map the 1st 2 MB for kernel ;;; will be sufficient. Code this function in 64 bit mode will be much easier ;;; as we can easily handle 64 bit arithmetic in 64 bit mode. get-memory-size (push esi) (push ecx) (push ebx) (push ebp) (movzx ecx word (mm-count-physical-addr)) ; Number of entries to process (mov esi mm-entries-physical-addr) (xor edx edx) ; EDX:EAX store the maximum physical address. (xor eax eax) .start (mov ebp (esi mm-memory-type)) (cmp ebp memory-usable) ; TODO: consider ACPI reclaimable? (jnz .skip-entry) (mov ebp (esi 8)) ; Lower 32 bits. (mov ebx (esi 12)) ; Higher 32 bits. Now EBX:EBP store the current physical address. (cmp ebx edx) (jb .skip-entry) (ja .update) (cmp ebp eax) (jbe .skip-entry) .update (mov edx ebx) (mov eax ebp) .skip-entry (add esi mm-entry-size) (loop .start) .done (pop ebp) (pop ebx) (pop ecx) (pop esi) (ret) )) (defparameter *memory* `(;;; ==================== Start of Physical Memory Manager (PMM) ==================== (equ page-size-shift 21) ; Shift for 2 MB (equ mm-count-virtual-addr (+ kernel-virtual-base mm-count-physical-addr)) (equ mm-entries-virtual-addr (+ kernel-virtual-base mm-entries-physical-addr)) ;;; Function pmm-init: initilize the pmm. ;;; Input: None ;;; Output: None ;;; ;;; Algorithm: ;;; First we mark all page frames as free (set corresponding bit to 0). ;;; Then we goes through the memory map. ;;; For every memory entry unusable: ;;; For every page frame whose starting address <= end address of the memory entry: ;;; If the end address of the page frame >= the starting address of the memory entry: ;;; Mark the page frame as used (set the bit to 1). ,@(def-fun 'pmm-init nil `( ;; First initialize page-table-bitmap. (mov rdi page-table-bitmap-virtual-addr) (mov rsi page-table-max) (push rdi) ,@(call-function 'bitmap-init) (pop rdi) ;; The first three page tables are already used. Note that identity mapping tables ;; are available for reuse. (xor esi esi) ,@(call-function 'bitmap-set) (mov esi 1) ,@(call-function 'bitmap-set) (mov esi 2) ,@(call-function 'bitmap-set) ;; Now initialize page-frame-bitmap. (mov rsi (memory-size-virtual-addr)) (mov eax 1) (shl eax page-size-shift) (dec eax) (add rsi rax) (shr rsi page-size-shift) ; Get ceil(memory-size / (2 ^ page-size-shift)) (mov rdi page-frame-bitmap-virtual-addr) (push rdi) ,@(call-function 'bitmap-init) (pop rdi) ;; Now loop throught every unusable memory entry. (movzx ecx word (mm-count-virtual-addr)) ; Number of entries to process (mov rax mm-entries-virtual-addr) ; Use RAX to loop throught memory map entry. .memory-entry (mov edx (rax mm-memory-type)) (cmp edx memory-usable) ; TODO: consider ACPI reclaimable? (je .skip-entry) (mov r8 (rax mm-start-addr)) (mov r9 (rax mm-end-addr)) (xor r10d r10d) ; The index to the page frames. .page-frame (mov r11 r10) (shl r11 page-size-shift) ; Starting address of the page frame. (cmp r11 r9) ;; Skip the current and remaining page frames, as the memory entry cannot ;; overlap with them. (ja .skip-entry) (mov r11 r10) (inc r11) (shl r11 page-size-shift) ; End address of the page frame. (cmp r11 r8) (jb .next-page-frame) ;; Now the unusable memory entry overlaps with the page frame, so ;; we set it to used (bit is 1). (push rsi) (push rdx) (mov rsi r10) ,@(call-function 'bitmap-set) (pop rdx) (pop rsi) .next-page-frame (inc r10) (cmp r10 rsi) (jb .page-frame) .skip-entry (add rax mm-entry-size) (loop .memory-entry) )) ;;; Function pmm-alloc-page-frame: allocate one page frame. ;;; Input: None. ;;; Output: ;;; RAX: starting physical address of the page frame. ;;; 0 if out of memory. ,@(def-fun 'pmm-alloc-page-frame nil `( (mov rdi page-frame-bitmap-virtual-addr) ,@(call-function 'bitmap-scan) (mov rsi -1) (cmp rax rsi) (je .out-of-memory) (mov rsi rax) (push rax) ,@(call-function 'bitmap-set) (pop rax) (shl rax page-size-shift) (jmp short .done) .out-of-memory (xor eax eax) .done )) ;;; Function pmm-free-page-frame: free one page frame. ;;; Input: ;;; RDI: starting physical address of the page frame. ;;; Output: None. ,@(def-fun 'pmm-free-page-frame nil `( (mov rsi rdi) (shr rsi page-size-shift) (mov rdi page-frame-bitmap-virtual-addr) ,@(call-function 'bitmap-unset))) ;;; ===================== End of Physical Memory Manager (PMM) ===================== ))
10,840
Common Lisp
.lisp
268
33.641791
106
0.557091
whily/yalo
571
32
1
GPL-2.0
9/19/2024, 11:24:32 AM (Europe/Amsterdam)
344701436c571e2c5c284158c9c4d8de2839e5e4710e21b03cc6b092be828a80
203
[ 44631 ]
204
lap.lisp
whily_yalo/cc/lap.lisp
;;;; -*- Mode: Lisp -*- ;;;; Author: ;;;; Yujian Zhang <[email protected]> ;;;; Description: ;;;; Lisp Assembly Program. ;;;; References: ;;;; [1] AMD64 Architecture Programmer's Manual Volume 3: ;;;; General-Purpose and System Instructions ;;;; Publication No. 24594; Revision: 3.22 ;;;; [2] Intel 64 and IA-32 Architectures Software Developer's Manual ;;;; Volume 2, Instruction Set Reference, A-Z. June 2015 ;;;; License: ;;;; GNU General Public License v2 ;;;; http://www.gnu.org/licenses/gpl-2.0.html ;;;; Copyright (C) 2009-2015 Yujian Zhang (in-package :cc) ;;; CL code in this file will be reused by Ink bootstrapping, ;;; therefore only list data structure is used even though hash table ;;; might be better. (defun asm (listing) "One pass assembler. listing is in the form of LAP as described in https://github.com/whily/yalo/blob/master/doc/AssemblyX64.md Returns opcodes as a list of bytes. To implement the assembler in one pass, for each instruction, expressions are tried to be evaluated. If fails (e.g. due to unresolvable labels), ((length expr) ? ...) with ? filling up to length serve as placeholders. At the end of the pass, those placeholders are evaluated and replaced with actual values, with ? removed (? is inserted just to make the cursor moving correct)." (let (symtab code (origin 0) (length 0) (cursor 0) (bits 64) (addressing 'rel) label) (dolist (e listing) (if (listp e) (let* ((e* (cons (car e) (try-eval-values (normalize-local-labels (cdr e) label) cursor origin symtab))) (snippet (case (car e*) (align (let ((n (second e*))) (unless (member n '(4 8 16 32 64 128 256 512)) (error "asm: unsupported alignment ~A." n)) (repeat-list (mod (- n cursor) n) (list #x90)))) ; #x90 is NOP. (addressing (setf addressing (second e*)) nil) (bits (setf bits (second e*)) nil) (equ (push (cons (second e*) (eval (third e*))) symtab) nil) (org (setf origin (second e*) cursor origin) nil) (times (repeat-list (eval (second e*)) (encode (nthcdr 2 e*) cursor bits addressing))) (t (encode e* cursor bits addressing))))) (setf code (nconc code snippet)) (incf length (length snippet)) (incf cursor (length snippet))) ;; Labels (progn (unless (local-label? e) (setf label e)) (let ((nl (normalize-label e label))) (when (assoc nl symtab) (error "asm: duplicated label ~A." nl)) (push (cons nl cursor) symtab))))) (mapcan #'(lambda (c) (cond ((numberp c) (list c)) ((eq c '?) nil) ((listp c) (encode-bytes (eval-final c symtab) (first c))) (t (error "asm: wrong byte for final processing: ~A" c)))) code))) (defun pp-asm (listing) "Processing the list with asm, and pretty print the bytes with pp-hex." (pp-hex (asm listing))) (defun write-kernel (filename) "Output kernel (including bootloader) as an image file with filename." (write-image (asm *bootloader*) filename)) (defun write-image (bytes filename) "Write a list of bytes to the file with filename." (with-open-file (s filename :direction :output :element-type 'unsigned-byte :if-exists :supersede) (when s (dolist (b bytes) (write-byte b s))))) (defun read-image (filename) "Return a list of bytes contained in the file with filename." (with-open-file (s filename :element-type 'unsigned-byte) (when s (let (output) (loop for byte = (read-byte s nil) while byte do (push byte output)) (nreverse output))))) (defun pp-image (filename) "Pretty print the image file." (pp-hex (read-image filename))) (defparameter *prefix-mapping* ;; As in section 2.1.1 (Instruction Prefixes) of [2]. `((lock . #xf0) (repne . #xf2) (repnz .#xf2) (rep . #xf3) (repe . #xf3) (repz . #xf3) ;; Handle segment override prefix here for simplicity. (cs . #x2e) (ss . #x36) (ds . #x3e) (es . #x26) (fs . #x64) (gs . #x65) ) "Prefix mapping table.") (defun encode (e* cursor bits addressing) "Opcode encoding, including pseudo instructions like db/dw..., resb/resw..." (let ((e (if (and (eq (car e*) 'xchg) (member (second e*) '(ax eax rax))) (list (car e*) (third e*) (second e*)) e*))) (acond ((assoc* (car e) *prefix-mapping*) (cons it (encode (cdr e) (1+ cursor) bits addressing))) ((assoc* e (x86-64-syntax bits) :test #'equal) ;; Instructions with exact match, e.g. instructions without ;; operands (like nop, hlt), or special instructions like int 3. ;; copy-list is necessary since syntax table is LITERAL. (cond ((member (car it) '(o16 o32 a16 a32)) (append (size-prefix (car it) bits) (copy-list (cdr it)))) ((eq (car it) 'rex.w) (append (list (encode-rex 1 0 0 0)) (copy-list (cdr it)))) (t (copy-list it)))) ((assoc e (x86-64-syntax bits) :test #'(lambda (x y) (and (> (length y) 1) (eq (car x) (car y)) (or (and (member (elt x 1) '(al ax eax rax)) (> (length x) 2) (numberp (elt x 2)) (eq (second x) (second y))) (and (eq (car x) 'xchg) (member (third x) '(ax eax rax)) (eq (third x) (third y))))))) ;; Some registers are explicitly given as destination operand, ;; e.g. (add al imm8). (encode-complex e (canonical-type (car it)) (cdr it) cursor bits addressing)) ((assoc* e (x86-64-syntax bits) :test #'(lambda (x y) (and (member (car x) '(sal sar shl shr)) (> (length y) 2) (= (length x) (length y)) (eq (car x) (car y)) (eq (car (last x)) (car (last y))) (eq (operand-type (car (last x 2))) (car (last y 2))) (if (= (length x) 3) t (eq (second x) (second y))) (member (car (last x)) '(1 cl))))) ;; Special case for (shl/shr r/m8/16 1/cl). (encode-complex (butlast e) (butlast (instruction-type e)) it cursor bits addressing)) ((cc-instruction? e 'cmov) ; CMOVcc. (declare (ignore it)) (cc-encode e 'cmov cursor bits addressing)) ((cc-instruction? e 'j) ; Jcc. (declare (ignore it)) (cc-encode e 'j cursor bits addressing)) ((cc-instruction? e 'set) ; SETcc. (declare (ignore it)) (cc-encode e 'set cursor bits addressing)) (t (declare (ignore it)) (case (car e) ;; Pseudo instructions. ((db dw dd dq) (mapcan #'(lambda (v) (ecase (car e) (db (cond ((stringp v) (string->bytes v)) (t (try-encode-bytes v 1)))) (dw (try-encode-bytes v 2)) (dd (try-encode-bytes v 4)) (dq (try-encode-bytes v 8)))) (cdr e))) ((resb resw resd resq) (let ((n-bytes (ecase (car e) (resb 1) (resw 2) (resd 4) (resq 8)))) ;; Use 0 as unitialized data, as in NASM. (repeat-list (* (second e) n-bytes) (list 0)))) ;; Normal instructions. (t (match-n-encode e cursor bits addressing))))))) (defun match-n-encode (e cursor bits addressing &optional (cc-code 0)) "Match instruction and encode it." (multiple-value-bind (type opcode) (match-instruction e (instruction-type e) bits) (if (and (>= (length opcode) 2) (eq (second opcode) 'rex.w)) ;; Handle instructions like popcnt where rex.w is the 2nd element in opcode. (append (list (first opcode)) (encode-complex e type (cdr opcode) (1+ cursor) bits addressing cc-code)) (encode-complex e type opcode cursor bits addressing cc-code)))) (defun encode-complex (instruction type opcode cursor bits addressing &optional (cc-code 0)) "Encode instruction (with optional rex prefix). Other prefixes like lock are directly handled in encode()." (let* (rex-set ; Possibly containing a subset of {w r x b}. (dummy (when (eq (car opcode) 'rex.w) (push 'w rex-set))) (prefix (when (member (car opcode) '(o16 o32 a16 a32)) (size-prefix (car opcode) bits))) (opcode* (if (member (car opcode) '(rex.w o16 o32 a16 a32)) (cdr opcode) opcode)) (encoded-len (length prefix)) ; Tracking for (R)IP relative encoding. disp32 ; Pointer for RIP Relative Addressing. (remaining (mapcan #'(lambda (on) (let ((x (cond ((numberp on) (list on)) ((listp on) (ecase (car on) (+ (ecase (caddr on) (r (multiple-value-bind (regi rex) (reg->int (second instruction)) (when rex (if (eq rex 'p) (push 'p rex-set) (push 'b rex-set))) (list (+ (cadr on) regi)))) (cc (list (+ (cadr on) cc-code))))))) (t (ecase on ((ib iw id io) (try-encode-bytes (if (equal type '(mov r64 -imm32)) (third instruction) (instruction-value instruction type (on->in on))) (on-length on))) ((cb cw cd co) (try-encode-bytes `(- ,(instruction-value instruction type (on->in on)) ,(+ cursor encoded-len (on-length on))) (on-length on))) ((/0 /1 /2 /3 /4 /5 /6 /7 /r) (let* ((mem (instruction-value instruction type (find-r/m instruction type))) (mem* mem) (addressing* (if (and (listp mem) (> (length mem) 1) (member (car mem) '(abs rel))) ;; Explicit abs/rel override. (progn (setf mem* (cdr mem)) (car mem)) addressing))) (multiple-value-bind (mod-sib-disp rex-set*) (encode-r/m-sib-disp mem* (if (eq on '/r) (instruction-value instruction type (find-reg instruction type)) on) bits addressing*) (setf rex-set (append rex-set rex-set*)) (setf disp32 (mark-rip-relative mod-sib-disp bits)) mod-sib-disp)))))))) (incf encoded-len (length x)) x)) opcode*))) (declare (ignore dummy)) (when (and rex-set (/= bits 64)) (error "Instruction ~A only supported in 64-bit mode." instruction)) (when disp32 (process-rip-relative disp32 cursor encoded-len rex-set)) ;; REX prefix should precede immdiately the opcode, i.e. other ;; prefix should precede REX prefix (see section 2.2.1 (REX Prefixes) of [2]). (append prefix (if (null rex-set) nil (list (encode-rex (if (member 'w rex-set) 1 0) (if (member 'r rex-set) 1 0) (if (member 'x rex-set) 1 0) (if (member 'b rex-set) 1 0)))) remaining))) (defun mark-rip-relative (mod-sib-disp bits) "For RIP Relative Addressing, return the list pointing to the field disp32. Actual modification is done by process-rip-relative." (when (and (= bits 64) (rip-relative? (car mod-sib-disp))) (cdr mod-sib-disp))) (defun process-rip-relative (disp32 cursor encoded-len rex-set) "For RIP Relative Addressing, handle the encoding of disp32 (modify mod-sib-disp if needed)." (let* ((next-rip (+ cursor encoded-len (if rex-set 1 0))) (mem (if (numberp (first disp32)) ; TODO: handle in r/m-values-64 to avoid this case. (error "process-rip-relative(): RIP relative addressing cannot be used on absolute address.") (second (first disp32)))) (new-disp (try-encode-bytes `(- ,mem ,next-rip) 4))) ;; In-place replacement. (setf (first disp32) (first new-disp)) (setf (second disp32) (second new-disp)) (setf (third disp32) (third new-disp)) (setf (fourth disp32) (fourth new-disp)))) (defun size-prefix (op bits) "Handles operand/address-size override prefix o16/o32 and a16/a32. Returns nil if no prefix is needed, otherwise corresponding prefix #x66 or #x67." (let* ((s (str op)) (st (symb (subseq s 0 1))) (sbit (read-from-string (subseq s 1 3)))) (if (or (= sbit bits) (and (eq op 'o32) (member bits '(32 64)))) nil (list (ecase st (o #x66) (a #x67)))))) (defun find-r/m (instruction type) "Return the r/m contained in type." (aif (member* '(m r/m8 r/m16 r/m32 r/m64 r8 r16 r32 r64) type) it (error "No r/m operand in ~A~%!" instruction))) (defun find-reg (instruction type) "Return the reg contained in type." (aif (member* '(sreg cr0-cr7 r8 r16 r32 r64) type) it (error "No (s)reg operand in ~A~%" instruction))) (defun encode-r/m-sib-disp (r/m reg/opcode bits addressing) "Return 2 values: - Encode ModR/M, SIB byte (if any) and displacement (if any). - A list of (w r x b) if present." (let* (rex-set (r/o (case reg/opcode ((/0 /1 /2 /3 /4 /5 /6 /7) (- (char-code (elt (symbol-name reg/opcode) 1)) 48)) (t (case (operand-type reg/opcode) (sreg (sreg->int reg/opcode)) (cr0-cr7 (cr0-cr7->int reg/opcode)) (t (multiple-value-bind (regi rex) (reg->int reg/opcode) (when rex (push (ecase rex (p 'p) (e 'r)) rex-set)) regi))))))) (multiple-value-bind (mod rm sib disp disp-length rex-set*) (r/m-values r/m bits addressing) (values (append (list (encode-modr/m mod rm r/o)) (when sib (list sib)) (when disp (try-encode-bytes disp disp-length))) (append rex-set rex-set*))))) (defun r/m-values (r/m bits addressing) "Return values: mod, r/m for encoding, sib, disp, length of disp in bytes, and rex-set. Note 1. If sib is not needed, return nil. 2. If disp is not needed, return nil as disp and disp-length could be arbitrary." (ecase (operand-type r/m) ((r8 r16 r32 r64) (multiple-value-bind (regi rex) (reg->int r/m) (values #b11 regi nil nil 0 (if rex (list (ecase rex (p 'p) (e 'b))) nil)))) (m (ecase bits ;; FIXME: should be directly related to address mode. (16 (r/m-values-16 r/m)) (32 (r/m-values-32 r/m)) (64 (r/m-values-64 r/m addressing)))))) (defun r/m-values-16 (r/m) (if (equal r/m '(bp)) ; Special handling of (bp) (values 1 #b110 nil 0 1 nil) (let ((type (mapcar #'operand-type r/m))) (if (and (= (length r/m) 1) ; Special handling of (disp16) (member* '(imm8 imm16 label) type)) (values 0 #b110 nil (car r/m) 2 nil) (let* ((mod (cond ((member 'imm8 type) 1) ((member 'imm16 type) 2) (t 0))) (disp (ecase mod (1 (instruction-value r/m type 'imm8)) (2 (instruction-value r/m type 'imm16)) (0 nil))) (rm (cond ((and (member 'bx r/m) (member 'si r/m)) #b000) ((and (member 'bx r/m) (member 'di r/m)) #b001) ((and (member 'bp r/m) (member 'si r/m)) #b010) ((and (member 'bp r/m) (member 'di r/m)) #b011) ((member 'si r/m) #b100) ((member 'di r/m) #b101) ((member 'bp r/m) #b110) ((member 'bx r/m) #b111) (t (error "Incorrect memory addressing: ~A~%" r/m))))) (values mod rm nil disp mod nil)))))) (defun r/m-values-32 (r/m) (cond ((equal r/m '(ebp)) ; Special handling of (ebp) (values 1 #b101 nil 0 1 nil)) ((equal r/m '(esp)) ; Special handling of (esp) (values 0 #b100 (encode-sib 0 #b100 4) nil 0 nil)) (t (let ((type (mapcar #'operand-type r/m))) (cond ((and (= (length r/m) 1) ; Special handling of (disp32) (member* '(imm8 imm16 imm32 label) type)) (values 0 #b101 nil (car r/m) 4 nil)) ((and (= (length r/m) 2) (member 'esp r/m) (member 'imm8 type)) ;; Special handling of (esp + disp8) (values 1 #b100 (encode-sib 0 #b100 4) (instruction-value r/m type 'imm8) 1 nil)) ((and (= (length r/m) 2) (member 'esp r/m) (member* '(imm16 imm32) type)) ;; Special handling of (esp + disp32) (values 2 #b100 (encode-sib 0 #b100 4) (instruction-value r/m type (member* '(imm16 imm32) type)) 4 nil)) (t (let* ((mod (cond ((member 'imm8 type) 1) ((member* '(imm16 imm32) type) 2) (t 0))) (disp (ecase mod (1 (instruction-value r/m type 'imm8)) (2 (instruction-value r/m type (member* '(imm16 imm32) type))) (0 nil))) (disp-length (if (= mod 2) 4 mod)) (sib (cond ((some #'scaled-index? r/m) (let* ((si (find-if #'scaled-index? r/m)) (sis (str si)) (scale (floor (log (read-from-string (subseq sis 4 5)) 2))) (index (reg->int (symb (subseq sis 0 3)))) (base-reg (find-if #'r32? r/m)) (base (if base-reg (reg->int base-reg) 5))) (unless base-reg ;; Special case of (scaled-index + disp32) (setf mod 0 disp (instruction-value r/m type (member* '(imm8 imm16 imm32) type)) disp-length 4)) (encode-sib scale index base))) ((= (count-if #'r32? r/m) 2) (let* ((scale 0) (base (reg->int (find-if #'r32? r/m))) (index (reg->int (find-if #'r32? r/m :from-end t)))) (encode-sib scale index base))) (t nil))) (rm (if sib #b100 (reg->int (member* '(eax ecx edx ebx ebp esi edi esp ax cx dx bp bp si di sp) r/m))))) (values mod rm sib disp disp-length nil)))))))) (defun r/m-values-64 (r/m addressing) (cond ((equal r/m '(rbp)) ; Special handling of (rbp) (values 1 #b101 nil 0 1 nil)) ((equal r/m '(rsp)) ; Special handling of (rsp) (values 0 #b100 (encode-sib 0 #b100 4) nil 0 nil)) (t (let ((type (mapcar #'operand-type r/m))) (cond ((and (= (length r/m) 1) (member* '(imm8 imm16 imm32 label) type)) ;; Special handling of (disp32). In 64 bit mode, ;; RIP-Relative Addressing is used when mod=00 and r/m=101 ;; (Table 1-16 of [1]). For abslute encoding, use ;; (mod=00, r/m=100, with SIB byte). (ecase addressing (abs (values 0 #b100 (encode-sib 0 #b100 #b101) (car r/m) 4 nil)) ;; Not encoded yet. As we need to know the cursor and instruction length, ;; we will let higher level function (`encode-complex`) to actually encode ;; as it has more context e.g. the prefix to determine instruction length. (rel (values 0 #b101 nil (car r/m) 4 nil)))) ((and (= (length r/m) 2) (member 'rsp r/m) (member 'imm8 type)) ;; Special handling of (rsp + disp8) (values 1 #b100 (encode-sib 0 #b100 4) (instruction-value r/m type 'imm8) 1 nil)) ((and (= (length r/m) 2) (member 'rsp r/m) (member* '(imm16 imm32) type)) ;; Special handling of (rsp + disp32) (values 2 #b100 (encode-sib 0 #b100 4) (instruction-value r/m type (member* '(imm16 imm32) type)) 4 nil)) (t (let* ((mod (cond ((member 'imm8 type) 1) ((member* '(imm16 imm32) type) 2) (t 0))) (disp (ecase mod (1 (instruction-value r/m type 'imm8)) (2 (instruction-value r/m type (member* '(imm16 imm32) type))) (0 nil))) (disp-length (if (= mod 2) 4 mod)) (sib (cond ((some #'scaled-index? r/m) (let* ((si (find-if #'scaled-index? r/m)) (sis (str si)) (scale (floor (log (read-from-string (subseq sis 4 5)) 2))) (index (reg->int (symb (subseq sis 0 3)))) (base-reg (find-if #'r64? r/m)) (base (if base-reg (reg->int base-reg) 5))) (unless base-reg ;; Special case of (scaled-index + disp32) (setf mod 0 disp (instruction-value r/m type (member* '(imm8 imm16 imm32) type)) disp-length 4)) (encode-sib scale index base))) ((= (count-if #'r64? r/m) 2) (let* ((scale 0) (base (reg->int (find-if #'r64? r/m))) (index (reg->int (find-if #'r64? r/m :from-end t)))) (encode-sib scale index base))) (t nil))) (rm (if sib #b100 (reg->int (member* '(rax rcx rdx rbx rbp rsi rdi rsp r8 r9 r10 r11 r12 r13 r14 r15 eax ecx edx ebx ebp esi edi esp r8d r9d r10d r11d r12d r13d r14d r15d ax cx dx bx bp si di sp r8w r9w r10w r11w r12w r13w r14w r15w) r/m))))) (values mod rm sib disp disp-length nil)))))))) (defun try-encode-bytes (x length) "If x is evaluable, run encode-bytes. Otherwise return the placeholder list." (if (evaluable? x) (encode-bytes (eval x) length) (cons `(,length ,x) (repeat-element (1- length) '?)))) (defun encode-bytes (x length) "Encode byte, word, doubleword, quadword into bytes in little-endian. Length is the number of bytes to convert to. X is first converted from signed to unsigned." (ecase length ((1 2 4 8) (do* ((e (1- length) (1- e)) (y (signed->unsigned x length)) (r (floor y (expt 256 e)) (floor y (expt 256 e))) z) ((zerop e) (push (mod y 256) z) z) (decf y (* r (expt 256 e))) (push r z))))) (defun try-eval-values (ops cursor origin symtab) "Run lookup-value. For each element, evaluate it if possible." (mapcar #'(lambda (v) (let ((v* (lookup-value v cursor origin symtab))) (if (evaluable? v*) (eval v*) v*))) ops)) (defun evaluable? (e) "Returns T is expression e is evaluable." (cond ((atom e) (numberp e)) ((null e) t) ((atom (car e)) (and (member (car e) '(+ - ceiling)) (every #'evaluable? (cdr e)))) (t nil))) (defun eval-final (revisit symtab) "Final evaluation of the revisit." (car (try-eval-values (cdr revisit) -1 -1 symtab))) (defun on->in (on) "Maps opcode notation (e.g. ib, iw) to instruction notation (e.g. imm8)." (ecase on ((ib cb) 'imm8) ((iw cw) 'imm16) ((id cd) 'imm32) ((io co) 'imm64))) (defun on-length (on) "Return lengths (in terms of bytes) for opcode notation (e.g. ib, iw)." (ecase on ((ib cb) 1) ((iw cw) 2) ((id cd) 4) ((io co) 8))) (defun lookup-value (ops cursor origin symtab) "Replace special variables and labels with values if possible." (cond ((atom ops) (operand->value ops cursor origin symtab)) ((null ops) nil) ((atom (car ops)) (cons (car ops) (mapcar #'(lambda (co) (lookup-value co cursor origin symtab)) (cdr ops)))) (t (cons (lookup-value (car ops) cursor origin symtab) (lookup-value (cdr ops) cursor origin symtab))))) (defun operand->value (operand cursor origin symtab) "For labels, returns its value if possible. For special variables, returns its value. For all other stuff, just return it." (cond ((eq operand '$) cursor) ((eq operand '$$) origin) ((eq (operand-type operand) 'label) (aif (assoc* operand symtab) it operand)) (t operand))) (defun instruction-value (instruction type name) "Get the value (in instruction) corresponding to the name (in type)." (assoc* name (mapcar #'cons type instruction))) (defun match-instruction (instruction type bits) "Returns values of (type opcode). In the first run, when the type does not appear in syntax table, try to match immediate data with register length." ;; Special handling for (mov r64 imm32) if imm32 < 0. (if (and (eq (car instruction) 'mov) (= (length instruction) 3) (eq (second type) 'r64) (numberp (third instruction)) (<= (- (expt 2 31)) (third instruction) -1)) (values (list 'mov 'r64 'imm32) (list 'rex.w #xc7 '/0 'id)) (aif (assoc-x86-64-opcode type bits) (values (canonical-type (car it)) (copy-list (cdr it))) (error "match-instruction: unsupported instruction ~A" instruction)))) (defun canonical-type (type) "Return the canonical form of the type." (mapcar #'(lambda (x) (if (listp x) (car x) x)) type)) (defun assoc-x86-64-opcode (type bits) "Returns a associated opcode based on x86-64 syntax." (assoc type (x86-64-syntax bits) :test #'(lambda (x y) (every #'(lambda (a b) (if (listp b) (sub-type-list? a b) (sub-type? a b))) x y)))) (defun sub-type? (a b) "Returns T if `a` is a sub-type of `b`." (or (eq a b) (case a (imm8 (member b '(imm16 imm32 imm64))) (imm16 (member b '(imm32 imm64))) (imm32 (eq b 'imm64)) (r8 (eq b 'r/m8)) (r16 (eq b 'r/m16)) (r32 (eq b 'r/m32)) (r64 (eq b 'r/m64)) (m (member b '(r/m8 r/m16 r/m32 r/m64)))))) (defun sub-type-list? (a list) "Returns T if `a` is a sub-type of at least one element of `list`." (some #'(lambda (x) (sub-type? a x)) list)) (defun signed->unsigned (value length) "Change value from signed to unsigned." (if (>= value 0) value (ecase length ((1 2 4 8) (+ (expt 256 length) value))))) (defun encode-modr/m (mod r/m reg/opcode) "Encode ModR/M byte." (+ (* mod #b1000000) (* reg/opcode #b1000) r/m)) (defun rip-relative? (modr/m) "Returns T if ModR/M byte indicates RIP relative addressing." (= (logand modr/m #b11000111) #b00000101)) (defun encode-sib (scale index base) "Encode SIB byte." (+ (* scale #b1000000) (* index #b1000) base)) (defun encode-rex (w r x b) "Encode rex prefix." (+ #b01000000 (* w #b1000) (* r #b100) (* x #b10) b)) (defun instruction-type (instruction) "Returns the instruction type for encoding." (cons (car instruction) (mapcar #'operand-type (cdr instruction)))) (defun operand-type (operand) "Returns operand type." (cond ((numberp operand) (cond ((<= (- (expt 2 7)) operand (1- (expt 2 8))) 'imm8) ((<= (- (expt 2 15)) operand (1- (expt 2 16))) 'imm16) ((<= (- (expt 2 31)) operand (1- (expt 2 32))) 'imm32) ((<= (- (expt 2 63)) operand (1- (expt 2 64))) 'imm64) (t (error "Invalid operand: ~A" operand)))) ((listp operand) (case (car operand) ((+ -) 'imm) (t 'm))) (t (case operand ((al cl dl bl ah ch dh bh bpl spl dil sil r8l r9l r10l r11l r12l r13l r14l r15l) 'r8) ((ax cx dx bx sp bp si di r8w r9w r10w r11w r12w r13w r14w r15w) 'r16) ((eax ecx edx ebx esp ebp esi edi r8d r9d r10d r11d r12d r13d r14d r15d) 'r32) ((rax rcx rdx rbx rsp rbp rsi rdi r8 r9 r10 r11 r12 r13 r14 r15) 'r64) ((cs ds es ss fs gs) 'sreg) ((cr0 cr2 cr3 cr4) 'cr0-cr7) ((near short byte word dword qword) operand) (t 'label))))) (defun r32? (op) "Returns T if operand op is a 32-bit general purpose register." (eq (operand-type op) 'r32)) (defun r64? (op) "Returns T if operand op is a 64-bit general purpose register." (eq (operand-type op) 'r64)) (defun reg->int (reg) "Returns values of: - the integer representation for register when encoding ModR/M byte. - whether extension (e.g. rex.b) is needed: * nil: no REX extension * p: REX extension is present but no field (e.g. rex.b or rex.r) is used. Can be used to encode SIL, DIL, SPL, BPL. * e: REX extension is used and one field will be set." (ecase reg ((al ax eax rax mm0 xmm0) (values 0 nil)) ((cl cx ecx rcx mm1 xmm1) (values 1 nil)) ((dl dx edx rdx mm2 xmm2) (values 2 nil)) ((bl bx ebx rbx mm3 xmm3) (values 3 nil)) ((ah sp esp rsp mm4 xmm4) (values 4 nil)) ((ch bp ebp rbp mm5 xmm5) (values 5 nil)) ((dh si esi rsi mm6 xmm6) (values 6 nil)) ((bh di edi rdi mm7 xmm7) (values 7 nil)) (spl (values 4 'p)) (bpl (values 5 'p)) (sil (values 6 'p)) (dil (values 7 'p)) ((r8l r8w r8d r8) (values 0 'e)) ((r9l r9w r9d r9) (values 1 'e)) ((r10l r10w r10d r10) (values 2 'e)) ((r11l r11w r11d r11) (values 3 'e)) ((r12l r12w r12d r12) (values 4 'e)) ((r13l r13w r13d r13) (values 5 'e)) ((r14l r14w r14d r14) (values 6 'e)) ((r15l r15w r15d r15) (values 7 'e)))) (defun sreg->int (sreg) "Returns the integer representation for segment register when encoding ModR/M byte." (ecase sreg (es 0) (cs 1) (ss 2) (ds 3) (fs 4) (gs 5))) (defun cr0-cr7->int (cr0-cr7) "Returns the integer representation for control registers when encoding ModR/M byte." (ecase cr0-cr7 (cr0 0) (cr2 2) (cr3 3) (cr4 4))) (defun cc->int (cc) "Returns the integer representing conditional codes (cc) used by cmovcc, jcc, and setcc. Returns -1 if cc is not a valid value." (case cc (o 0) (no 1) ((b c nae) 2) ((ae nb nc) 3) ((e z) 4) ((ne nz) 5) ((be na) 6) ((a nbe) 7) (s 8) (ns 9) ((p pe) 10) ((np po) 11) ((l nge) 12) ((ge nl) 13) ((le ng) 14) ((g nle) 15) (t -1))) (defun cc-instruction? (e prefix) "Returns T if instruction e contains instruction code with prefix." (let* ((mnemonic (str (car e))) (prefix-s (str prefix)) (prefix-len (length prefix-s))) (and (>= (length mnemonic) (1+ prefix-len)) (string= (subseq mnemonic 0 prefix-len) prefix-s) (>= (cc->int (symb (subseq mnemonic prefix-len))) 0)))) (defun cc-encode (e prefix cursor bits addressing) "Encode instructions with conditional codes." (let* ((cc (symb (subseq (str (car e)) (length (str prefix))))) (cc-code (cc->int cc)) (e* (cons (symb prefix 'cc) (cdr e)))) (match-n-encode e* cursor bits addressing cc-code))) (defun string->bytes (s) (map 'list #'char-code s)) (defun local-label? (l) "Returns T is L is a local label (starting with period)." (and (symbolp l) (eq (elt (symbol-name l) 0) #\.))) (defun normalize-label (e label) "If e is a local label, prefix it with label. Otherwise, return as is." (if (local-label? e) (symb label e) e)) (defun normalize-local-labels (e label) "For all local labels in E, normalize it by prefixing it with current label." (cond ((null e) e) ((atom (car e)) (cons (normalize-label (car e) label) (normalize-local-labels (cdr e) label))) (t (cons (normalize-local-labels (car e) label) (normalize-local-labels (cdr e) label))))) (defun member* (options list) "Returns the first element of OPTIONS in list. NIL if none found." (dolist (o options) (when (member o list) (return o)))) (defun scaled-index? (v) "Returns T if v is a scaled index (e.g. eax*2)." ;; TODO: using regular expression when available. (let ((s (str v))) (and (= (length s) 5) (member (read-from-string (subseq s 4 5)) '(2 4 8)) (char= (elt s 3) #\*) (member (symb (subseq s 0 3)) '(eax ecx edx ebx ebp esi edi rax rcx rdx rbx rbp rsi rdi)))))
37,645
Common Lisp
.lisp
822
31.70438
117
0.477981
whily/yalo
571
32
1
GPL-2.0
9/19/2024, 11:24:32 AM (Europe/Amsterdam)
23b4adaacfe0df47a71ef2f64126d132549a69a65114f48b24aab79dd73085b6
204
[ 81393 ]
205
test-cc.lisp
whily_yalo/cc/test-cc.lisp
;;;; -*- Mode: Lisp -*- ;;;; Author: ;;;; Yujian Zhang <[email protected]> ;;;; Description: ;;;; Regression tests. Cross checked with NASM. ;;;; License: ;;;; GNU General Public License v2 ;;;; http://www.gnu.org/licenses/gpl-2.0.html ;;;; Copyright (C) 2009-2018 Yujian Zhang (in-package :cc) (defun arith-test-1 (mnemonic) "Return test codes for arithmetic operations: add/and/cmp/or/sub/xor." `((,mnemonic al 8) (,mnemonic ax 1000) (,mnemonic bl 3) (,mnemonic byte (msg) 4) (,mnemonic bx 1234) (,mnemonic word (msg) 5678) (,mnemonic cx 9) (,mnemonic word (msg) 12) (,mnemonic al bl) (,mnemonic (msg) ch) (,mnemonic cx bx) (,mnemonic (msg) dx) (,mnemonic ch (msg)) (,mnemonic dx (msg)))) (defun arith-test-2 (mnemonic) "Return test codes for arithmetic operations: div/mul/neg/not" `((,mnemonic ch) (,mnemonic byte (msg)) (,mnemonic di) (,mnemonic word (bp si 3)))) (defun shift-test (mnemonic) "Return test codes for shift operations: shl/shr." `((,mnemonic dh 1) (,mnemonic byte (msg) 1) (,mnemonic dh cl) (,mnemonic byte (msg) cl) (,mnemonic dh 5) (,mnemonic byte (msg) 5) (,mnemonic dx 1) (,mnemonic word (msg) 1) (,mnemonic dx cl) (,mnemonic word (msg) cl) (,mnemonic dx 5) (,mnemonic word (msg) 5))) (defparameter *arith-asm* `((bits 16) (org #x7c00) ,@(arith-test-1 'add) ,@(arith-test-1 'and) ,@(arith-test-1 'cmp) (dec bx) (dec eax) (dec dl) (dec byte (msg)) (dec word (bp si 3)) (dec dword (msg)) ,@(arith-test-2 'div) (inc bx) (inc eax) (inc dl) (inc byte (msg)) (inc word (bp si 3)) (inc dword (msg)) ,@(arith-test-2 'mul) ,@(arith-test-2 'neg) ,@(arith-test-2 'not) ,@(arith-test-1 'or) ,@(shift-test 'shl) ,@(shift-test 'shr) ,@(arith-test-1 'sub) (test al 8) (test ax 1000) (test bl 3) (test byte (msg) 4) (test bx 1234) (test (msg) 5678) (test al bl) (test (msg) ch) (test cx bx) (test (msg) dx) ,@(arith-test-1 'xor) (bits 32) (add ax 1000) (dec dx) (dec ebp) (inc dx) (inc ebp) (bits 64) (addressing abs) (adc rax #x12345) (add ebx 1000) (add rax #x10010203) ; TODO: use special encoding, as noted in x86-64-syntax.lisp. ;(add rax 10) (add rbx 267) (add r15 #x123456) (add r10d 3) (add sil 6) (add r9l 8) (add r10 rbx) (add rsi (rbx)) (dec di) (dec ecx) (dec r10) (div ebx) (inc di) (inc ecx) (inc r10) (mul dword (rbx)) (neg rcx) (not qword (rbx)) (sbb rbx rdx) (test rax 123456789) (test r12 11223344) (test qword (rdi) 9966) (test rdx rdi) (test (rdx) r9) msg (db "Hello World! ") endmsg) "Arithmetic instructions are tested separately.") (defparameter *arith-code* '(4 8 5 232 3 128 195 3 128 6 102 126 4 129 195 210 4 129 6 102 126 46 22 131 193 9 131 6 102 126 12 0 216 0 46 102 126 1 217 1 22 102 126 2 46 102 126 3 22 102 126 36 8 37 232 3 128 227 3 128 38 102 126 4 129 227 210 4 129 38 102 126 46 22 131 225 9 131 38 102 126 12 32 216 32 46 102 126 33 217 33 22 102 126 34 46 102 126 35 22 102 126 60 8 61 232 3 128 251 3 128 62 102 126 4 129 251 210 4 129 62 102 126 46 22 131 249 9 131 62 102 126 12 56 216 56 46 102 126 57 217 57 22 102 126 58 46 102 126 59 22 102 126 75 102 72 254 202 254 14 102 126 255 74 3 102 255 14 102 126 246 245 246 54 102 126 247 247 247 114 3 67 102 64 254 194 254 6 102 126 255 66 3 102 255 6 102 126 246 229 246 38 102 126 247 231 247 98 3 246 221 246 30 102 126 247 223 247 90 3 246 213 246 22 102 126 247 215 247 82 3 12 8 13 232 3 128 203 3 128 14 102 126 4 129 203 210 4 129 14 102 126 46 22 131 201 9 131 14 102 126 12 8 216 8 46 102 126 9 217 9 22 102 126 10 46 102 126 11 22 102 126 208 230 208 38 102 126 210 230 210 38 102 126 192 230 5 192 38 102 126 5 209 226 209 38 102 126 211 226 211 38 102 126 193 226 5 193 38 102 126 5 208 238 208 46 102 126 210 238 210 46 102 126 192 238 5 192 46 102 126 5 209 234 209 46 102 126 211 234 211 46 102 126 193 234 5 193 46 102 126 5 44 8 45 232 3 128 235 3 128 46 102 126 4 129 235 210 4 129 46 102 126 46 22 131 233 9 131 46 102 126 12 40 216 40 46 102 126 41 217 41 22 102 126 42 46 102 126 43 22 102 126 168 8 169 232 3 246 195 3 246 6 102 126 4 247 195 210 4 247 6 102 126 46 22 132 216 132 46 102 126 133 217 133 22 102 126 52 8 53 232 3 128 243 3 128 54 102 126 4 129 243 210 4 129 54 102 126 46 22 131 241 9 131 54 102 126 12 48 216 48 46 102 126 49 217 49 22 102 126 50 46 102 126 51 22 102 126 102 5 232 3 102 74 77 102 66 69 72 21 69 35 1 0 129 195 232 3 0 0 72 5 3 2 1 16 72 129 195 11 1 0 0 73 129 199 86 52 18 0 65 131 194 3 64 128 198 6 65 128 193 8 73 1 218 72 3 51 102 255 207 255 201 73 255 202 247 243 102 255 199 255 193 73 255 194 247 35 72 247 217 72 247 19 72 25 211 72 169 21 205 91 7 73 247 196 48 65 171 0 72 247 7 238 38 0 0 72 133 250 76 133 10 72 101 108 108 111 32 87 111 114 108 100 33 32)) (defparameter *misc-asm* '((bits 16) (org #x7c00) start (align 4) (bt edx 29) (align 4) (btc eax 28) (btr ebx 27) (bts ecx 26) (call msg) (clc) (cld) (cli) (hlt) (in al 3) (in ax 4) (in al dx) (in ax dx) (int 3) (int #x10) .loop (jcxz .loop) (je .loop) (jmp short .loop) (jmp near meta-msg) (lgdt (msg)) (lidt (msg)) (lldt dx) (lldt (msg)) (lodsb) (lodsw) (lodsd) (loop .loop) ;; Segment override prefix. (es mov bl (di)) (ds mov byte (si) #xff) (mov ah 9) ;; TODO: currently if we use AL in place of BL, generated code is not as efficient as that of NASM; ;; Will add more instructions e.g. mov al, moffset. (mov bl (msg)) (mov (msg) bh) (mov bx (- endmsg msg)) (mov ax cx) (mov (msg) bx) (mov cx (#x1c7b)) (mov byte (msg) 42) (mov word (msg) 123) (mov es bx) (mov ax cs) (mov cr0 eax) (mov eax cr0) (movzx ax (msg)) (movzx edx cx) (movzx eax byte (msg)) (movzx eax word (msg)) (nop) (out 3 al) (out 4 ax) (out dx al) (out dx ax) (push cx) (push edx) (push cs) (push ss) (push ds) (push es) (pushf) (pushfd) (pop dx) (pop ecx) (pop ss) (pop ds) (pop es) (popf) (popfd) (rdmsr) (rep movsb) (rep movsw) (rep movsd) (ret) (stc) (std) (sti) (stosb) (stosw) (stosd) (wrmsr) (bits 64) (addressing rel) (bsf ax bx) (bsf ecx edx) (bsf r10 (msg)) (bsr ax r8w) (bsr r10d r9d) (bsr rax r12) (bswap ebx) (bswap rax) (bswap r10) (bt edx 29) (bt edx ecx) (bt rdx 30) (bt rax rbx) (btc rax 29) (btr rbx 28) (bts rcx 27) (call msg) (cmova ax bx) (cmovc eax edx) (cmove rdx r10) (cmpxchg cl dl) (cmpxchg cx dx) (cmpxchg edi edx) (cmpxchg rcx r10) (cmpxchg8b (rbx)) (cmpxchg16b (rbx)) (invlpg (abs 0)) (iretq) (jb near msg) (jmp near rbx) (jmp near msg) (jmp near (msg)) (leave) (lgdt (msg)) (lidt (msg)) (lodsq) (mov eax #x1234) (mov rsp #x90000) (mov rax #x1122334455667788) (mov rcx (msg)) (mov rcx (abs msg)) (mov rdi (abs #xb8000)) (mov rbx rcx) (mov rax -1) (mov qword (msg) 1019) ;; Following two cases test that REX prefix should follow legacy prefixes. (mov ax r8w) (fs mov r9w (msg)) ; Not sure whether this case is useful or not. ;; Following case tests the case that no bit is set for REX prefix. (mov dil 19) (movsq) (movzx r10 al) (movzx eax byte (msg)) (movzx rdx word (msg)) (push r10) (pushfq) (pop rax) (popcnt r11 (msg)) (popfq) (sal ebx 1) (sar edx cl) (seta ah) (setz (msg)) (shl r10 6) (shr qword (msg) 8) (rep stosq) (syscall) (sysret) (xadd cl dl) (xadd cx dx) (xadd edi edx) (xadd rcx r10) (xchg ax bx) (xchg cx ax) (xchg eax ebx) (xchg ecx eax) (xchg rax rbx) (xchg rcx rax) ;; (xchg a b) is equivalent to NASM's xchg b, a. ;; They are semantically equivalent anyway. (xchg al cl) (xchg cx bx) (xchg edx ebx) (xchg r10 r15) ;; Put these short jump instructions here to avoid the very long jump. ;; TODO: check near version? (jecxz msg) (jrcxz msg) (equ hi 4) meta-msg (dw msg) (resb 4) msg (db "Hello World! ") endmsg (times 3 db 0) (dw #xaa55) (resw 3) (dd 123456 7891011) (resd 2) (dq 3372036854775808) (resq 1)) "Miscellaneous instructions.") (defparameter *misc-code* '(102 15 186 226 29 144 144 144 102 15 186 248 28 102 15 186 243 27 102 15 186 233 26 232 250 1 248 252 250 244 228 3 229 4 236 237 204 205 16 227 254 116 252 235 250 233 222 1 15 1 22 20 126 15 1 30 20 126 15 0 210 15 0 22 20 126 172 173 102 173 226 223 38 138 29 62 198 4 255 180 9 138 30 20 126 136 62 20 126 187 13 0 137 200 137 30 20 126 139 14 123 28 198 6 20 126 42 199 6 20 126 123 0 142 195 140 200 15 34 192 15 32 192 15 182 6 20 126 102 15 183 209 102 15 182 6 20 126 102 15 183 6 20 126 144 230 3 231 4 238 239 81 102 82 14 22 30 6 156 102 156 90 102 89 23 31 7 157 102 157 15 50 243 164 243 165 243 102 165 195 249 253 251 170 171 102 171 15 48 102 15 188 195 15 188 202 76 15 188 21 72 1 0 0 102 65 15 189 192 69 15 189 209 73 15 189 196 15 203 72 15 200 73 15 202 15 186 226 29 15 163 202 72 15 186 226 30 72 15 163 216 72 15 186 248 29 72 15 186 243 28 72 15 186 233 27 232 15 1 0 0 102 15 71 195 15 66 194 73 15 68 210 15 176 209 102 15 177 209 15 177 215 76 15 177 209 15 199 11 72 15 199 11 15 1 60 37 0 0 0 0 72 207 15 130 223 0 0 0 255 227 233 216 0 0 0 255 37 210 0 0 0 201 15 1 21 202 0 0 0 15 1 29 195 0 0 0 72 173 184 52 18 0 0 188 0 0 9 0 72 184 136 119 102 85 68 51 34 17 72 139 13 166 0 0 0 72 139 12 37 20 126 0 0 72 139 60 37 0 128 11 0 72 137 203 72 199 192 255 255 255 255 72 199 5 129 0 0 0 251 3 0 0 102 68 137 192 100 102 68 139 13 116 0 0 0 64 183 19 72 165 76 15 182 208 15 182 5 100 0 0 0 72 15 183 21 92 0 0 0 65 82 156 88 243 76 15 184 29 79 0 0 0 157 209 227 211 250 15 151 196 15 148 5 64 0 0 0 73 193 226 6 72 193 45 52 0 0 0 8 243 72 171 15 5 15 7 15 192 209 102 15 193 209 15 193 215 76 15 193 209 102 147 102 145 147 145 72 147 72 145 134 200 102 135 217 135 218 77 135 250 103 227 8 227 6 20 126 0 0 0 0 72 101 108 108 111 32 87 111 114 108 100 33 32 0 0 0 85 170 0 0 0 0 0 0 64 226 1 0 67 104 120 0 0 0 0 0 0 0 0 0 0 0 230 130 217 250 11 0 0 0 0 0 0 0 0 0)) (defparameter *address-asm* '((org #x7c00) (bits 16) (mov (bp) es) (mov (bx si) ds) (mov (bx di) es) (mov (bp si) ds) (mov (bp di) ss) (mov (si) ds) (mov (di) cs) (mov (32330) ds) (mov (msg) ds) (mov (bx) cs) (mov (bx si 1) ds) (mov (bx di 2) es) (mov (bp si 3) ds) (mov (bp di 4) ss) (mov (si 5) ds) (mov (di 6) cs) (mov (bp 7) ds) (mov (bx 8) cs) (mov ds (di)) (mov ds (bx si 1001)) (mov es (bx di 1002)) (mov ds (bp si 1003)) (mov ss (bp di 1004)) (mov ds (si 1005)) (mov es (di 1006)) (mov ds (bp 1007)) (mov es (bx 1008)) (bits 32) (mov (ebp) ebx) (mov (esp) ecx) (mov (123456) edx) (mov (eax) edx) (mov (ebp 36) ecx) (mov (edi 1234) edx) (mov (esi 123456) ecx) (mov (esp #x23) ebx) (mov (esp #x12345678) ecx) (mov (eax ebx) ecx) (mov (esi edi) edx) (mov (esi ebp) edx) ;; (mov (eax*2 3456) edx) ; NASM encodes as (eax eax 3456) (mov (eax*2 esi) edx) (mov (esi*2 ebp 123) edx) (mov (edi*2 ebx 8) ecx) (mov (ecx*4 ebp 123) edx) (mov (esi*4 edx 8) ecx) (mov (edx*8 ebp 123456) ebx) (mov (edi*8 ecx 8) edx) (bits 64) (mov (rbp) rbx) (mov (rsp) rcx) (mov (abs 123456) rdx) (mov (rax) rdx) (mov (rbp 36) rcx) (mov (rdi 1234) rdx) (mov (rsi 123456) rcx) (mov (rsp #x23) rbx) (mov (rsp #x12345678) rcx) (mov (rax rbx) rcx) (mov (rsi rdi) rdx) (mov (rsi rbp) rdx) ;; (mov (rax*2 3456) rdx) ; NASM encodes as (rax rax 3456) (mov (rax*2 rsi) rdx) (mov (rsi*2 rbp 123) rdx) (mov (rdi*2 rbx 8) rcx) (mov (rcx*4 rbp 123) rdx) (mov (rsi*4 rdx 8) rcx) (mov (rdx*8 rbp 123456) rbx) (mov (rdi*8 rcx 8) rdx) msg (db "Hello World! ") endmsg) "Test addressing modes.") (defparameter *address-code* '(140 70 0 140 24 140 1 140 26 140 19 140 28 140 13 140 30 74 126 140 30 5 125 140 15 140 88 1 140 65 2 140 90 3 140 83 4 140 92 5 140 77 6 140 94 7 140 79 8 142 29 142 152 233 3 142 129 234 3 142 154 235 3 142 147 236 3 142 156 237 3 142 133 238 3 142 158 239 3 142 135 240 3 137 93 0 137 12 36 137 21 64 226 1 0 137 16 137 77 36 137 151 210 4 0 0 137 142 64 226 1 0 137 92 36 35 137 140 36 120 86 52 18 137 12 24 137 20 62 137 20 46 137 20 70 137 84 117 123 137 76 123 8 137 84 141 123 137 76 178 8 137 156 213 64 226 1 0 137 84 249 8 72 137 93 0 72 137 12 36 72 137 20 37 64 226 1 0 72 137 16 72 137 77 36 72 137 151 210 4 0 0 72 137 142 64 226 1 0 72 137 92 36 35 72 137 140 36 120 86 52 18 72 137 12 24 72 137 20 62 72 137 20 46 72 137 20 70 72 137 84 117 123 72 137 76 123 8 72 137 84 141 123 72 137 76 178 8 72 137 156 213 64 226 1 0 72 137 84 249 8 72 101 108 108 111 32 87 111 114 108 100 33 32)) (defparameter *bootloader-code* '(180 3 205 16 184 1 19 187 15 0 185 15 0 189 20 124 205 16 235 254 72 101 108 108 111 32 87 111 114 108 100 33 32 13 10 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 85 170)) (deftest test-cc () (check (equal (asm *address-asm*) *address-code*) (equal (asm *arith-asm*) *arith-code*) (equal (asm *misc-asm*) *misc-code*)))
16,156
Common Lisp
.lisp
486
28.440329
103
0.552253
whily/yalo
571
32
1
GPL-2.0
9/19/2024, 11:24:32 AM (Europe/Amsterdam)
e67dee5fa895d6897c07c1dec6a20932351937e28a81c862b08ef7e05c578de9
205
[ 191715 ]
206
bochs.lisp
whily_yalo/cc/bochs.lisp
;;;; -*- Mode: Lisp -*- ;;;; Author: ;;;; Yujian Zhang <[email protected]> ;;;; Description: ;;;; BOCHS specific functions. ;;;; License: ;;;; GNU General Public License v2 ;;;; http://www.gnu.org/licenses/gpl-2.0.html ;;;; Copyright (C) 2018 Yujian Zhang (in-package :cc) (defparameter *bochs* `( (equ bochs-shutdown-port #x8900) ;;; Shutdown computer. ;;; Note that although computer is already shutdown after sending the special string, ;;; a function is still defined for simplicity. ;;; Input: None ;;; Output: Noneq ,@(def-fun 'bochs-shutdown nil `( .start (mov dx bochs-shutdown-port) (mov rsi shutdown-str) .loop (lodsb) (out dx al) (test al al) (jz .done) (jmp short .loop) .done)) shutdown-str (db "Shutdown" 0) ))
919
Common Lisp
.lisp
32
23.0625
89
0.556561
whily/yalo
571
32
1
GPL-2.0
9/19/2024, 11:24:32 AM (Europe/Amsterdam)
940b1a981b986e0877f2e0b5d5c02eadcf0d6530aae125d6a11ec4edaccf0c6b
206
[ 21930 ]
207
vga-text.lisp
whily_yalo/cc/vga-text.lisp
;;;; -*- Mode: Lisp -*- ;;;; Author: ;;;; Yujian Zhang <[email protected]> ;;;; Description: ;;;; VGA text mode functions. ;;;; BIOS interruptions are not used. ;;;; License: ;;;; GNU General Public License v2 ;;;; http://www.gnu.org/licenses/gpl-2.0.html ;;;; Copyright (C) 2009-2015 Yujian Zhang (in-package :cc) (defparameter *vga-text-constants* `( ;;; VGA text mode related constants. ;;; ASCII characters. (equ ascii-backspace #x08) (equ ascii-linefeed #x0a) (equ ascii-space #x20) )) (defparameter *vga-text-16* ;;; VGA text output code in 16 bit mode, based on http://wiki.osdev.org/Babystep4 ;;; We only implement minimal set of features in 16 bit mode as the main intention ;;; is only to print error messages. `( ;;; Initialize text mode. Call it before calling any text mode functions. init-text-mode-16 (xor ax ax) (mov ds ax) (mov ax #xb800) ; Text video memory (mov es ax) (call clear-16) (ret) ;;; Clear screen. clear-16 (movzx ax (text-rows-16)) (movzx dx (text-cols-16)) (mul dx) (movzx ecx ax) ; All screen to be cleared. (mov ax #x0f20) ; Black background, white foreground, space char. (mov di 0) (rep stosw) (ret) ;;; Function println-16. Write a string and start a new line. ;;; It is equivalent to calling print twice: first to print the string, ;;; and then print CR/LF. ;;; Input: ;;; DS:SI: points to the starting address of the 0 terminated string. ;;; Output: None ;;; Modified registers: same as putchar ;;; Global variables: same as putchar println-16 (call print-16) (call printlf-16) (ret) ;;; Function printlf-16. Print crlf only. ;;; Input: None ;;; Output: None ;;; Modified reisters: None ;;; Global variables: text-x-16, text-y-16 printlf-16 (add byte (text-y-16) 1) ; Down one row (mov byte (text-x-16) 0) ; Back to left (ret) do-char-16 (call putchar-16) ;;; Function print-16. Write string to screen. ;;; Input: ;;; DS:SI: points to the starting address of the 0 terminated string. ;;; Output: None ;;; Modified registers: same as putchar ;;; Global variables: same as putchar print-16 (lodsb) ; Load string char to AL (cmp al 0) ; 0 terminated string like C. (jne do-char-16) (ret) ;;; Function putchar-16. Writer character at cursor position. ;;; Input: ;;; AL: character to display ;;; Output: None ;;; Modified registers: AX, BX, CX, DX, DI ;;; Global variables: text-x-16, text-y-16, text-cols-16 putchar-16 (mov ah #xf) ; Attribute: white on black (mov cx ax) ; Save char/attribute (movzx ax (text-y-16)) (movzx dx (text-cols-16)) (shl dx 1) ; 2 bytes for one character (mul dx) (movzx bx (text-x-16)) (shl bx 1) (mov di 0) ; Start of video memory (add di ax) ; Add y offset (add di bx) ; Add x offset (mov ax cx) ; Restore char/attribute (stosw) ; Write char/atribute (add byte (text-x-16) 1) ; Advance to right (ret) text-rows-16 (db 25) ;; Number of rows in text mode. text-cols-16 (db 80) ;; Number of columns in text mode. text-x-16 (db 0) ;; Position x in text mode [0, text-cols-16) text-y-16 (db 0) ;; Position y in text mode [0, text-rows-16) )) (defparameter *vga-text* ;;; VGA text output in 64 bit mode. `( (equ vga-video-memory (+ kernel-virtual-base #xb8000)) ;; Blue background, white foreground, space char. (equ background-filling #x1f201f20) ;;; Clear screen. ,@(def-fun 'clear nil `( (movzx eax byte (text-rows)) (movzx edx byte (text-cols)) (mul edx) (shr eax 1) (mov ecx eax) ; All screen to be cleared. (mov eax background-filling) (mov rdi vga-video-memory) (rep stosd) (mov byte (text-x) 0) (mov byte (text-y) 0) ,@(call-function 'set-cursor))) ;;; Function println. Write a string and start a new line. ;;; It is equivalent to calling print twice: first to print the string, ;;; and then print CR/LF. ;;; Input: ;;; RSI: points to the starting address of the 0 terminated string. ;;; Output: None ;;; Modified registers: same as putchar ;;; Global variables: same as putchar ,@(def-fun 'println nil `( ,@(call-function 'print) ,@(call-function 'printlf))) ;;; Function printlf. Print crlf only. ;;; Input: None ;;; Output: None ;;; Modified registers: EAX ;;; Global variables: text-x, text-y ,@(def-fun 'printlf nil `( (inc byte (text-y)) ; Down one row (mov byte (text-x) 0) ; Back to left (mov al (text-y)) (cmp al (text-rows)) (jb .done) ,@(call-function 'scroll-up) .done ,@(call-function 'set-cursor))) ;;; Function print. Write string to screen. ;;; Input: ;;; RDI: points to the starting address of the 0 terminated string. ;;; Output: None ;;; Modified registers: same as putchar ;;; Global variables: same as putchar ,@(def-fun 'print nil `( (mov rsi rdi) .start (lodsb) ; Load string char to AL (cmp al 0) ; 0 terminated string like C. (je .done) (mov dil al) ,@(call-function 'putchar) (jmp short .start) .done )) ;;; Function putchar. Writer character at cursor position. ;;; Input: ;;; DIL: character to display ;;; Output: None ;;; Modified registers: RAX, RCX, RDX, RDI, R8, R9 ;;; Global variables: text-x, text-y, text-cols ,@(def-fun 'putchar nil `( (cmp dil ascii-linefeed) (je .next-line) (mov r8d #x1f00) ; Attribute: white on blue (mov r8l dil) ; Save char/attribute (movzx eax byte (text-y)) (movzx edx byte (text-cols)) (shl edx 1) ; 2 bytes for one character (mul edx) (movzx r9d byte (text-x)) (shl r9d 1) (mov rdi vga-video-memory) ; Start of video memory (add rdi rax) ; Add y offset (add rdi r9) ; Add x offset (mov ax r8w) ; Restore char/attribute (stosw) ; Write char/atribute (inc byte (text-x) 1) ; Advance to right (mov al (text-x)) (cmp al (text-cols)) (je .next-line) (jmp short .done) .next-line ,@(call-function 'printlf) .done ,@(call-function 'set-cursor))) ;;; Function scroll-up. Scroll the screen up one line. ;;; Input: None ;;; Output: None ;;; Modified registers: RAX, RCX, RDX, RDI, RSI ;;; Global variables: text-x, text-y, text-rows, text-cols ,@(def-fun 'scroll-up '(rbx) '( ;; Copy rows from (1 to text-rows - 1) to (0 to text-fows - 2) (movzx ebx byte (text-cols)) (movzx eax byte (text-rows)) (dec eax) ; Only copy text-rows - 1 lines. (mul ebx) (shr eax 1) ; 2 bytes per character, write 4 bytes with movsd (shl ebx 1) ; Number of bytes per line. (mov rdi vga-video-memory) (mov rsi rdi) (add rsi rbx) (mov ecx eax) (cld) ;; TODO: change to movsq (rep movsd) ;; Clear the last line. (mov eax background-filling) (shr ebx 2) ; As we're using stosd, divide by 4. (mov ecx ebx) (rep stosd) ;; Reset the y position to the last line. (dec byte (text-y)))) ;;; Function backspace-char. Remove one character before cursor, ;;; and move cursor one character back. ,@(def-fun 'backspace-char nil `( ;; If the cursor just follows prompt (e.g. REPL> ), then backspace ;; does nothing. (cmp byte (text-x) prompt-length) (jbe .done) ;; First go back one character and write a space. (dec byte (text-x)) (mov dil ascii-space) ,@(call-function 'putchar) ;; Go back once more and set cursor. (dec byte (text-x)) ,@(call-function 'set-cursor) .done )) ;;; Function set-cursor. Set VGA hardware cursor. ;;; Input: based on text-xy, text-y ;;; Output: None ;;; Modified registers: RAX, RCX, RDX, RDI ;;; Global variables: text-x, text-y, text-cols ;;; Based on http://www.brokenthorn.com/Resources/OSDev10.html (equ crt-index-reg #x3d4) (equ crt-data-reg #x3d5) (equ cursor-location-high #xe) (equ cursor-location-low #xf) ,@(def-fun 'set-cursor nil `( ;; Get current cursor position. Note that we only care about the ;; location, not the memory (as in putchar). So following equation ;; is used: location = text-x + text-y * text-cols (movzx eax byte (text-y)) (movzx edx byte (text-cols)) (mul edx) (movzx ecx byte (text-x)) (add ecx eax) ;; Set low byte index to vga register. (mov al cursor-location-low) (mov dx crt-index-reg) (out dx al) (mov al cl) (mov dx crt-data-reg) (out dx al) ;; Set high byte index to vga register. (mov al cursor-location-high) (mov dx crt-index-reg) (out dx al) (mov al ch) (mov dx crt-data-reg) (out dx al))) text-rows (db 25) ;; Number of rows in text mode. text-cols (db 80) ;; Number of columns in text mode. text-x (db 0) ;; Position x in text mode [0, text-cols) text-y (db 0) ;; Position y in text mode [0, text-rows) ))
10,711
Common Lisp
.lisp
284
30.426056
84
0.52974
whily/yalo
571
32
1
GPL-2.0
9/19/2024, 11:24:32 AM (Europe/Amsterdam)
5dcfcf02fff678f1151ae7c4f8024d4e0e9b29ace385e9fecee14cdc9f28687e
207
[ 229761 ]
208
config.lisp
whily_yalo/cc/config.lisp
;;;; -*- Mode: Lisp -*- ;;;; Author: ;;;; Yujian Zhang <[email protected]> ;;;; Description: ;;;; Configuration for the kernel. ;;;; License: ;;;; GNU General Public License v2 ;;;; http://www.gnu.org/licenses/gpl-2.0.html ;;;; Copyright (C) 2018 Yujian Zhang (in-package :cc) (defparameter *include-regression-test* nil "Whether to include regression tests in the kernel: - t: Include regression tests - nil: NOT include regression tests") (defun regression-container (forms) "Include the FORMS if *include-regression-test* is T" (when *include-regression-test* forms))
615
Common Lisp
.lisp
18
31.888889
55
0.685185
whily/yalo
571
32
1
GPL-2.0
9/19/2024, 11:24:32 AM (Europe/Amsterdam)
109aededb42db23d0212c0fbf13e09c63b1755568453dfab48401a1853610401
208
[ 325270 ]
209
a20.lisp
whily_yalo/cc/a20.lisp
;;;; -*- Mode: Lisp -*- ;;;; Author: ;;;; Yujian Zhang <[email protected]> ;;;; Description: ;;;; A20 address line related functions. ;;;; License: ;;;; GNU General Public License v2 ;;;; http://www.gnu.org/licenses/gpl-2.0.html ;;;; Copyright (C) 2015 Yujian Zhang (in-package :cc) (defparameter *a20* `( ;;; Enable A20 address line based on: ;;; http://www.independent-software.com/writing-your-own-toy-operating-system-enabling-the-a20-line/ ;;; Input: None ;;; Output: None ;;; Modified registers: AL, BL, CL enable-a20 (call check-a20) (cmp ax 0) (jne .done) ;; Enable A20 based on BIOS (mov ax #x2401) (int #x15) (call check-a20) (cmp ax 0) (jne .done) ;; Enable A20 based on keyboard controller. (mov al kbd-ctrl-cmd-disable-keyboard) (call kbd-ctrl-send-cmd-16) (mov al kbd-ctrl-cmd-read-output-port) (call kbd-ctrl-send-cmd-16) (call wait-kbd-out-buf-16) (in al kbd-encoder-buf) (mov cl al) ; Save AL (mov al kbd-ctrl-cmd-write-output-port) (call kbd-ctrl-send-cmd-16) (mov al cl) ; Restore AL (or al 2) ; Enable A20 by set bit 1 to 1. (call kbd-encoder-send-cmd-16) (mov al kbd-ctrl-cmd-enable-keyboard) (call kbd-ctrl-send-cmd-16) (call wait-kbd-in-buf-16) (call check-a20) (cmp ax 0) (jne .done) ;; Enable A20 based on fast gate method. (in al #x92) (or al 2) (out #x92 al) (call check-a20) (cmp ax 0) (jne .done) .fail (mov si .a20-error-message) (call println-16) .panic (hlt) (jmp short .panic) .a20-error-message (db "ERROR: A20 address line cannot be enabled." 0) .done (ret) ;;; Check whether A20 is enabled or not. ;;; Input: None ;;; Output: AX=1 if A20 is enabled; AX=0 otherwise. ;;; The function writes different values to two addresses: ;;; 0000:0500 and ffff:0510. If A20 is not enabled, the two ;;; addresses are equivalent due to wrap around. ;;; This functions restores registers and states modified in the call. check-a20 ;; Save flags and registers. (pushf) (push ds) (push es) (push di) (push si) ;; Set es:di = 0000:0500 (xor ax ax) (mov es ax) (mov di #x500) ;; Set ds:si = ffff:0510 (mov ax #xffff) (mov ds ax) (mov si #x510) ;; Save byte at es:di on stack. (es mov al (di)) (push ax) ;; Save byte at ds:si on stack. (ds mov al (si)) (push ax) (es mov byte (di), #x00) ; [es:di] = #x00 (ds mov byte (si), #xff) ; [ds:si] = #xff (es cmp byte (di), #xff) ; Check memory wrap around. ;; Restore byte at ds:si (pop ax) (ds mov (si) al) ;; Restore byte at es:di (pop ax) (es mov (di) al) (mov ax 0) (je .exit) ; If A20 is disabled, return 0. (mov ax 1) ; Else, return 1 .exit (pop si) (pop di) (pop es) (pop ds) (popf) (ret) ))
3,267
Common Lisp
.lisp
110
25.018182
106
0.542276
whily/yalo
571
32
1
GPL-2.0
9/19/2024, 11:24:32 AM (Europe/Amsterdam)
185200a4714a1dc2735735afb112ed1c009e07a9a80cc0c2b750b3b4c3d8c44a
209
[ 127876 ]
210
unit-test.lisp
whily_yalo/cc/unit-test.lisp
;;;; -*- Mode: Lisp -*- ;;;; Author: ;;;; Yujian Zhang <[email protected]> ;;;; Description: ;;;; Unit test, adapted from chapter 9 of Practical Common Lisp. ;;;; License: ;;;; GNU General Public License v2 ;;;; http://www.gnu.org/licenses/gpl-2.0.html ;;;; Copyright (C) 2009-2012 Yujian Zhang (in-package :cc) (defmacro with-gensyms ((&rest names) &body body) "Environment for a list of gensyms." `(let ,(loop for n in names collect `(,n (gensym))) ,@body)) (defvar *test-name* nil) (defmacro deftest (name parameters &body body) "Define a test function. Within a test function we can call other test functions or use 'check' to run individual test cases." `(defun ,name ,parameters (let ((*test-name* (list ',name))) ,@body))) (defmacro check (&body forms) "Run each expression in 'forms' as a test case." `(combine-results ,@(loop for f in forms collect `(report-result ,f ',f)))) (defmacro combine-results (&body forms) "Combine the results (as booleans) of evaluating 'forms' in order." (with-gensyms (result) `(let ((,result t)) ,@(loop for f in forms collect `(unless ,f (setf ,result nil))) ,result))) (defun report-result (result form) "Report the results of a single test case. Called by 'check'." (format t "~:[FAIL~;pass~] ~a: ~a~%" result (car *test-name*) form) result)
1,378
Common Lisp
.lisp
36
35.277778
69
0.659925
whily/yalo
571
32
1
GPL-2.0
9/19/2024, 11:24:32 AM (Europe/Amsterdam)
cf963ce93f7ea24d1e6860e976a559a9f562bdbc18c4315f87cc40a941b6cfef
210
[ 172410 ]
211
bootloader.lisp
whily_yalo/cc/bootloader.lisp
;;;; -*- Mode: Lisp -*- ;;;; Author: ;;;; Yujian Zhang <[email protected]> ;;;; Description: ;;;; Bootloader. ;;;; ;;;; Switch to 32 bit protected mode and 64 bit long mode is mainly based on ;;;; Section 14.8 (Long-Mode Initialization Example) of ;;;; [1] AMD64 Architecture Programmer's Manual Volume 2: System Programming. ;;;; Publication No. 24593; Revision: 3.25 ;;;; License: ;;;; GNU General Public License v2 ;;;; http://www.gnu.org/licenses/gpl-2.0.html ;;;; Copyright (C) 2009-2015 Yujian Zhang (in-package :cc) (defparameter *bootloader* `(;;;==================== 16 bit real mode ==================== (bits 16) (org #x7c00) ;; Setup segments and stack. (cli) (xor ax ax) (mov ds ax) (mov es ax) ;; From http://wiki.osdev.org/Memory_Map_(x86), ;; #x7e00 ~ #x7ffff is guaranteed to be available for use, therefore set ;; ss:sp = 7000:ff00 (mov ax #x7000) (mov ss ax) (mov sp #xff00) (sti) ;; Load other sectors from floppy disk. ;; AL: # of sectors (mov ax (+ #x200 (ceiling (+ (- kernel-before-relocation stage-2) (- kernel-virtual-end kernel-virtual-start)) 512))) (mov bx stage-2) ; ES:BX is destination (mov cx 2) ; CH: cylinder; CL: sector (xor dx dx) ; DH: head; DL: drive (int #x13) (jmp near stage-2) ;; Fill up to 510 bytes. (times (- 510 (- $ $$)) db 0) (dw #xaa55) ; Boot sector signature ;; Stage 2. stage-2 ;; Initialize text mode. (call init-text-mode-16) ;; Check whether BGA is available ;; The following two lines are disabled for now as BGA mode is not used currently. ;; If not disabled, error will be thrown on VirtualBox (however osdev.org actually says that ;; VirtualBox supports BGA: http://wiki.osdev.org/BGA) ;;(call bga-available) ;;(jc no-bga-error) ;; Set target screen mode. ;(call set-bga-mode) ;; Show all red. ;(mov ecx ,(/ 65536 4)) ;(mov eax #xa000) ;(mov es ax) ;(xor edi edi) ;(mov eax #xff0000) ; Red ;(cld) ;(rep stosd) ;; Check whether CPU supports Long Mode or not. (call check-cpu) (jc no-long-mode-error) ;; Enable A20 line. (call enable-a20) ;; Get memory map. (call get-memory-map) (jmp near switch-to-protected-mode) ;; A20 and keyboard related include from keyboard.lisp. ,@*keyboard-constants* ,@*keyboard-16* ,@*a20* ;; Memory map include from memory.lisp. ,@*memory-16* ;; Function check-cpu. Use CPUID to check if the process supports long mode. ;; From section 14.8 (Long-Mode Initialization Example) of [1]. ;; If long mode is supported, CF is cleared; otherwise CF is set. check-cpu (mov eax #x80000000) (cpuid) (cmp eax #x80000000) ; Whether any extended function > 0x800000000 is available? (jbe no-long-mode) (mov eax #x80000001) (cpuid) (bt edx 29) ; Test if long mode is supported. (jnc no-long-mode) (clc) (ret) no-long-mode (stc) (ret) no-long-mode-error (mov si no-long-mode-message) (call println-16) .panic (hlt) (jmp short .panic) no-long-mode-message (db "ERROR: CPU does not support long mode." 0) ;; Include content from vga-text.lisp. ,@*vga-text-16* ;;; Global Descriptor Table (GDT). ;;; 32 bit GDT entries are according to ;;; http://www.brokenthorn.com/Resources/OSDev8.html ;;; 64 bit GDT entries are according to section 14.8 ;;; (Long-Mode Initialization Example) of [1]. gdt ;; Null descriptor (dd 0) (dd 0) ;; 32 bit code descriptor. (equ code-selector-32 (- $ gdt)) (dw #xffff) ; Limit low (dw 0) ; Base low (db 0) ; Base middle (db #b10011010) ; Access (db #b11001111) ; Granularity (db 0) ; Base high ;; 32 bit data descriptor. (equ data-selector-32 (- $ gdt)) (dw #xffff) ; Limit low (dw 0) ; Base low (db 0) ; Base middle (db #b10010010) ; Access (db #b11001111) ; Granularity (db 0) ; Base high ;; 64 bit code descriptor. (equ code-selector-64 (- $ gdt)) (dw 0) ; Limit low (ingored) (dw 0) ; Base low (ingored) (db 0) ; Base middle (ingored) (db #b10011000) ; Access (db #b00100000) ; Granularity (db 0) ; Base high (ingored) ;; 64 bit data descriptor (read/write). (equ data-selector-64 (- $ gdt)) (dw 0) ; Limit low (ingored) (dw 0) ; Base low (ingored) (db 0) ; Base middle (ingored) (db #b10010000) ; Access (db #b00000000) ; Granularity (db 0) ; Base high (ingored) end-gdt pgdt (dw (- end-gdt gdt 1)) ; Limit (size of GDT) (dd gdt) ; Base of GDT (align 4) idt .length (dw 0) .base (dd 0) switch-to-protected-mode (cli) (lgdt (pgdt)) ; Load GDT ;; Enter protected mode by setting CR0.PE = 1. (mov eax #b11) (mov cr0 eax) ;; Far jump to turn on protected mode. The following code is equivalent to ;; (jmp far code-selector-32:protected-mode) (db #xea) ; Far jump (dw protected-mode) (dw code-selector-32) ;;;==================== 32 bit protected mode ==================== protected-mode (bits 32) ;; Setup registers. (mov ax data-selector-32) (mov ss ax) (mov esp #x90000) (mov ds ax) (mov es ax) switch-to-long-mode (call32 setup-paging) ;; Enable 64 bit page-translation-table entries by setting ;; CR4.PAE=1. Paging is not enabled until long mode is ;; enabled. (mov eax cr4) (bts eax 5) (mov cr4 eax) ;; Initialize 64-bit CR3 to point to the base of PML4 page table. ;; Note that PML4 table must be below 4 GB. (mov eax pml4-base) (mov cr3 eax) ;; Enable long mode (set EFER.LME = 1). (mov ecx #xc0000080) ; EFER MSR number. (rdmsr) ; Read EFER. (bts eax 8) ; Set LME = 1. (wrmsr) ; Write EFER. ;; Enable paging to activate long mode (set CR0.PG = 1). (mov eax cr0) ; Read CR0. (bts eax 31) ; Set PE = 1. (mov cr0 eax) ; Write CR0. ;; Jump from 32 bit compatibility mode to 64 bit code segment. ;; Far jump to turn on long mode. The following code is equivalent to ;; (jmp far code-selector-64:protected-mode) (db #x66) (db #xea) ; Far jump (dw long-mode) ; In [1], dd is used instead of dw. (dw code-selector-64) ,@*paging-32* ,@*memory-32* ,@*kernel*))
7,354
Common Lisp
.lisp
204
30.901961
96
0.534073
whily/yalo
571
32
1
GPL-2.0
9/19/2024, 11:24:32 AM (Europe/Amsterdam)
217195ab84b3cf9f7e77c00efbc2f9417c37be22a743aac8f76830e8a22e819b
211
[ 38883 ]
212
paging.lisp
whily_yalo/cc/paging.lisp
;;;; -*- Mode: Lisp -*- ;;;; Author: ;;;; Yujian Zhang <[email protected]> ;;;; Description: ;;;; Paging functions. ;;;; References: ;;;; [1] AMD64 Architecture Programmer's Manual Volume 2: System Programming. ;;;; Publication No. 24593; Revision: 3.25 ;;;; License: ;;;; GNU General Public License v2 ;;;; http://www.gnu.org/licenses/gpl-2.0.html ;;;; Copyright (C) 2015 Yujian Zhang (in-package :cc) (defparameter *paging-32* `( ;;; Technical details for 2 MB page translation can be found in ;;; section 5.3.4 (2-Mbyte Page Translation) of [1]. ;;; At the beginning, paging setup is based on ;;; http://wiki.osdev.rg/Entering_Long_Mode_Directly ;;; ;;; Setup two mappings: ;;; 1) Identity mapping for bottom 2 MB physical address. ;;; 2) Map ALL available physical memory to higher memory space ;;; starting from -2GB memory space below recursive mapping. As ;;; recursive mapping occupies 512 GB and starts from #xffffff8000000000, ;;; kernel starts from #xffffff7f80000000. ;;; Identity mapping will be removed after entering 64 bit mode ;;; by calling function unmap-lower-memory. ;;; ;;; Suppose PML4 points to address A (`pml4-base` below), then there are ;;; five 4 KB memory regions to be processed by this function (note that we put ;;; identity mapping after kernel mapping as identity mapping will be unmapped): ;;; A .. A + #x0fff: Page Map Level 4 ;;; A + #x1000 .. A + #x3fff: Page Directory Pointer Table for higher half mapping. ;;; A + #x2000 .. A + #x4fff: Page Directory Table for higher half mapping. ;;; A + #x3000 .. A + #x1fff: Page Directory Pointer Table for identity mapping. ;;; A + #x4000 .. A + #x2fff: Page Directory Table for identity mapping. setup-paging (equ pml4-base #x10000) (equ page-table-size 4096) ; Number of bytes occupied by a page table. ;; Page flags. (equ page-present (expt 2 0)) (equ page-writable (expt 2 1)) (equ page-user-accessible (expt 2 2)) (equ page-write-through (expt 2 3)) (equ page-cache-disable (expt 2 4)) (equ page-accessed (expt 2 5)) (equ page-dirty (expt 2 6)) (equ page-pde.ps (expt 2 7)) (equ page-global (expt 2 8)) (equ page-no-execuite (expt 2 63)) (equ page-table-flag (+ page-present page-writable)) (equ page-entry-flag (+ page-table-flag page-pde.ps)) ; In addition to above flags, set PDE.PS for 2 MB page. (equ kernel-virtual-base #xffffff7f80000000) ; Start virtual address for higher half kernel. ;; The position to store memory size. (equ memory-size-physical-addr (+ mm-entries-physical-addr (* mm-entry-max mm-entry-size))) (equ memory-size-virtual-addr (+ kernel-virtual-base memory-size-physical-addr)) ;; Maximum number of page tables. (equ page-table-end-next #x70000) (equ page-table-max (/ (- page-table-end-next pml4-base) page-table-size)) (equ page-table-bitmap-virtual-addr (+ memory-size-virtual-addr 8)) ; 8 byte to store memory size. ;; In the calculation below, first 8 for bitmap-offset, second 8 because 1 bytes contains 8 bits. (equ page-frame-bitmap-virtual-addr (+ page-table-bitmap-virtual-addr 8 (ceiling page-table-max 8))) (push edx) (push ecx) (push ebx) (push edi) ;; Firstly check the size of the kernel. When kernel is firstly loaded ;; (before relocated), the memory map of our code/data below 1 MB is like: ;; 0 - some BIOS stuff ;; - kernel (starting from #x7c00) ;; - page tables (starting from pml4-base) ;; - FREE ;; - stack ;; - memory map (starting from mm-count-physical-addr) ;; - memory size (starting from memory-size-physical-addr), page table bitmap ;; and page frame bitmap ;; - other BIOS stuff ;; If kernel size is too big, code about page tables will trash ;; the kernel. So the following check is needed. ;; TODO: we need to make sure that page tables do not run into the region for ;; stack and memory map. (mov edx kernel-physical-end) (cmp edx pml4-base) (jb .page-continue) ;; If code comes to this branch, increase pml4-base appropriately. .panic (hlt) (jmp short .panic) .page-continue (call32 get-memory-size) ;; Store the memory size. (mov ecx memory-size-physical-addr) (mov (ecx) eax) (mov (ecx 4) edx) ;; TODO. So far we only handle < 4GB memory. As memory size is in ;; EDX:EAX, we ignore the value in EDX for now. Use EDX to store ;; the memory size (< 4 GB). (mov edx eax) ;; Zero out the 5 * 4 kB buffer. (mov edi pml4-base) (mov ecx #x1400) (xor eax eax) (cld) (rep stosd) (mov edi pml4-base) ;; Build the Page Map Level 4. ;; First set entry the identity mapping. (mov eax edi) (add eax #x3000) ; Address of the Page Directory Pointer Table for identity mapping. (or eax page-table-flag) (mov (edi) eax) ;; Secondly set entry for higher half mapping. (sub eax #x2000) ; Address of the Page Directory Pointer Table for higher half mapping. (mov ebx 510) (mov (ebx*8 edi) eax) (mov eax 511) ; Now starts recursive mapping. (shl eax 3) (add eax edi) (mov (eax) eax) ;; Build the Page Directory Pointer Table for identity mapping. (mov eax edi) (add eax #x4000) ; Address of the Page Directory. (or eax page-table-flag) (mov (edi #x3000) eax) ;; Build the Page Directory Table for identity mapping. Just map 2 MB. (mov eax page-entry-flag) ; Effectively point EAX to address #x0. (mov (edi #x4000) eax) ;; Build the Page Directory Pointer Table for higher half mapping. (mov edi (+ pml4-base #x1000)) (mov eax edi) (add eax #x1000) ; Address of the Page Directory. (or eax page-table-flag) ;; TODO: we only map maximum 1 GB memory now. So we only handle the 2nd last entry here. (mov ebx 510) ; The second last entry in the 512 entry table. (mov (ebx*8 edi) eax) ;; Build the Page Directory Table for higher half mapping. (add edi #x1000) (mov eax page-entry-flag) ; Effectively point EAX to address #x0. .loop-page-directory-table (mov (edi) eax) (add eax #x200000) ; Increase 2 MB. (add edi 8) (cmp eax edx) ; Has all memory been mapped? (jb .loop-page-directory-table) (pop edi) (pop ebx) (pop ecx) (pop edx) (ret))) (defparameter *paging* `( ;;; Remove identity mapping of bottom 2 MB. ,@(def-fun 'unmap-lower-memory nil `( (mov rdi pml4-base) (mov qword (rdi) 0) (invlpg (abs 0)))) ;; Mask to get bits 12-51 from page table entry for the physical address of the frame. (equ page-frame-mask #x000ffffffffff000) ;;; Function pointed-frame. Returns page frame address (physical). ;;; Input: ;;; RDI: page table entry address (virtual) ;;; Output: ;;; RAX: page frame address. 0 if page table entry is invalid ;;; (e.g. not present) ,@(def-fun'pointed-frame nil `( (mov rax (rdi)) (test eax page-present) (je .not-present) (mov rsi page-frame-mask) (and rax rsi) (jmp short .done) .not-present (xor eax eax) .done)) ;;; Function page-directory-entry-set. Return a page directory entry (PDE) given ;;; the physical frame base address and flags ;;; Input: ;;; RDI: page frame base address (should be aligned at 2 MB boundary) and ;;; smaller than 2^52 (due to x86-64 architecture limitation) ;;; RSI: page flags ;;; Output: ;;; RAX: the page directory entry (PDE). ;;; Technical details for 2 MB PDE can be found in section 5.3.4 ;;; (2-Mbyte Page Translation) of [1], especially Figure 5-25. "2-Mbyte PDE - Long Mode" ,@(def-fun 'page-directory-entry-set nil `( (equ pde-physical-base-address-mask #xfff00000001fffff) (mov rdx pde-physical-base-address-mask) (test rdi rdx) (jne .panic) (or rdi rsi) (mov rax rdi) (jmp short .done) .invalid-physical-base-address .panic (hlt) (jmp short .panic) .done)) ))
9,011
Common Lisp
.lisp
203
38.689655
117
0.593832
whily/yalo
571
32
1
GPL-2.0
9/19/2024, 11:24:32 AM (Europe/Amsterdam)
329b5dc93970e7b2f5543916a12ea46641cb92f1bbd6dfab62da0d34adeb5621
212
[ 301045 ]
213
abi.lisp
whily_yalo/cc/abi.lisp
;;;; -*- Mode: Lisp -*- ;;;; Author: ;;;; Yujian Zhang <[email protected]> ;;;; Description: ;;;; x86-64 calling convention based on System V AMD64 ABI. ;;;; ;;;; Summary in ;;;; https://en.wikipedia.org/wiki/X86_calling_conventions#System_V_AMD64_ABI ;;;; Basically, the first 6 integer or pointer arguments are ;;;; passed in RDI, RSI, RDX, RCX, R8, and R9, and rest are pushed ;;;; on stack. Return values are stored in RAX, and RDX if needed. ;;;; If callees wants to use RBX, RBP, and R12-R15, it must ;;;; restore their original values before returning control to the ;;;; caller. All other registers must be saved by the caller if it ;;;; wishes to preserve their values. ;;;; ;;;; References: ;;;; [1] https://github.com/hjl-tools/x86-psABI/wiki/x86-64-psABI-1.0.pdf ;;;; License: ;;;; GNU General Public License v2 ;;;; http://www.gnu.org/licenses/gpl-2.0.html ;;;; Copyright (C) 2015-2018 Yujian Zhang (in-package :cc) (defun call-function (function-name &optional saved-registers) "Used by the caller. The function adds push and pops around function calling automatically. It is assumed that RSP is aligned on 16 byte boundary before calling. if the number of `saved-registers` is odd, one more push/pop is added to ensure that RSP is aligned on 16 byte boundaring before calling the function." (let ((saved-registers* (if (oddp (length saved-registers)) (push (car saved-registers) saved-registers) saved-registers))) `(,@(mapcar #'(lambda (reg) (list 'push reg)) saved-registers*) (call ,function-name) ,@(mapcar #'(lambda (reg) (list 'pop reg)) (reverse saved-registers*))))) (defun def-fun (function-name saved-registers body) "Define a function following System V ABI. * saved-registers: a set of registers to be preserved, a subset of (rbx rsp rbp r12 r13 r14 r15). TODO: automatically detect which registers to save. This function automatically detect whether the function is a leaf function (which does not call other functions) or not. For a non-leaf function, stack frames are saved via rbp; while such additional operation is not done for leaf functions. Note that 128 byte red zone is not used." (when (and saved-registers (notevery #'(lambda (x) (member x '(rbx rsp rbp r12 r13 r14 r15))) saved-registers)) (error "def-fun: trying to save registers not in set (rbx rsp rbp r12 r13 r14 r15).")) (let* ((leaf? (notany #'(lambda (x) (and (listp x) (eq (car x) 'call))) body)) (prologue (unless leaf? '((push rbp) (mov rbp rsp)))) (epilogue (unless leaf? '((leave)))) ) `(,function-name ,@prologue ,@(mapcar #'(lambda (reg) (list 'push reg)) saved-registers) ,@body ,@(mapcar #'(lambda (reg) (list 'pop reg)) (reverse saved-registers)) ,@epilogue (ret) ))) (deftest test-abi () (check (equal (call-function 'read '(r10)) '((push r10) (push r10) (call read) (pop r10) (pop r10))) (equal (call-function 'write '(r10 r11)) '((push r10) (push r11) (call write) (pop r11) (pop r10))) (equal (def-fun 'read '(r12) '((xor eax eax))) '(read (push r12) (xor eax eax) (pop r12) (ret))) (equal (def-fun 'write '(r12 r13) '((move rdi 42) (call universe))) '(write (push rbp) (mov rbp rsp) (push r12) (push r13) (move rdi 42) (call universe) (pop r13) (pop r12) (leave) (ret)))))
3,917
Common Lisp
.lisp
96
32.90625
97
0.582176
whily/yalo
571
32
1
GPL-2.0
9/19/2024, 11:24:32 AM (Europe/Amsterdam)
8e21f7a02ccbed3175e355736fb45a87205376ddb67ba06311e7456e19aa11e8
213
[ 455961 ]
214
bitmap.lisp
whily_yalo/cc/bitmap.lisp
;;;; -*- Mode: Lisp -*- ;;;; Author: ;;;; Yujian Zhang <[email protected]> ;;;; Description: ;;;; Bitmap functions. ;;;; License: ;;;; GNU General Public License v2 ;;;; http://www.gnu.org/licenses/gpl-2.0.html ;;;; Copyright (C) 2015 Yujian Zhang (in-package :cc) (defparameter *bitmap-prologue* `(;;; Bounds check. (cmp rsi (rdi)) (jb .continue) (mov rsi bitmap-overflow-message) ,@(call-function 'panic) .continue)) (defparameter *bitmap* `( ;;; Bitmap consists of a stream of bytes, representing a bit array. ;;; The first qword stores the size (in bits) of the bitmap. ;;; We assume the multiples of qwords are reserved to storet the bitmap. ;;; ;;; Typically functions have two input parameters: ;;; start-address: the starting address of the bitmap. ;;; bit-position: the bit position in the bit array, starting from 0. ;; The offset starting from which where actual bitmap is stored. (equ bitmap-offset 8) ;; Divide by 64 to get qword offset (equ bitmap-shift 6) ;; Mask to get the bit index within the qword. (equ bitmap-mask (1- (expt 2 bitmap-shift))) ;;; Function bitmap-init. Initialize the bitmap. ;;; Perform the following: ;;; 1) Set the size field. ;;; 2) Initialize all bits to 0. ;;; We assume multiples of qwords are reserved to store the bitmap. ;;; This has the benefit that we have sentinel element for bitmap-scan ;;; if the bitmap size is not the multiple of 64 (qword). ;;; Input: ;;; RDI: start-address, there is no requirement that it should be qword aligned. ;;; RSI: size in bits ,@(def-fun 'bitmap-init nil `( (mov (rdi) rsi) (add rdi bitmap-offset) (mov rcx rsi) (add rcx bitmap-mask) (shr rcx bitmap-shift) ; RCX now is: ceil(rsi / 64) (xor eax eax) (cld) (rep stosq))) ;;; Function bitmap-set. Set the bit (i.e. to 1). ;;; Input: ;;; RDI: start-address. ;;; RSI: bit-position. ,@(def-fun 'bitmap-set nil `( ,@*bitmap-prologue* (mov rdx rsi) ; RDX: qword offset (shr rdx bitmap-shift) (and esi bitmap-mask) (bts (rdx*8 rdi bitmap-offset) rsi))) ;;; Function bitmap-unset. Unset the bit (i.e. to 0). ;;; Input: ;;; RDI: start-address. ;;; RSI: bit-position. ,@(def-fun 'bitmap-unset nil `( ,@*bitmap-prologue* (mov rdx rsi) ; RDX: qword offset (shr rdx bitmap-shift) (and esi bitmap-mask) (btr (rdx*8 rdi bitmap-offset) rsi))) ;;; Function bitmap-test. Returns corresponding bit in RDX. ;;; Input: ;;; RDI: start-address. ;;; RSI: bit-position. ;;; Output: ;;; RAX: bit value ,@(def-fun 'bitmap-test nil `( ,@*bitmap-prologue* (xor eax eax) ; Prepare (mov ecx 1) ; returning results. (mov rdx rsi) ; RDX: qword offset (shr rdx bitmap-shift) (and esi bitmap-mask) (bt (rdx*8 rdi bitmap-offset) rsi) (cmovc rax rcx))) ;;; Function bitmap-scan. Returns the index of the 1st bit which is 0. ;;; If every bit is 1, return -1. ;;; Input: ;;; RDI: start-address ;;; Output: ;;; RAX: corresponding index ,@(def-fun 'bitmap-scan nil `( (mov rcx (rdi)) (add rcx bitmap-mask) ; Scan ceil((rdi) / 64) (shr rcx bitmap-shift) (xor edx edx) .start (mov r8 (rdx*8 rdi bitmap-offset)) (not r8) (bsf r9 r8) (jnz .scan-complete) ;; All zero means that the original qword contains all 1 (we use "NOT" instruction). (inc rdx) (loop .start) (jmp short .not-found) .scan-complete (mov rax rdx) (shl rax bitmap-shift) (add rax r9) ; RAX is now the index. (cmp rax (rdi)) (jb .done) .not-found (mov rax -1) .done )) ;;; Function bitmap-count-1. Returns the count of 1 in the bitmap. ;;; Input: ;;; RDI: start-address ;;; Output: ;;; RAX: count of 1. ,@(def-fun 'bitmap-count-1 nil `( (mov rcx (rdi)) (add rcx bitmap-mask) ; Scan ceil((rdi) / 64) (shr rcx bitmap-shift) (xor eax eax) ; RAX: count of 1 (xor edx edx) ; RDX: index to the qword element .start (popcnt r8 (rdx*8 rdi bitmap-offset)) (add rax r8) (inc rdx) (loop .start))) ;;; Function bitmap-count-0. Returns the count of 0 in the bitmap. ;;; Input: ;;; RDI: start-address ;;; Output: ;;; RAX: count of 0. ,@(def-fun 'bitmap-count-0 nil `( ,@(call-function 'bitmap-count-1) (neg rax) (add rax (rdi)))) ;;; Bitmap regression test. ,@(regression-container (def-fun 'bitmap-regression nil `( (equ bitmap-regression-addr #xffffffff80400000) (mov rdi bitmap-regression-addr) (mov rsi 100) ,@(call-function 'bitmap-init) (mov rdi bitmap-regression-addr) ,@(call-function 'bitmap-count-1) (cmp rax 0) (jne .error) ,@(call-function 'bitmap-count-0) (cmp rax 100) (jne .error) (mov rdi bitmap-regression-addr) (mov rsi 0) ,@(call-function 'bitmap-set) ,@(call-function 'bitmap-count-0) (cmp rax 99) (jne .error) (mov rsi 1) ,@(call-function 'bitmap-set) ,@(call-function 'bitmap-count-0) (cmp rax 98) (jne .error) ,@(call-function 'bitmap-scan) (cmp rax 2) (jne .error) (mov rax #xffffffffffffffff) (mov (rdi 8) rax) ,@(call-function 'bitmap-count-0) (cmp rax 36) (jne .error) ,@(call-function 'bitmap-scan) (cmp rax 64) (jne .error) (mov rsi 64) ,@(call-function 'bitmap-set) ,@(call-function 'bitmap-count-0) (cmp rax 35) (jne .error) ,@(call-function 'bitmap-scan) (cmp rax 65) (jne .error) (mov rsi 65) ,@(call-function 'bitmap-set) ,@(call-function 'bitmap-count-0) (cmp rax 34) (jne .error) ,@(call-function 'bitmap-scan) (cmp rax 66) (jne .error) (mov rsi 67) ,@(call-function 'bitmap-set) ,@(call-function 'bitmap-scan) (cmp rax 66) (jne .error) (mov rsi 64) ,@(call-function 'bitmap-unset) ,@(call-function 'bitmap-count-0) (cmp rax 34) (jne .error) ,@(call-function 'bitmap-scan) (cmp rax 64) (jne .error) (jmp short .done) .error (mov rdi bitmap-regression-error-message) ,@(call-function 'println) .done ))) bitmap-overflow-message (db "ERROR: bitmap index exceeds bounds." 0) bitmap-regression-error-message (db "Regression test fails for bitmap." 0) ))
8,070
Common Lisp
.lisp
222
27.004505
94
0.489087
whily/yalo
571
32
1
GPL-2.0
9/19/2024, 11:24:32 AM (Europe/Amsterdam)
b725b6c3952651470b2c16aae9b323d9a94c864c833ed2e4fa364eec93ca1ad7
214
[ 303353 ]
215
test.lisp
whily_yalo/cc/test.lisp
;;;; -*- Mode: Lisp -*- ;;;; Author: ;;;; Yujian Zhang <[email protected]> ;;;; Description: ;;;; Test suite. ;;;; License: ;;;; GNU General Public License v2 ;;;; http://www.gnu.org/licenses/gpl-2.0.html ;;;; Copyright (C) 2015 Yujian Zhang (in-package :cc) (deftest test () (combine-results (test-cc) (test-abi)))
349
Common Lisp
.lisp
14
23.071429
49
0.600601
whily/yalo
571
32
1
GPL-2.0
9/19/2024, 11:24:32 AM (Europe/Amsterdam)
d14c6a6f36717027077ea5df5f9ef4df375d51440ec5d07af86968e715e8935d
215
[ 332638 ]
216
cc.asd
whily_yalo/cc/cc.asd
;;;; -*- Mode: Lisp -*- ;;;; Author: ;;;; Yujian Zhang <[email protected]> ;;;; Description: ;;;; ASDF definition. ;;;; License: ;;;; GNU General Public License v2 ;;;; http://www.gnu.org/licenses/gpl-2.0.html (defpackage #:cc-system (:use #:cl #:asdf)) (in-package #:cc-system) (defsystem cc :description "Cross compiler for yalo." :serial t :components ((:file "package") (:file "util") (:file "unit-test") (:file "config") (:file "abi") (:file "bitmap") (:file "memory") (:file "paging") (:file "bga") (:file "vga-text") (:file "keyboard") (:file "a20") (:file "bochs") (:file "kernel") (:file "bootloader") (:file "x86-64-syntax") (:file "lap") (:file "nasm") (:file "test-cc") (:file "test")))
789
Common Lisp
.asd
35
19.571429
49
0.571809
whily/yalo
571
32
1
GPL-2.0
9/19/2024, 11:24:32 AM (Europe/Amsterdam)
608aa8c59d375a054a30491990cc613481913b09de158e8803b43aa9bc0e05e0
216
[ 442323 ]
217
lnasdf
whily_yalo/cc/lnasdf
#!/usr/bin/env bash # Create symbolic link of CC system for ASDF. mkdir -p ~/common-lisp ln -fs `pwd`\/cc.asd ~/common-lisp/cc.asd
132
Common Lisp
.asd
4
31.75
46
0.710938
whily/yalo
571
32
1
GPL-2.0
9/19/2024, 11:24:32 AM (Europe/Amsterdam)
951d080c48d1048c26a0d5e4dcb099d523bd0e089c992667ef4e4ab0fb861300
217
[ -1 ]
218
write-kernel-sbcl
whily_yalo/write-kernel-sbcl
#!/usr/bin/sbcl --script (require 'asdf) (asdf:oos 'asdf:load-op 'cc) (in-package :cc) (write-kernel "floppy.img")
116
Common Lisp
.cl
5
22
28
0.7
whily/yalo
571
32
1
GPL-2.0
9/19/2024, 11:24:32 AM (Europe/Amsterdam)
71e87a4d4168ecc4c3cc00633d6ef056063cf7c8f0ad875d952feda50a705a03
218
[ 225008 ]
221
debug-virtualbox
whily_yalo/debug-virtualbox
#!/usr/bin/env bash # Emulate with VirtualBox, enabling debug settings. VirtualBox --startvm yalo --debug
106
Common Lisp
.l
3
34.333333
51
0.786408
whily/yalo
571
32
1
GPL-2.0
9/19/2024, 11:24:32 AM (Europe/Amsterdam)
81bdce954e9306435c6a0e1473ee3cc484347b06fd52a9f8669aa4ea5875de26
221
[ -1 ]
240
AssemblyX64F.md
whily_yalo/doc/AssemblyX64F.md
x86-64 Instruction Set F ======================== [Assembly syntax](AssemblyX64.md) [A](AssemblyX64A.md) [B](AssemblyX64B.md) [C](AssemblyX64C.md) [D](AssemblyX64D.md) [E](AssemblyX64E.md) F [H](AssemblyX64H.md) [I](AssemblyX64I.md) [J](AssemblyX64J.md) [L](AssemblyX64L.md) [M](AssemblyX64M.md) [N](AssemblyX64N.md) [O](AssemblyX64O.md) [P](AssemblyX64P.md) [R](AssemblyX64R.md) [S](AssemblyX64S.md) [T](AssemblyX64T.md) [U](AssemblyX64U.md) [V](AssemblyX64V.md) [W](AssemblyX64W.md) [X](AssemblyX64X.md) Placeholder
520
Common Lisp
.l
11
46.090909
62
0.708087
whily/yalo
571
32
1
GPL-2.0
9/19/2024, 11:24:32 AM (Europe/Amsterdam)
73d25617c1be1b46fad86d8634d692c046c83e2d1e99505cfe16f57dda6ea971
240
[ -1 ]
241
AssemblyX64M.md
whily_yalo/doc/AssemblyX64M.md
x86-64 Instruction Set M ======================== [Assembly syntax](AssemblyX64.md) [A](AssemblyX64A.md) [B](AssemblyX64B.md) [C](AssemblyX64C.md) [D](AssemblyX64D.md) [E](AssemblyX64E.md) [F](AssemblyX64F.md) [H](AssemblyX64H.md) [I](AssemblyX64I.md) [J](AssemblyX64J.md) [L](AssemblyX64L.md) M [N](AssemblyX64N.md) [O](AssemblyX64O.md) [P](AssemblyX64P.md) [R](AssemblyX64R.md) [S](AssemblyX64S.md) [T](AssemblyX64T.md) [U](AssemblyX64U.md) [V](AssemblyX64V.md) [W](AssemblyX64W.md) [X](AssemblyX64X.md) ### mov: Move | Instruction | Opcode | | --------------- | -------------- | | mov r8 imm8 | B0+r ib | | mov r16 imm16 | o16 B8+r iw | | mov r32 imm32 | o32 B8+r id | | mov r64 imm64 | REX.W B8+r io | | mov r/m8 r8 | 88 /r | | mov r/m16 r16 | o16 89 /r | | mov r/m32 r32 | o32 89 /r | | mov r/m64 r64 | REX.W 89 /r | | mov r8 r/m8 | 8A /r | | mov r16 r/m16 | o16 8B /r | | mov r32 r/m32 | o32 8B /r | | mov r64 r/m64 | REX.W 8B /r | | mov r/m8 imm8 | C6 /0 ib | | mov r/m16 imm16 | o16 C7 /0 iw | | mov r/m32 imm32 | o32 C7 /0 id | | mov r/m64 imm32 | REX.W C7 /0 id | | mov sreg r/m16 | 8E /r | | mov r/m16 sreg | 8C /r | ### mov: Move to/from Control Registers | Instruction | Opcode | | --------------- | ------------ | | mov r32 cr0-cr7 | 0F 20 /r | | mov cr0-cr7 r32 | 0F 22 /r | ### movsb/movsw: Move Data from String to String | Instruction | Opcode | | ----------- | -------- | | movsb | A4 | | movsw | o16 A5 | | movsd | o32 A5 | | movsq | REX.W A5 | ### movzx: Move with Zero-Extend | Instruction | Opcode | | --------------- | -------------- | | movzx r16 r/m8 | o16 0F B6 /r | | movzx r32 r/m8 | o32 0F B6 /r | | movzx r64 r/m8 | REX.W 0F B6 /r | | movzx r32 r/m16 | o32 0F B7 /r | | movzx r64 r/m16 | REX.W 0F B7 /r | ### mul: Unsigned Multiply | Instruction | Opcode | | ----------- | ----------- | | mul r/m8 | F6 /4 | | mul r/m16 | o16 F7 /4 | | mul r/m32 | o32 F7 /4 | | mul r/m64 | REX.W F7 /4 |
2,161
Common Lisp
.l
58
36.068966
62
0.508126
whily/yalo
571
32
1
GPL-2.0
9/19/2024, 11:24:32 AM (Europe/Amsterdam)
9df949ed9e65abf746cbca14ddbc7664767654c5748f781574a8eded4d87f329
241
[ -1 ]
242
AssemblyX64T.md
whily_yalo/doc/AssemblyX64T.md
x86-64 Instruction Set T ======================== [Assembly syntax](AssemblyX64.md) [A](AssemblyX64A.md) [B](AssemblyX64B.md) [C](AssemblyX64C.md) [D](AssemblyX64D.md) [E](AssemblyX64E.md) [F](AssemblyX64F.md) [H](AssemblyX64H.md) [I](AssemblyX64I.md) [J](AssemblyX64J.md) [L](AssemblyX64L.md) [M](AssemblyX64M.md) [N](AssemblyX64N.md) [O](AssemblyX64O.md) [P](AssemblyX64P.md) [R](AssemblyX64R.md) [S](AssemblyX64S.md) T [U](AssemblyX64U.md) [V](AssemblyX64V.md) [W](AssemblyX64W.md) [X](AssemblyX64X.md) ### test: Logical Compare | Instruction | Opcode | | ---------------- | -------------- | | test al imm8 | A8 ib | | test ax imm16 | A9 iw | | test rax imm32 | REX.W A9 id | | test r/m8 imm8 | F6 /0 ib | | test r/m16 imm16 | F7 /0 iw | | test r/m32 imm32 | F7 /0 id | | test r/m64 imm32 | REX.W F7 /0 id | | test r/m8 r8 | 84 /r | | test r/m16 r16 | 85 /r | | test r/m32 r32 | 85 /r | | test r/m64 r64 | REX.W85 /r | After ANDing the two operands, flags SF, ZF, and PF are set according to the result. The destination operand is *not* modified.
1,158
Common Lisp
.l
26
43.384615
69
0.587766
whily/yalo
571
32
1
GPL-2.0
9/19/2024, 11:24:32 AM (Europe/Amsterdam)
5803df0033f766882c6ddf69fe8d32320f8e2e9884e38d224f666944edac2c84
242
[ -1 ]
243
AssemblyX64N.md
whily_yalo/doc/AssemblyX64N.md
x86-64 Instruction Set N ======================== [Assembly syntax](AssemblyX64.md) [A](AssemblyX64A.md) [B](AssemblyX64B.md) [C](AssemblyX64C.md) [D](AssemblyX64D.md) [E](AssemblyX64E.md) [F](AssemblyX64F.md) [H](AssemblyX64H.md) [I](AssemblyX64I.md) [J](AssemblyX64J.md) [L](AssemblyX64L.md) [M](AssemblyX64M.md) N [O](AssemblyX64O.md) [P](AssemblyX64P.md) [R](AssemblyX64R.md) [S](AssemblyX64S.md) [T](AssemblyX64T.md) [U](AssemblyX64U.md) [V](AssemblyX64V.md) [W](AssemblyX64W.md) [X](AssemblyX64X.md) ### neg: Two's Complement Negation | Instruction | Opcode | | ----------- | ----------- | | neg r/m8 | F6 /3 | | neg r/m16 | o16 F7 /3 | | neg r/m32 | o32 F7 /3 | | neg r/m64 | REX.W F7 /3 | Replaces the value of destination operand with its two's complement (-dest). ### nop: No Operation | Instruction | Opcode | | ----------- | ------ | | nop | 90 | ### not: One's Complement Negation | Instruction | Opcode | | ----------- | ----------- | | not r/m8 | F6 /2 | | not r/m16 | o16 F7 /2 | | not r/m32 | o32 F7 /2 | | not r/m64 | REX.W F7 /2 | Replaces the value of destination operand with its one's complement (bitwise NOT).
1,202
Common Lisp
.l
30
38.766667
82
0.596733
whily/yalo
571
32
1
GPL-2.0
9/19/2024, 11:24:32 AM (Europe/Amsterdam)
1af76a7d4b505ccf4d304d513ca76f5d8b60b6427c58187ca2e43c742723ad77
243
[ -1 ]
244
AssemblyX64S.md
whily_yalo/doc/AssemblyX64S.md
x86-64 Instruction Set S ======================== [Assembly syntax](AssemblyX64.md) [A](AssemblyX64A.md) [B](AssemblyX64B.md) [C](AssemblyX64C.md) [D](AssemblyX64D.md) [E](AssemblyX64E.md) [F](AssemblyX64F.md) [H](AssemblyX64H.md) [I](AssemblyX64I.md) [J](AssemblyX64J.md) [L](AssemblyX64L.md) [M](AssemblyX64M.md) [N](AssemblyX64N.md) [O](AssemblyX64O.md) [P](AssemblyX64P.md) [R](AssemblyX64R.md) S [T](AssemblyX64T.md) [U](AssemblyX64U.md) [V](AssemblyX64V.md) [W](AssemblyX64W.md) [X](AssemblyX64X.md) ### sbb: subtract with borrow Please refer to [x86-64 arithmetic instructions](AssemblyX64Arith.md) for details. ### sal/sar/shl/shr: Shift | Instruction | Opcode | | -------------- | ------------------ | | ins r/m8, 1 | D0 opcode | | ins r/m8, cl | D2 opcode | | ins r/m8, imm8 | C0 opcode ib | | ins r/m16 1 | o16 D1 opcode | | ins r/m16 cl | o16 D3 opcode | | ins r/m16 imm8 | o16 C1 opcode ib | | ins r/m32 1 | o32 D1 opcode | | ins r/m32 cl | o32 D3 opcode | | ins r/m32 imm8 | o32 C1 opcode ib | | ins r/m64 1 | REX.W D1 opcode | | ins r/m64 cl | REX.W D3 opcode | | ins r/m64 imm8 | REX.W C1 opcode ib | The opcodes are /4, /7, /4, 5 for sal, sar, shl, shr, respectively. Note that sal and shl perform the same operation. ### setcc: Set Byte on Condition | Instruction | Opcode | | ----------------- | --------------------- | | setcc r/m8 | 0F (+ 90 cc) /0 | Please refer [x86-64 conditional codes](AssemblyX64.md#conditional-codes) for details. ### stc: Set Carry Flag | Instruction | Opcode | | ----------- | ------ | | stc | F9 | ### std: Set Direction Flag | Instruction | Opcode | | ----------- | ------ | | std | FD | ### sti: Set Interrupt Flag | Instruction | Opcode | | ----------- | ------ | | sti | FB | ### stosb/stosw/stosd: Store String | Instruction | Opcode | | ----------- | -------- | | stosb | AA | | stosw | o16 AB | | stosd | o32 AB | | stosq | REX.W AB | ### sub: Sub Please refer to [x86-64 arithmetic instructions](AssemblyX64Arith.md) for details. ### syscall/sysret: (Return from) Fast System Call | Instruction | Opcode | | ----------- | ------ | | syscall | 0F 05 | | sysret | 0F 07 |
2,353
Common Lisp
.l
60
37.866667
86
0.560299
whily/yalo
571
32
1
GPL-2.0
9/19/2024, 11:24:32 AM (Europe/Amsterdam)
325da5a37712f2a5ba51185980d1f11d9416f84a85b29c52449c0ca480311d64
244
[ -1 ]
245
AssemblyX64J.md
whily_yalo/doc/AssemblyX64J.md
x86-64 Instruction Set J ======================== [Assembly syntax](AssemblyX64.md) [A](AssemblyX64A.md) [B](AssemblyX64B.md) [C](AssemblyX64C.md) [D](AssemblyX64D.md) [E](AssemblyX64E.md) [F](AssemblyX64F.md) [H](AssemblyX64H.md) [I](AssemblyX64I.md) J [L](AssemblyX64L.md) [M](AssemblyX64M.md) [N](AssemblyX64N.md) [O](AssemblyX64O.md) [P](AssemblyX64P.md) [R](AssemblyX64R.md) [S](AssemblyX64S.md) [T](AssemblyX64T.md) [U](AssemblyX64U.md) [V](AssemblyX64V.md) [W](AssemblyX64W.md) [X](AssemblyX64X.md) ### jcc: Conditional Branch | Instruction | Opcode | | -------------- | --------------- | | jcc imm | (+ 70 cc) cb | | jcc near imm | 0F (+ 80 cc) cd | | jcxz imm | a16 E3 cb | | jecxz imm | a32 E3 cb | | jrcxz imm | E3 cb | Please refer to [conditional codes](AssemblyX64.md) for details. ### jmp: Jump | Instruction | Opcode | | -------------- | -------- | | jmp short imm | EB cb | | jmp near imm | E9 cw (for 16/32 bits) | | jmp near imm | E9 cd (for 64 bit) | | jmp near r/m64 | FF /4 |
1,142
Common Lisp
.l
26
42.692308
64
0.547748
whily/yalo
571
32
1
GPL-2.0
9/19/2024, 11:24:32 AM (Europe/Amsterdam)
ae3f91bf8985c78f63afd940d509cb1ee1efacc2401cd61d5f420f90a5f87656
245
[ -1 ]
246
AssemblyX64H.md
whily_yalo/doc/AssemblyX64H.md
x86-64 Instruction Set H ======================== [Assembly syntax](AssemblyX64.md) [A](AssemblyX64A.md) [B](AssemblyX64B.md) [C](AssemblyX64C.md) [D](AssemblyX64D.md) [E](AssemblyX64E.md) [F](AssemblyX64F.md) H [I](AssemblyX64I.md) [J](AssemblyX64J.md) [L](AssemblyX64L.md) [M](AssemblyX64M.md) [N](AssemblyX64N.md) [O](AssemblyX64O.md) [P](AssemblyX64P.md) [R](AssemblyX64R.md) [S](AssemblyX64S.md) [T](AssemblyX64T.md) [U](AssemblyX64U.md) [V](AssemblyX64V.md) [W](AssemblyX64W.md) [X](AssemblyX64X.md) hlt: Halt --------- | Instruction | Opcode | | ----------- | ------ | | hlt | F4 |
604
Common Lisp
.l
15
39.066667
62
0.643345
whily/yalo
571
32
1
GPL-2.0
9/19/2024, 11:24:32 AM (Europe/Amsterdam)
fc1fa71d8a43f3af423b93620a1455688604240b058c68804bf70ea6ba86ce97
246
[ -1 ]
247
CrossCompilation.md
whily_yalo/doc/CrossCompilation.md
Cross Compilation ================= # Plan Below is the initial thinking on the plan to cross compile and bootstrap Yalo. ## Cross compile the minimal bootloader and Ink interpreter The milestone of this stage is to generate a minimal bootloader (OS is far away) which finally runs an Ink interpreter. * Input: a minimal version of Ink interpreter written in Ink * Cross compiling platform: x86-64 assembler and a minimal version of Ink compiler, both written in Common Lisp. The compiler may use some intermediate language (e.g. LLVM IR). ## Develop Ink compiler with Ink interpreter Once the minimal Ink interpreter is up, the main target is then to implement basic file system (ext2) support. The interpreter then is able to read/write Ink source files, which can then be put under version control via the interface between VM and host machine. The next milestone is to implement x86-64 assembler and a full fledged Ink compiler, both in Ink itself.
966
Common Lisp
.l
19
49.157895
70
0.795527
whily/yalo
571
32
1
GPL-2.0
9/19/2024, 11:24:32 AM (Europe/Amsterdam)
27d820ec1d1bceb207e9af3d24741d351f09b7881982ba96e03927e7e7ddc7f2
247
[ -1 ]
248
AssemblyX64P.md
whily_yalo/doc/AssemblyX64P.md
x86-64 Instruction Set P ======================== [Assembly syntax](AssemblyX64.md) [A](AssemblyX64A.md) [B](AssemblyX64B.md) [C](AssemblyX64C.md) [D](AssemblyX64D.md) [E](AssemblyX64E.md) [F](AssemblyX64F.md) [H](AssemblyX64H.md) [I](AssemblyX64I.md) [J](AssemblyX64J.md) [L](AssemblyX64L.md) [M](AssemblyX64M.md) [N](AssemblyX64N.md) [O](AssemblyX64O.md) P [R](AssemblyX64R.md) [S](AssemblyX64S.md) [T](AssemblyX64T.md) [U](AssemblyX64U.md) [V](AssemblyX64V.md) [W](AssemblyX64W.md) [X](AssemblyX64X.md) ### pop: Pop a Value from the Stack | Instruction | Opcode | | ----------- | -------- | | pop r16 | o16 58+r | | pop r32 | o32 58+r | | pop r64 | 58+r | | pop ss | 17 | | pop ds | 1F | | pop es | 07 | | popf | o16 9D | | popfd | o32 9D | | popfq | 9D | ### popcnt: Return the Count of the Number of Bits Set to 1 | Instruction | Opcode | | ---------------- | ----------------- | | popcnt r64 r/m64 | F3 REX.W 0F B8 /r | ### push: Push a Value Onto the Stack | Instruction | Opcode | | ----------- | -------- | | push r16 | o16 50+r | | push r32 | o32 50+r | | push r64 | 50+r | | push cs | 0E | | push ss | 16 | | push ds | 1E | | push es | 06 | | pushf | o16 9C | | pushfd | o32 9C | | pushfq | 9C |
1,391
Common Lisp
.l
39
34.487179
62
0.515242
whily/yalo
571
32
1
GPL-2.0
9/19/2024, 11:24:32 AM (Europe/Amsterdam)
6b73dc0af800371a0c9e01043f279b38989f9e9220afd37c23d81a48e119f0bd
248
[ -1 ]
249
AssemblyX64X.md
whily_yalo/doc/AssemblyX64X.md
x86-64 Instruction Set X ======================== [Assembly syntax](AssemblyX64.md) [A](AssemblyX64A.md) [B](AssemblyX64B.md) [C](AssemblyX64C.md) [D](AssemblyX64D.md) [E](AssemblyX64E.md) [F](AssemblyX64F.md) [H](AssemblyX64H.md) [I](AssemblyX64I.md) [J](AssemblyX64J.md) [L](AssemblyX64L.md) [M](AssemblyX64M.md) [N](AssemblyX64N.md) [O](AssemblyX64O.md) [P](AssemblyX64P.md) [R](AssemblyX64R.md) [S](AssemblyX64S.md) [T](AssemblyX64T.md) [U](AssemblyX64U.md) [V](AssemblyX64V.md) [W](AssemblyX64W.md) X ### xadd: Exchange and Add | Instruction | Opcode | | -------------- | -------------- | | xadd r/m8 r8 | 0F C0 /r | | xadd r/m16 r16 | o16 0F C1 /r | | xadd r/m32 r32 | o32 0F C1 /r | | xadd r/m64 r64 | REX.W 0F C1 /r | ### xchg: Exchange | Instruction | Opcode | | -------------- | ----------- | | xchg ax r16 | o16 90+r | | xchg r16 ax | o16 90+r | | xchg eax r32 | o32 90+r | | xchg r32 eax | o32 90+r | | xchg rax r64 | REX.W 90+r | | xchg r64 rax | REX.W 90+r | | xchg r/m8 r8 | 86 /r | | xchg r8 r/m8 | 86 /r | | xchg r/m16 r16 | o16 87 /r | | xchg r16 r/m16 | o16 87 /r | | xchg r/m32 r32 | o32 87 /r | | xchg r32 r/m32 | o32 87 /r | | xchg r/m64 r64 | REX.W 87 /r | | xchg r64 r/m64 | REX.W 87 /r | Note that when a memory operand is referenced, lock protocal is automatically implemented, regardless whether LOCK prefix is used or not. This may has impact on performance. ### xor: Logical Exclusive OR Please refer to [x86-64 arithmetic instructions](AssemblyX64Arith.md) for details.
1,591
Common Lisp
.l
39
39.589744
82
0.608808
whily/yalo
571
32
1
GPL-2.0
9/19/2024, 11:24:32 AM (Europe/Amsterdam)
b995552221861da1801648f4693f3100b6e1dc010f0bb4b9983bbfe7a0afca97
249
[ -1 ]
250
AssemblyX64O.md
whily_yalo/doc/AssemblyX64O.md
x86-64 Instruction Set O ======================== [Assembly syntax](AssemblyX64.md) [A](AssemblyX64A.md) [B](AssemblyX64B.md) [C](AssemblyX64C.md) [D](AssemblyX64D.md) [E](AssemblyX64E.md) [F](AssemblyX64F.md) [H](AssemblyX64H.md) [I](AssemblyX64I.md) [J](AssemblyX64J.md) [L](AssemblyX64L.md) [M](AssemblyX64M.md) [N](AssemblyX64N.md) O [P](AssemblyX64P.md) [R](AssemblyX64R.md) [S](AssemblyX64S.md) [T](AssemblyX64T.md) [U](AssemblyX64U.md) [V](AssemblyX64V.md) [W](AssemblyX64W.md) [X](AssemblyX64X.md) ### or: Logical Inclusive OR Please refer to [x86-64 arithmetic instructions](AssemblyX64Arith.md) for details. ### out: Output from Port | Instruction | Opcode | | ----------- | ------ | | out imm8 al | E6 ib | | out imm8 ax | E7 ib | | out dx al | EE | | out dx ax | EF |
799
Common Lisp
.l
19
40.789474
82
0.663226
whily/yalo
571
32
1
GPL-2.0
9/19/2024, 11:24:32 AM (Europe/Amsterdam)
f88ca5e27462317a3a42d9989b0414a2bc675e5685ecd6a23031faafee82c4e8
250
[ -1 ]
251
AssemblyX64I.md
whily_yalo/doc/AssemblyX64I.md
x86-64 Instruction Set I ======================== [Assembly syntax](AssemblyX64.md) [A](AssemblyX64A.md) [B](AssemblyX64B.md) [C](AssemblyX64C.md) [D](AssemblyX64D.md) [E](AssemblyX64E.md) [F](AssemblyX64F.md) [H](AssemblyX64H.md) I [J](AssemblyX64J.md) [L](AssemblyX64L.md) [M](AssemblyX64M.md) [N](AssemblyX64N.md) [O](AssemblyX64O.md) [P](AssemblyX64P.md) [R](AssemblyX64R.md) [S](AssemblyX64S.md) [T](AssemblyX64T.md) [U](AssemblyX64U.md) [V](AssemblyX64V.md) [W](AssemblyX64W.md) [X](AssemblyX64X.md) ### in: Input from Port | Instruction | Opcode | | ----------- | ------ | | in al imm8 | E4 ib | | in ax imm8 | E5 ib | | in al dx | EC | | in ax dx | ED | ### inc: Increment by 1 | Instruction | Opcode | | ----------- | ----------- | | inc r/m8 | FE /0 | | inc r/m16 | o16 FF /0 | | inc r/m32 | o32 FF /0 | | inc r/m64 | REX.W FF /0 | | inc r16 | o16 40+r | | inc r32 | o32 40+r | ### int: Call Interrupt Procedure | Instruction | Opcode | | ----------- | ------ | | int 3 | CC | | int imm8 | CD ib | ### invlpg: Invalidate TLB entries | Instruction | Opcode | | ----------- | -------- | | invlpg m | 0F 01 /7 | ### iretq: Interrupt Return | Instruction | Opcode | | ----------- | -------- | | iretq | REX.W CF |
1,314
Common Lisp
.l
39
32.410256
62
0.543513
whily/yalo
571
32
1
GPL-2.0
9/19/2024, 11:24:32 AM (Europe/Amsterdam)
4ab4b2b198f5aea4fcdf8c5e9adbf111400a07941563dcf7ac6ff2574c677887
251
[ -1 ]
252
AssemblyX64Bit.md
whily_yalo/doc/AssemblyX64Bit.md
x86-64 Bit Instruction ============================= [Assembly syntax](AssemblyX64.md) [A](AssemblyX64B.md) [B](AssemblyX64B.md) [C](AssemblyX64C.md) [D](AssemblyX64D.md) [E](AssemblyX64E.md) [F](AssemblyX64F.md) [H](AssemblyX64H.md) [I](AssemblyX64I.md) [J](AssemblyX64J.md) [L](AssemblyX64L.md) [M](AssemblyX64M.md) [N](AssemblyX64N.md) [O](AssemblyX64O.md) [P](AssemblyX64P.md) [R](AssemblyX64R.md) [S](AssemblyX64S.md) [T](AssemblyX64T.md) [U](AssemblyX64U.md) [V](AssemblyX64V.md) [W](AssemblyX64W.md) [X](AssemblyX64X.md) There are 4 bit instructions which have similar formats of instructions. They are discussed together here. The instructions are: * bt: bit test * btc: bit test and complement * btr: bit test and reset * bts: bit test and set The format of the instructions are given below. | Instruction | Opcode | | -------------- | ----------------------- | | ins r/m16 r16 | 0F (+ base A3) /r | | ins r/m32 r32 | 0F (+ base A3) /r | | ins r/m32 r32 | 0F (+ base A3) /r | | ins r/m16 imm8 | 0F BA opcode ib | | ins r/m32 imm8 | 0F BA opcode ib | | ins r/m64 imm8 | REX.W 0F BA opcode ib | Base and opcode in above table are given below for each instruction. | Instruction | Base (hexadecimal) | Opcode | | ----------- | ------------------ | ------ | | bt | 0 | /4 | | btc | 18 | /7 | | btr | 10 | /6 | | bts | 8 | /5 |
1,514
Common Lisp
.l
33
44.666667
68
0.562415
whily/yalo
571
32
1
GPL-2.0
9/19/2024, 11:24:32 AM (Europe/Amsterdam)
3a7ff5ca01fcdc86e17c3885a6fbe06c9fe53ee6e98a2e55dab0ce28cde3fab0
252
[ -1 ]
253
AssemblyX64W.md
whily_yalo/doc/AssemblyX64W.md
x86-64 Instruction Set W ======================== [Assembly syntax](AssemblyX64.md) [A](AssemblyX64A.md) [B](AssemblyX64B.md) [C](AssemblyX64C.md) [D](AssemblyX64D.md) [E](AssemblyX64E.md) [F](AssemblyX64F.md) [H](AssemblyX64H.md) [I](AssemblyX64I.md) [J](AssemblyX64J.md) [L](AssemblyX64L.md) [M](AssemblyX64M.md) [N](AssemblyX64N.md) [O](AssemblyX64O.md) [P](AssemblyX64P.md) [R](AssemblyX64R.md) [S](AssemblyX64S.md) [T](AssemblyX64T.md) [U](AssemblyX64U.md) [V](AssemblyX64V.md) W [X](AssemblyX64X.md) ### wrmsr: Write to Model Specific Register | Instruction | Opcode | | ----------- | ------ | | wrmsr | 0F 30 |
628
Common Lisp
.l
14
43.642857
62
0.666121
whily/yalo
571
32
1
GPL-2.0
9/19/2024, 11:24:32 AM (Europe/Amsterdam)
3b04aa3091b2f5fa69bb230e1c629410234ee01e9568a7737f3525d237c8d484
253
[ -1 ]
254
AssemblyX64C.md
whily_yalo/doc/AssemblyX64C.md
x86-64 Instruction Set C ======================== [Assembly syntax](AssemblyX64.md) [A](AssemblyX64A.md) [B](AssemblyX64B.md) C [D](AssemblyX64D.md) [E](AssemblyX64E.md) [F](AssemblyX64F.md) [H](AssemblyX64H.md) [I](AssemblyX64I.md) [J](AssemblyX64J.md) [L](AssemblyX64L.md) [M](AssemblyX64M.md) [N](AssemblyX64N.md) [O](AssemblyX64O.md) [P](AssemblyX64P.md) [R](AssemblyX64R.md) [S](AssemblyX64S.md) [T](AssemblyX64T.md) [U](AssemblyX64U.md) [V](AssemblyX64V.md) [W](AssemblyX64W.md) [X](AssemblyX64X.md) ### call: Call Procedure | Instruction | Opcode | | ----------- | ---------- | | call imm16 | o16 E8 cw | | call imm32 | o32 E8 cd | ### clc: Clear Carry Flag | Instruction | Opcode | | ----------- | ------ | | clc | F8 | ### cld: Clear Direction Flag | Instruction | Opcode | | ----------- | ------ | | cld | FC | ### cli: Clear Interrupt Flag | Instruction | Opcode | | ----------- | ------ | | cli | FA | ### cmovcc: Conditional Move | Instruction | Opcode | | ----------------- | --------------------- | | cmovcc r16 r/m16 | o16 0F (+ 40 cc) /r | | cmovcc r32 r/m32 | o32 0F (+ 40 cc) /r | | cmovcc r64 r/m64 | REX.W 0F (+ 40 cc) /r | Please refer [x86-64 conditional codes](AssemblyX64.md#conditional-codes) for details. ### cmp: Compare Please refer to [x86-64 arithmetic instructions](AssemblyX64Arith.md) for details. ### cmpxchg: Compare and Exchange | Instruction | Opcode | | ----------------- | ------------------ | | cmpxchg r/m8 r8 | 0F B0 /r | | cmpxchg r/m16 r16 | o16 0F B1 /r | | cmpxchg r/m32 r32 | o32 0F B1 /r | | cmpxchg r/m64 r64 | REX.W 0F B1 /r | ### cmpxchg8b/cmpxchg16b: Compare and Exchange Bytes | Instruction | Opcode | | --------------- | -------------- | | cmpxchg8b m64 | 0F C7 /1 | | cmpxchg16b m128 | REX.W 0F C7 /1 |
1,914
Common Lisp
.l
48
38.520833
86
0.55219
whily/yalo
571
32
1
GPL-2.0
9/19/2024, 11:24:32 AM (Europe/Amsterdam)
9bef4c515ca02df2cbdede675512550b74ce385c717622135fe45ea9aab01030
254
[ -1 ]
255
AssemblyX64Arith.md
whily_yalo/doc/AssemblyX64Arith.md
x86-64 Arithmetic Instruction ============================= [Assembly syntax](AssemblyX64.md) [A](AssemblyX64B.md) [B](AssemblyX64B.md) [C](AssemblyX64C.md) [D](AssemblyX64D.md) [E](AssemblyX64E.md) [F](AssemblyX64F.md) [H](AssemblyX64H.md) [I](AssemblyX64I.md) [J](AssemblyX64J.md) [L](AssemblyX64L.md) [M](AssemblyX64M.md) [N](AssemblyX64N.md) [O](AssemblyX64O.md) [P](AssemblyX64P.md) [R](AssemblyX64R.md) [S](AssemblyX64S.md) [T](AssemblyX64T.md) [U](AssemblyX64U.md) [V](AssemblyX64V.md) [W](AssemblyX64W.md) [X](AssemblyX64X.md) There are 8 arithmetic instructions which have similar formats of instructions. They are discussed together here. The instructions are: * adc: add with carry * add: add * and: logical and * cmp: compare * or: logical or * sbb: subtract with borrow * sub: subtract * xor: logical exclusive or The format of the instructions are given below. | Instruction | Opcode | | --------------- | ------------------------ | | ins al imm8 | (+ base 04) ib | | ins ax imm16 | o16 (+ base 05) iw | | ins eax imm32 | o32 (+ base 05) id | | ins rax imm32 | REX.W (+ base 05) id | | ins r/m8 imm8 | 80 opcode ib | | ins r/m16 imm16 | o16 81 opcode iw | | ins r/m32 imm32 | o32 81 opcode id | | ins r/m64 imm32 | REX.W 81 opcode id | | ins r/m16 imm8 | o16 83 opcode ib | | ins r/m32 imm8 | o32 83 opcode ib | | ins r/m64 imm8 | REX.W 83 opcode ib | | ins r/m8 r8 | base /r | | ins r/m16 r16 | o16 (+ base 01) /r | | ins r/m32 r32 | o32 (+ base 01) /r | | ins r/m64 r64 | REX.W (+ base 01) /r | | ins r8 r/m8 | (+ base 02) /r | | ins r16 r/m16 | o16 (+ base 03) /r | | ins r32 r/m32 | o32 (+ base 03) /r | | ins r64 r/m64 | REX.W (+ base 03) /r | Base and opcode in above table are given below for each instruction. | Instruction | Base (hexadecimal) | Opcode | | ----------- | ------------------ | ------ | | adc | 10 | /2 | | add | 00 | /0 | | and | 20 | /4 | | cmp | 38 | /7 | | or | 08 | /1 | | sbb | 18 | /3 | | sub | 28 | /5 | | xor | 30 | /6 |
2,399
Common Lisp
.l
54
43.296296
68
0.505988
whily/yalo
571
32
1
GPL-2.0
9/19/2024, 11:24:32 AM (Europe/Amsterdam)
2ea88eb5b33b4cacc9b4cb528f9fd729b92dfd795eda2294eb863ed4a89717b9
255
[ -1 ]
256
AssemblyX64A.md
whily_yalo/doc/AssemblyX64A.md
x86-64 Instruction Set A ======================== [Assembly syntax](AssemblyX64.md) A [B](AssemblyX64B.md) [C](AssemblyX64C.md) [D](AssemblyX64D.md) [E](AssemblyX64E.md) [F](AssemblyX64F.md) [H](AssemblyX64H.md) [I](AssemblyX64I.md) [J](AssemblyX64J.md) [L](AssemblyX64L.md) [M](AssemblyX64M.md) [N](AssemblyX64N.md) [O](AssemblyX64O.md) [P](AssemblyX64P.md) [R](AssemblyX64R.md) [S](AssemblyX64S.md) [T](AssemblyX64T.md) [U](AssemblyX64U.md) [V](AssemblyX64V.md) [W](AssemblyX64W.md) [X](AssemblyX64X.md) ### adc: Add with Carry Please refer to [x86-64 arithmetic instructions](AssemblyX64Arith.md) for details. ### add: Add Please refer to [x86-64 arithmetic instructions](AssemblyX64Arith.md) for details. ### and: Logical AND Please refer to [x86-64 arithmetic instructions](AssemblyX64Arith.md) for details.
820
Common Lisp
.l
16
49.8125
82
0.735257
whily/yalo
571
32
1
GPL-2.0
9/19/2024, 11:24:32 AM (Europe/Amsterdam)
dec1b3b7fa3ef1ca34d9ec71043049d3f71f2e0b183e00aa8fbf40e24d0f133a
256
[ -1 ]
257
AssemblyX64B.md
whily_yalo/doc/AssemblyX64B.md
x86-64 Instruction Set B ======================== [Assembly syntax](AssemblyX64.md) [A](AssemblyX64A.md) B [C](AssemblyX64C.md) [D](AssemblyX64D.md) [E](AssemblyX64E.md) [F](AssemblyX64F.md) [H](AssemblyX64H.md) [I](AssemblyX64I.md) [J](AssemblyX64J.md) [L](AssemblyX64L.md) [M](AssemblyX64M.md) [N](AssemblyX64N.md) [O](AssemblyX64O.md) [P](AssemblyX64P.md) [R](AssemblyX64R.md) [S](AssemblyX64S.md) [T](AssemblyX64T.md) [U](AssemblyX64U.md) [V](AssemblyX64V.md) [W](AssemblyX64W.md) [X](AssemblyX64X.md) ### bsf: Bit Scan Forward | Instruction | Opcode | | ------------- | -------------- | | bsf r16 r/m16 | o16 0F BC /r | | bsf r32 r/m32 | o32 0F BC /r | | bsf r64 r/m64 | REX.W 0F BC /r | ### bsf: Bit Scan Reverse | Instruction | Opcode | | ------------- | -------------- | | bsr r16 r/m16 | o16 0F BD /r | | bsr r32 r/m32 | o32 0F BD /r | | bsr r64 r/m64 | REX.W 0F BD /r | ### bswap: Byte Swap | Instruction | Opcode | | ----------- | -------------- | | bswap r32 | 0F C8+r | | bswap r64 | REX.W 0F C8+r | ### bt: Bit Test Please refer to [x86-64 bit instructions](AssemblyX64Bit.md) for details. ### btc: Bit Test and Complement Please refer to [x86-64 bit instructions](AssemblyX64Bit.md) for details. ### btr: Bit Test and Reset Please refer to [x86-64 bit instructions](AssemblyX64Bit.md) for details. ### bts: Bit Test and Set Please refer to [x86-64 bit instructions](AssemblyX64Bit.md) for details.
1,476
Common Lisp
.l
35
40.742857
73
0.622721
whily/yalo
571
32
1
GPL-2.0
9/19/2024, 11:24:32 AM (Europe/Amsterdam)
362a8b977b09f380b378be1f53e8e8cb1cce1e907697911d24e8c645dd4ba5d8
257
[ -1 ]
258
AssemblyX64U.md
whily_yalo/doc/AssemblyX64U.md
x86-64 Instruction Set U ======================== [Assembly syntax](AssemblyX64.md) [A](AssemblyX64A.md) [B](AssemblyX64B.md) [C](AssemblyX64C.md) [D](AssemblyX64D.md) [E](AssemblyX64E.md) [F](AssemblyX64F.md) [H](AssemblyX64H.md) [I](AssemblyX64I.md) [J](AssemblyX64J.md) [L](AssemblyX64L.md) [M](AssemblyX64M.md) [N](AssemblyX64N.md) [O](AssemblyX64O.md) [P](AssemblyX64P.md) [R](AssemblyX64R.md) [S](AssemblyX64S.md) [T](AssemblyX64T.md) U [V](AssemblyX64V.md) [W](AssemblyX64W.md) [X](AssemblyX64X.md) Placeholder
520
Common Lisp
.l
11
46.090909
62
0.708087
whily/yalo
571
32
1
GPL-2.0
9/19/2024, 11:24:32 AM (Europe/Amsterdam)
e0aefdfdbcc80380ae5ed20b07c7b5feb8083c77b31b8c799a0a6092c2e1cded
258
[ -1 ]
259
AssemblyX64R.md
whily_yalo/doc/AssemblyX64R.md
x86-64 Instruction Set R ======================== [Assembly syntax](AssemblyX64.md) [A](AssemblyX64A.md) [B](AssemblyX64B.md) [C](AssemblyX64C.md) [D](AssemblyX64D.md) [E](AssemblyX64E.md) [F](AssemblyX64F.md) [H](AssemblyX64H.md) [I](AssemblyX64I.md) [J](AssemblyX64J.md) [L](AssemblyX64L.md) [M](AssemblyX64M.md) [N](AssemblyX64N.md) [O](AssemblyX64O.md) [P](AssemblyX64P.md) R [S](AssemblyX64S.md) [T](AssemblyX64T.md) [U](AssemblyX64U.md) [V](AssemblyX64V.md) [W](AssemblyX64W.md) [X](AssemblyX64X.md) ### rdmsr: Read From Model Specific Register | Instruction | Opcode | | ----------- | ------ | | rdmsr | 0F 32 | ### rep: Repeat String Operation Prefix Following are examples. | Instruction | Opcode | | ----------- | ------ | | rep movsb | F3 A4 | | rep movsw | F3 A5 | Note *rep* is a kind of prefix. ### ret: Return From Procedure | Instruction | Opcode | | ----------- | ------ | | ret | C3 |
938
Common Lisp
.l
26
34.692308
62
0.626386
whily/yalo
571
32
1
GPL-2.0
9/19/2024, 11:24:32 AM (Europe/Amsterdam)
98389d9f86ef35bcd31fbf6f987ac50aa55bf61a02c104ee46d1eb35eedf302e
259
[ -1 ]
260
AssemblyX64D.md
whily_yalo/doc/AssemblyX64D.md
x86-64 Instruction Set D ======================== [Assembly syntax](AssemblyX64.md) [A](AssemblyX64A.md) [B](AssemblyX64B.md) [C](AssemblyX64C.md) D [E](AssemblyX64E.md) [F](AssemblyX64F.md) [H](AssemblyX64H.md) [I](AssemblyX64I.md) [J](AssemblyX64J.md) [L](AssemblyX64L.md) [M](AssemblyX64M.md) [N](AssemblyX64N.md) [O](AssemblyX64O.md) [P](AssemblyX64P.md) [R](AssemblyX64R.md) [S](AssemblyX64S.md) [T](AssemblyX64T.md) [U](AssemblyX64U.md) [V](AssemblyX64V.md) [W](AssemblyX64W.md) [X](AssemblyX64X.md) ### dec: Decrement by 1 | Instruction | Opcode | | ----------- | ----------- | | dec r/m8 | FE /1 | | dec r/m16 | o16 FF /1 | | dec r/m32 | o32 FF /1 | | dec r/m64 | REX.W FF /1 | | dec r16 | o16 48+r | | dec r32 | o32 48+r | ### div: Unsigned Divide | Instruction | Opcode | | ----------- | ----------- | | div r/m8 | F6 /6 | | div r/m16 | o16 F7 /6 | | div r/m32 | o32 F7 /6 | | div r/m64 | REX.W F7 /6 |
980
Common Lisp
.l
26
36.5
62
0.564805
whily/yalo
571
32
1
GPL-2.0
9/19/2024, 11:24:32 AM (Europe/Amsterdam)
79bb24b9a2c43145868fe41a2ae4e1b56a9c20b40c9a843f03511633a32fffc6
260
[ -1 ]
261
AssemblyX64V.md
whily_yalo/doc/AssemblyX64V.md
x86-64 Instruction Set V ======================== [Assembly syntax](AssemblyX64.md) [A](AssemblyX64A.md) [B](AssemblyX64B.md) [C](AssemblyX64C.md) [D](AssemblyX64D.md) [E](AssemblyX64E.md) [F](AssemblyX64F.md) [H](AssemblyX64H.md) [I](AssemblyX64I.md) [J](AssemblyX64J.md) [L](AssemblyX64L.md) [M](AssemblyX64M.md) [N](AssemblyX64N.md) [O](AssemblyX64O.md) [P](AssemblyX64P.md) [R](AssemblyX64R.md) [S](AssemblyX64S.md) [T](AssemblyX64T.md) [U](AssemblyX64U.md) V [W](AssemblyX64W.md) [X](AssemblyX64X.md) Placeholder
520
Common Lisp
.l
11
46.090909
62
0.708087
whily/yalo
571
32
1
GPL-2.0
9/19/2024, 11:24:32 AM (Europe/Amsterdam)
870d419425600c80b89f52bd4e0ebc7f95593b4c0f3e4f6cc07ae4551bafac55
261
[ -1 ]
262
AssemblyX64.md
whily_yalo/doc/AssemblyX64.md
Assembly syntax used by CL cross compiler and Ink ================================================= # Introduction Lisp Assembly Program (LAP) uses list structure to contain assembly code. Basically, atoms represent labels while lists represent (pseudo) instructions. Local labels (starting with a period) are also supported. Lisp expressions can be used for immediate values. In addition, since LAP is an S-expression, macros could be used to mimic the macro facility of *real* assemblers. The syntax is similar to what NASM uses. Basically, Intel syntax is used, i.e. destination operand precedes source operand. To get a feeling about what LAP looks like, one may take a look at the value of `*bootloader*` defined in https://github.com/whily/yalo/blob/master/cc/bootloader.lisp. # Pseudo Instructions of Assembly. Directives (e.g. bits, origin) are categorized as pseudo instructions here too. ## addressing: addressing mode Set the default setting of whether RIP Relative Addressing is used in 64 bit mode. This only applies when memory label is used (i.e. it does not affect the addressing options when registers are used, also it is not applicable to absolute address like #xb8000). One can use per-instruction override of `abs` or `rel` explicitly, for example: `(mov byte (abs msg) 0)`. | Instruction | Description | | -------------- | ------------------------------------------- | | addressing abs | Default to bsolute addresing | | addressing rel | Default to RIP Relative addresing (default) | ## align: boundary align The next instruction will be aligned at the boundary specified. NOP (#x90) will be inserted if necessary. | Instruction | Description | | -------------------------- | ------------- | | align 4 &#124; 8 &#124; 16 | | ## bits: Bit Mode | Instruction | Description | | ----------- | --------------------- | | bits 16 | 16-bit mode | | bits 64 | 64-bit mode (default) | ## db: Declaring initialized byte value(s) | Instruction | Description | | -------------------------------------- | ----------------------------- | | db (_number_ &#124; _string_)* | Declare byte values via lists | Note: * _number_ should be in range -128..+255. Expression within the same range can be used as well. * _string_ is converted byte by byte. ## dw: Declaring initialized word value(s) | Instruction | Description | | ---------------------- | ------------------------------ | | dw (_number_)* | Declare word value via lists | Note: * _number_ should be in range -32,768..+65,535. Expression within the same range can be used as well. ## dd: Declaring initialized doubleword value(s) | Instruction | Description | | ---------------------- | ------------------------------------ | | dd (_number_)* | Declare doubleword value via lists | Note: * _number_ should be in range -2,147,483,648..+4,294,967,295. Expression within the same range can be used as well. ## dq: Declaring initialized quadword value(s) | Instruction | Description | | ---------------------- | ---------------------------------- | | dq (_number_)* | Declare quadword value via lists | Note: * _number_ should be in range -9,223,372,036,854,775,808..+18,446,744,073,709,551,615. Expression within the same range can be used as well. ## equ: Defint Constant | Instruction | Description | | ------------------ | ----------------------------------------- | | equ _const_ _expr_ | Define constant _const_ with value _expr_ | Note: * _expr_ should be evaulated when encoutering the instruction, i.e. forward reference is not allowed. ## org: Define Origin | Instruction | Description | | ----------- | ----------------------- | | org val | Define origin to be val | Note: * *org* can be used multiple times, however $$ refers to the latest definition of *org*. ## resb/resw/resd/resq: Declare unitialized data | Instruction | Description | | ----------- | ----------------------- | | resb _n_ | Reserve _n_ bytes | | resw _n_ | Reserve _n_ words | | resd _n_ | Reserve _n_ doublewords | | resq _n_ | Reserve _n_ quadwords | ## times: Repeat instruction = | Instruction | Description | | --------------------------- | --------------------------------------- | | times _count_ _instruction_ | Assemble _count_ times of _instruction_ | Note: * _count_ could be an expression which can be evaluated when *times* instruction is encoutered, e.g. containing $, $$, or labels defined before *times* instruction. * _instruction_ can be any other (pseudo) instructions. # Special Variables of Assembly. Following special variables are supported: * **$** Location of the start of current instruction. * **$$** Origin (start address) of current assembly program. # Overview of x86-64 Assembly ## Intruction This wiki lists the machine instructions supported by x86-64 LAP, and the short description of the functions for each instruction. One should refer to Intel or AMD manuals for complete reference. For each mnemonic, one table is provided to list the supported instructions. There are 2 columns in the table: * **Instruction**: documents mnemonic and operands. * **Opcode**: documents the translated opcode. ## Notations for Instructions Following notations are used: * **imm8**: immediate byte value in the range of -128..+255. * **imm16**: immediate word value in the range of -32,768..+65,535. * **imm32**: immediate doubleword value in the range of -2,147,483,648..+4,294,967,295. * **imm64**: immediate quadword value in the range of -9,223,372,036,854,775,808..+18,446,744,073,709,551,615.. * **r8**: one of the byte general-purpose registers: al, cl, dl, bl, ah, ch, dh, bh, bpl, spl, dil, and sil. * **r16**: one of the word general-purpose registers: ax, cx, dx, bx, sp, bp, si, di. * **r32**: one of the doubleword general-purpose registers: eax, ecx, edx, ebx, esp, ebp, esi, edi. * **r64**: one of the quadword general-purpose registers: rax, rcx, rdx, rbx, rsp, rbp, rsi, rdi, r8-r15. * **m8, m16, m32, m64, m128**: memory references. Specifier (`byte`, `word`, `dword`, `qword`) is needed for ambiguous cases. For example in `(mov word (12345) 16). * **m16&32**, **m16&16**, **m32&32**, **m16&64**, a memory operand containing one pair whose sizes are indicated on the left and right size of the ampersand. * **r/m8, r/m16, r/m32, r/m64**: register or memeory choices. For example, r/m8 means that either r8 or m8 can be used as operand. * **sreg**: segment register. ## Range of Immediate Values Note that the range for imm8/16/32/64 is defined considering the capcity of 8/16/32/64 bits. The range might be too broad for jmp like instructions which require *true* signed integers, however the impact is minimal. In 64 bit mode, the default operand size is 32 bit. REX.W is used for 64 bit operand size. When 32 bit register is used as target, the result is automatically sign extended to 64 bit. To reduce the generated machine code size, the assembler automatically use the 32 bit operand size if immediate value can be represented as 32 bits. For example, `(mov eax 1)` and `(mov rax 1)` generates same machine code. Note that such optimization is mainly meaningful for *mov* instructions, as sign extension to 64 bit is generally not applicable for other instructions unless the upper 32 bits are always 0. ## Memory Address Operands Memory address operands are supported, e.g. `(bp)`, `(var)`, `(bp si 5)`. Note that the order is flexible. For example, `(bp si 3)` is equivalent to `(si 3 bp)`. For scaled index of 32-bit addressing modes, one has to use the form of register*scale, e.g. eax*8. Segment override prefix is used purely as a prefix, e.g. `(es mov al (di))`, which is different from traditional syntax. The motiviation is to use a simple method to handle this case as such override is not used in 64 bit mode. ## Notations for Opcodes Following notations are used: * A hex number, such as CC, indicates a fixed byte containing that number. * A hex number followed by **+r**, like **B0+r**, indicates that one of the operands is a register, and correspondign register value should be added to the opcode. * **/n** (where n is 0 to 7): indictes that one of the operand is r/m, and the field Reg/Opcode should be encoded with n. * **/r**: ModR/M byte of the instruction contains a register operand (encoded in field Reg/Opcode) and an r/m operand (encoded in field R/M). * **cb, cw, cd, co**: one of the operands is an immediate value, and the _difference_ between this value and the end address of the instruction is to be encoded as byte (cb), little-endian word (cw), little-endian doubleword (cd), and little-endian quadword (co) respectively. * **ib, iw, id, io**: one of the operands is an immediate value, and it is to be encoded as byte (ib), little-endian word (iw), little-endian doubleword (id), and little-endian quadword (io) respectively. * **o16, o32**: operand-size override prefix. o16 generates no code in 16-bit mode, but indicates a 66h prefix in 32/64-bit mode; similarly, o32 generates no code in 32/64-bit mode, but indicates a 66h prefix in 16-bit mode. * **a16, a32**: address-size override prefix. a16 generates no code in 16-bit mode, but indicates a 67h prefix in 32/64-bit mode; similarly, a32 generates no code in 32-bit mode, but indicates a 67h prefix in 16/64-bit mode. * **rex.w**: REX prefix indicating 64 bit operand, in 64 bit mode. Note that REX prefix are not used in opcode notations. The prefix is automatically generated by analyzing the operands. ### Conditional Codes Conditional codes are used for Jcc, CMOVcc, and SETcc instructions, which are encoded as (+ xx cc). Meaning of conditional codes are listed below. | cc | value | trigger flag | | -------- | ----- | ------------ | | o | 0 | overflow flag set | | no | 1 | overflow flag not set | | b c nae | 2 | carry flag set | | ae nb nc | 3 | carry flag not set | | e z | 4 | zero flag set | | ne nz | 5 | zero flag not set | | be na | 6 | either of carry or zero flag set | | a nbe | 7 | neither carry nor zero flag set | | s | 8 | sign flag set | | ns | 9 | sign flag not set | | p pe | 10 | parity flag set | | np po | 11 | parity flag not set | | l nge | 12 | exactly one of sign and overflow flag is set | | ge nl | 13 | opposite case of above | | le ng | 14 | either the zero flag is set, or exactly one of sign and overflow flag is set | | g nle | 15 | opposite case of above | # Instruction set [A](AssemblyX64A.md) [B](AssemblyX64B.md) [C](AssemblyX64C.md) [D](AssemblyX64D.md) [E](AssemblyX64E.md) [F](AssemblyX64F.md) [H](AssemblyX64H.md) [I](AssemblyX64I.md) [J](AssemblyX64J.md) [L](AssemblyX64L.md) [M](AssemblyX64M.md) [N](AssemblyX64N.md) [O](AssemblyX64O.md) [P](AssemblyX64P.md) [R](AssemblyX64R.md) [S](AssemblyX64S.md) [T](AssemblyX64T.md) [U](AssemblyX64U.md) [V](AssemblyX64V.md) [W](AssemblyX64W.md) [X](AssemblyX64X.md)
12,163
Common Lisp
.l
190
62.657895
276
0.611088
whily/yalo
571
32
1
GPL-2.0
9/19/2024, 11:24:32 AM (Europe/Amsterdam)
f7210ae35887efe484f7fc3e9302d2717358c87acf3cdfd427b3589f587a9439
262
[ -1 ]
263
AssemblyX64L.md
whily_yalo/doc/AssemblyX64L.md
x86-64 Instruction Set L ======================== [Assembly syntax](AssemblyX64.md) [A](AssemblyX64A.md) [B](AssemblyX64B.md) [C](AssemblyX64C.md) [D](AssemblyX64D.md) [E](AssemblyX64E.md) [F](AssemblyX64F.md) [H](AssemblyX64H.md) [I](AssemblyX64I.md) [J](AssemblyX64J.md) L [M](AssemblyX64M.md) [N](AssemblyX64N.md) [O](AssemblyX64O.md) [P](AssemblyX64P.md) [R](AssemblyX64R.md) [S](AssemblyX64S.md) [T](AssemblyX64T.md) [U](AssemblyX64U.md) [V](AssemblyX64V.md) [W](AssemblyX64W.md) [X](AssemblyX64X.md) ### leave: High Level Procedure Exit | Instruction | Opcode | | ----------- | -------- | | leave | C9 | ### lgdt/lidt/lldt: Load Descriptor Tables | Instruction | Opcode | | ----------- | -------- | | lgdt m16&32 | 0F 01 /2 | | lidt m16&32 | 0F 01 /3 | | lldt r/m16 | 0F 00 /2 | ### lodsb/lodsw: Load String | Instruction | Opcode | | ----------- | -------- | | lodsb | AC | | lodsw | o16 AD | | lodsd | o32 AD | | lodsq | REX.W AD | ### loop: Loop According to (E)CX Counter | Instruction | Opcode | | ----------- | ------ | | loop imm16 | E2 cb |
1,120
Common Lisp
.l
31
34.806452
62
0.577386
whily/yalo
571
32
1
GPL-2.0
9/19/2024, 11:24:32 AM (Europe/Amsterdam)
45e24cd370e08b6ddd85aedf1a0927c350ae90778be3c0559cafdf59a72639e0
263
[ -1 ]
264
AssemblyX64E.md
whily_yalo/doc/AssemblyX64E.md
x86-64 Instruction Set E ======================== [Assembly syntax](AssemblyX64.md) [A](AssemblyX64A.md) [B](AssemblyX64B.md) [C](AssemblyX64C.md) [D](AssemblyX64D.md) E [F](AssemblyX64F.md) [H](AssemblyX64H.md) [I](AssemblyX64I.md) [J](AssemblyX64J.md) [L](AssemblyX64L.md) [M](AssemblyX64M.md) [N](AssemblyX64N.md) [O](AssemblyX64O.md) [P](AssemblyX64P.md) [R](AssemblyX64R.md) [S](AssemblyX64S.md) [T](AssemblyX64T.md) [U](AssemblyX64U.md) [V](AssemblyX64V.md) [W](AssemblyX64W.md) [X](AssemblyX64X.md) Placeholder
520
Common Lisp
.l
11
46.090909
62
0.708087
whily/yalo
571
32
1
GPL-2.0
9/19/2024, 11:24:32 AM (Europe/Amsterdam)
90b19355e15787a9725dcbb67c897ede0464a4a7f04bc583a770bd26d6d080f3
264
[ -1 ]
265
build-bochs
whily_yalo/scripts/build-bochs
#!/usr/bin/env bash # Run the script in the root directory of bochs source. # Based on # https://git.archlinux.org/svntogit/community.git/tree/trunk/PKGBUILD?h=packages/bochs # https://wiki.osdev.org/Bochs#Compiling_Bochs_from_Source sed -i 's/2\.6\*|3\.\*)/2.6*|3.*|4.*)/' configure* ./configure \ --prefix=/usr \ --without-wx \ --enable-cpu-level=6 \ --enable-fpu \ --enable-3dnow \ --enable-disasm \ --enable-smp \ --enable-x86-64 \ --enable-avx \ --enable-long-phy-address \ --enable-disasm \ --enable-pcidev \ --enable-pci \ --enable-usb \ --enable-sb16=dummy \ --enable-cdrom \ --enable-debugger \ --enable-x86-debugger \ --enable-debugger-gui \ --enable-iodebug \ --enable-logging \ --with-x --with-x11 --with-term --with-sdl2 \ #--enable-all-optimizations --disable-docbook \ --disable-plugins sed -i 's/^LIBS = /LIBS = -lpthread/g' Makefile make -j5 && sudo make install
1,088
Common Lisp
.l
34
25
89
0.566667
whily/yalo
571
32
1
GPL-2.0
9/19/2024, 11:24:32 AM (Europe/Amsterdam)
111ac479621cd202ecd2b9e24b36a53d689ef4aefd0311670c6ab4e9ce964efe
265
[ -1 ]
280
ppu.lisp
samanthadoran_potential-disco/ppu.lisp
;; Almost all of my understanding of the PPU comes from.. ;; The nesdev wiki ;; Sprocket-NES ;; Fogleman's NES ;; Famiclom ;; As such, this is basically a translation of https://github.com/fogleman/nes/blob/master/nes/ppu.go ;; Hopefully, I can eventually gain a better understanding (defpackage #:NES-ppu (:nicknames #:ppu) (:use :cl) (:export #:step-ppu #:make-ppu #:reset-ppu #:read-register #:write-register #:ppu-trigger-nmi-callback #:ppu-front #:ppu-back #:ppu-frame #:color-r #:color-g #:color-b #:color #:read-palette #:write-palette #:ppu-memory-get #:ppu-memory-set #:ppu-name-table-data #:ppu-oam-dma-callback #:ppu-oam-stall-adder #:screen-width #:screen-height)) (in-package :NES-ppu) (declaim (optimize (speed 3) (safety 1))) (defconstant screen-width 256) (defconstant screen-height 240) (defconstant vblank-scanline 241) (defconstant last-scanline 261) (defconstant cycles-per-scanline 114) (defconstant cycles-per-cpu 3) (defstruct color "Simple RGBA" (r 0 :type (unsigned-byte 8)) (g 0 :type (unsigned-byte 8)) (b 0 :type (unsigned-byte 8))) (defun wrap-byte (val) (declare ((unsigned-byte 64) val)) (ldb (byte 8 0) val)) (defun wrap-word (val) (declare ((unsigned-byte 64) val)) (ldb (byte 16 0) val)) (defun to-signed-byte-8 (val) (declare ((unsigned-byte 8) val)) (the fixnum (if (ldb-test (byte 1 7) val) (* -1 (wrap-byte (1+ (lognot val)))) val))) (defvar *palette* (progn (let ((pal (make-array 64 :element-type 'color :initial-element (make-color :r 0 :g 0 :b 0))) (colors (make-array 64 :element-type '(unsigned-byte 32) :initial-contents '(#x666666 #x002A88 #x1412A7 #x3B00A4 #x5C007E #x6E0040 #x6C0600 #x561D00 #x333500 #x0B4800 #x005200 #x004F08 #x00404D #x000000 #x000000 #x000000 #xADADAD #x155FD9 #x4240FF #x7527FE #xA01ACC #xB71E7B #xB53120 #x994E00 #x6B6D00 #x388700 #x0C9300 #x008F32 #x007C8D #x000000 #x000000 #x000000 #xFFFEFF #x64B0FF #x9290FF #xC676FF #xF36AFF #xFE6ECC #xFE8170 #xEA9E22 #xBCBE00 #x88D800 #x5CE430 #x45E082 #x48CDDE #x4F4F4F #x000000 #x000000 #xFFFEFF #xC0DFFF #xD3D2FF #xE8C8FF #xFBC2FF #xFEC4EA #xFECCC5 #xF7D8A5 #xE4E594 #xCFEF96 #xBDF4AB #xB3F3CC #xB5EBF2 #xB8B8B8 #x000000 #x000000)))) (loop for i from 0 to 63 do (let* ((c (aref colors i)) (r (ldb (byte 8 16) c)) (g (ldb (byte 8 8) c)) (b (ldb (byte 8 0) c))) (setf (aref pal i) (make-color :r r :g g :b b)))) pal))) (defstruct ppu "A model picture processing unit" (front (make-array #xF000 :element-type 'color :initial-element (make-color :r 0 :g 0 :b 0)) :type (simple-array color 1)) (back (make-array #xF000 :element-type 'color :initial-element (make-color :r 0 :g 0 :b 0)) :type (simple-array color 1)) (cycle 0 :type (unsigned-byte 16)) (scanline 0 :type (unsigned-byte 16)) (frame 0 :type (unsigned-byte 16)) (memory-get (make-array 3 :element-type 'function :initial-element (lambda ())) :type (simple-array function 1)) (memory-set (make-array 3 :element-type 'function :initial-element (lambda ())) :type (simple-array function 1)) (palette-data (make-array 32 :element-type '(unsigned-byte 8)) :type (simple-array (unsigned-byte 8) 1)) (name-table-data (make-array 2048 :element-type '(unsigned-byte 8)) :type (simple-array (unsigned-byte 8) 1)) (oam-data (make-array 256 :element-type '(unsigned-byte 8)) :type (simple-array (unsigned-byte 8) 1)) ;Registers (v 0 :type (unsigned-byte 16)) ;Current vram address (tv 0 :type (unsigned-byte 16));Temporary vram address (x 0 :type (unsigned-byte 3));Fine x scroll (w 0 :type (unsigned-byte 1));Write toggle (f 0 :type (unsigned-byte 1));Odd frame flag (register 0 :type (unsigned-byte 8)) ;NMI Status (nmi-occurred nil :type boolean) (nmi-output nil :type boolean) (nmi-previous nil :type boolean) (nmi-delay 0 :type (unsigned-byte 16)) (trigger-nmi-callback (lambda ()) :type function) ;Tiles (name-table 0 :type (unsigned-byte 8)) (attribute-table 0 :type (unsigned-byte 8)) (low-tile 0 :type (unsigned-byte 8)) (high-tile 0 :type (unsigned-byte 8)) (tile-data 0 :type (unsigned-byte 64)) ;Sprites (sprite-count 0 :type (unsigned-byte 8)) (sprite-patterns (make-array 8 :element-type '(unsigned-byte 32)) :type (simple-array (unsigned-byte 32) 1)) (sprite-positions (make-array 8 :element-type '(unsigned-byte 8)) :type (simple-array (unsigned-byte 8) 1)) (sprite-priorities (make-array 8 :element-type '(unsigned-byte 8)) :type (simple-array (unsigned-byte 8) 1)) (sprite-indexes (make-array 8 :element-type '(unsigned-byte 8)) :type (simple-array (unsigned-byte 8) 1)) ;$2000 PPU Control (flag-name-table 0 :type (unsigned-byte 2)) (flag-increment 0 :type (unsigned-byte 1)) (flag-sprite-table 0 :type (unsigned-byte 1)) (flag-background-table 0 :type (unsigned-byte 1)) (flag-sprite-size 0 :type (unsigned-byte 1)) (flag-master-slave 0 :type (unsigned-byte 1)) ;$2001 PPU Mask (flag-grayscale 0 :type (unsigned-byte 1)) (flag-show-left-background 0 :type (unsigned-byte 1)) (flag-show-left-sprites 0 :type (unsigned-byte 1)) (flag-show-background 0 :type (unsigned-byte 1)) (flag-show-sprites 0 :type (unsigned-byte 1)) (flag-red-tint 0 :type (unsigned-byte 1)) (flag-green-tint 0 :type (unsigned-byte 1)) (flag-blue-tint 0 :type (unsigned-byte 1)) ;$2002 PPU Status (flag-sprite-zero-hit 0 :type (unsigned-byte 8)) (flag-sprite-overflow 0 :type (unsigned-byte 8)) ;$2003 OAM Address (oam-address 0 :type (unsigned-byte 8)) ;Buffer for $2007 Data Read (buffered-data 0 :type (unsigned-byte 8)) (oam-dma-callback (lambda()) :type function) (oam-stall-adder (lambda()) :type function)) (defun read-ppu (p addr) (declare (ppu p) ((unsigned-byte 16) addr)) (setf addr (mod addr #x4000)) (cond ;Mapper ((< addr #x2000) (funcall (aref (ppu-memory-get p) 0) addr)) ;Name table data ((< addr #x3F00) (funcall (aref (ppu-memory-get p) 1) addr)) ;Palette data ((< addr #x4000) (funcall (aref (ppu-memory-get p) 2) addr)))) (defun write-ppu (p addr val) (declare (ppu p) ((unsigned-byte 16) addr) ((unsigned-byte 8) val)) (setf addr (mod addr #x4000)) (cond ;Mapper ((< addr #x2000) (funcall (aref (ppu-memory-set p) 0) addr val)) ;Name table data ((< addr #x3F00) (funcall (aref (ppu-memory-set p) 1) addr val)) ;Palette data ((< addr #x4000) (funcall (aref (ppu-memory-set p) 2) addr val)))) (defun read-palette (p address) (declare (ppu p) ((unsigned-byte 16) address)) (aref (ppu-palette-data p) (if (and (>= address 16) (= (mod address 4) 0)) (wrap-word (- address 16)) address))) (defun write-palette (p address value) (declare (ppu p) ((unsigned-byte 16) address) ((unsigned-byte 8) value)) (setf (aref (ppu-palette-data p) (if (and (>= address 16) (= (mod address 4) 0)) (wrap-word (- address 16)) address)) value)) (defun write-control (p value) (declare (ppu p) ((unsigned-byte 8) value)) (setf (ppu-flag-name-table p) (ldb (byte 2 0) value)) (setf (ppu-flag-increment p) (ldb (byte 1 2) value)) (setf (ppu-flag-sprite-table p) (ldb (byte 1 3) value)) (setf (ppu-flag-background-table p) (ldb (byte 1 4) value)) (setf (ppu-flag-sprite-size p) (ldb (byte 1 5) value)) (setf (ppu-flag-master-slave p) (ldb (byte 1 6) value)) (setf (ppu-nmi-output p) (ldb-test (byte 1 7) value)) (nmi-change p) (setf (ppu-tv p) (logior (logand (ppu-tv p) #xF3FF) (ash (logand value 3) 10)))) (defun write-mask (p value) (declare (ppu p) ((unsigned-byte 8) value)) (setf (ppu-flag-grayscale p) (ldb (byte 1 0) value)) (setf (ppu-flag-show-left-background p) (ldb (byte 1 1) value)) (setf (ppu-flag-show-left-sprites p) (ldb (byte 1 2) value)) (setf (ppu-flag-show-background p) (ldb (byte 1 3) value)) (setf (ppu-flag-show-sprites p) (ldb (byte 1 4) value)) (setf (ppu-flag-red-tint p) (ldb (byte 1 5) value)) (setf (ppu-flag-green-tint p) (ldb (byte 1 6) value)) (setf (ppu-flag-blue-tint p) (ldb (byte 1 7) value))) (defun read-status (p) (setf (ppu-w p) 0) (let ((result (logand (ppu-register p) #x1F))) (declare ((unsigned-byte 8) result)) (setf result (logior (logior result (ash (ppu-flag-sprite-overflow p) 5)) (ash (ppu-flag-sprite-zero-hit p) 6))) (when (ppu-nmi-occurred p) (setf result (logior result (ash 1 7)))) (setf (ppu-nmi-occurred p) nil) (nmi-change p) result)) (defun write-oam-address (p value) (declare (ppu p) ((unsigned-byte 8) value)) (setf (ppu-oam-address p) value)) (defun read-oam-data (p) (declare (ppu p)) (aref (ppu-oam-data p) (ppu-oam-address p))) (defun write-oam-data (p value) (declare (ppu p) ((unsigned-byte 8) value)) (setf (aref (ppu-oam-data p) (ppu-oam-address p)) value) (setf (ppu-oam-address p) (wrap-byte (1+ (ppu-oam-address p))))) (defun write-scroll (p value) (declare (ppu p) ((unsigned-byte 8) value)) (if (= (ppu-w p) 0) (progn (setf (ppu-tv p) (logior (logand (ppu-tv p) #xFFE0) (ash value -3))) (setf (ppu-x p) (logand value #x07)) (setf (ppu-w p) 1)) (progn (setf (ppu-tv p) (logior (logand (ppu-tv p) #x8FFF) (ash (logand value #x07) 12))) (setf (ppu-tv p) (logior (logand (ppu-tv p) #xFC1F) (ash (logand value #xF8) 2))) (setf (ppu-w p) 0)))) (defun write-address (p value) (declare (ppu p) ((unsigned-byte 8) value)) (if (= (ppu-w p) 0) (progn (setf (ppu-tv p) (logior (logand (ppu-tv p) #x80FF) (ash (logand value #x3F) 8))) (setf (ppu-w p) 1)) (progn (setf (ppu-tv p) (logior (logand (ppu-tv p) #xFF00) value)) (setf (ppu-v p) (ppu-tv p)) (setf (ppu-w p) 0)))) (defun read-data (p) (declare (ppu p)) (let ((value (read-ppu p (ppu-v p)))) (declare ((unsigned-byte 8) value)) (if (< (mod (ppu-v p) #x4000) #x3F00) (let ((buffered (ppu-buffered-data p))) (setf (ppu-buffered-data p) value) (setf value buffered)) (setf (ppu-buffered-data p) (read-ppu p (wrap-word (- (ppu-v p) #x1000))))) (setf (ppu-v p) (wrap-word (+ (ppu-v p) (if (= (ppu-flag-increment p) 0) 1 32)))) value)) (defun write-data (p value) (declare (ppu p) ((unsigned-byte 8) value)) (write-ppu p (ppu-v p) value) (setf (ppu-v p) (wrap-word (+ (ppu-v p) (if (= (ppu-flag-increment p) 0) 1 32))))) (defun write-dma (p value) (declare (ppu p) ((unsigned-byte 8) value)) (let ((address (ash value 8))) (loop for i from 0 to 255 do (progn (setf (aref (ppu-oam-data p) (ppu-oam-address p)) (funcall (ppu-oam-dma-callback p) address)) (setf (ppu-oam-address p) (wrap-byte (1+ (ppu-oam-address p)))) (setf address (wrap-word (1+ address))))) (funcall (ppu-oam-stall-adder p) 513))) (defun read-register (p selector) (declare (ppu p) ((unsigned-byte 16) selector)) (case selector ;Read ppu status (2 (read-status p)) ;Read OAM Data (4 (read-oam-data p)) ;Read Data (7 (read-data p)) (otherwise (progn (print "Uhm?") 0)))) (defun write-register (p selector value) (declare (ppu p) ((unsigned-byte 16) selector)) (setf (ppu-register p) value) (case selector ;Write Control (0 (write-control p value)) ;Write Mask (1 (write-mask p value)) ;Write OAM Address (3 (write-oam-address p value)) ;Write OAM Data (4 (write-oam-data p value)) ;Write scroll (5 (write-scroll p value)) ;Write Address (6 (write-address p value)) ;Write Data (7 (write-data p value)) ;Write DMA (#x4014 (write-dma p value)) (otherwise (progn (print "Uhm in write?") 0)))) (defun increment-x (p) (declare (ppu p)) (setf (ppu-v p) (if (= (logand (ppu-v p) #x001F) 31) (logxor #x0400 (logand (ppu-v p) #xFFE0)) (wrap-word (1+ (ppu-v p)))))) (defun increment-y (p) (declare (ppu p)) (if (/= (logand (ppu-v p) #x7000) #x7000) (setf (ppu-v p) (wrap-word (+ #x1000 (ppu-v p)))) (progn (setf (ppu-v p) (logand (ppu-v p) #x8FFF)) (let ((y (ash (logand (ppu-v p) #x03E0) -5))) (if (= y 29) (progn (setf y 0) (setf (ppu-v p) (logxor (ppu-v p) #x0800))) (setf y (if (= y 31) 0 (1+ y)))) (setf (ppu-v p) (logior (logand (ppu-v p) #xFC1F) (ash y 5))))))) (defun copy-x (p) (declare (ppu p)) (setf (ppu-v p) (logior (logand (ppu-v p) #xFBE0) (logand (ppu-tv p) #x041F)))) (defun copy-y (p) (declare (ppu p)) (setf (ppu-v p) (logior (logand (ppu-v p) #x841F) (logand (ppu-tv p) #x7BE0)))) (defun nmi-change (p) (declare (ppu p)) (let ((nmi (and (ppu-nmi-output p) (ppu-nmi-occurred p)))) (when (and nmi (not (ppu-nmi-previous p))) (setf (ppu-nmi-delay p) 15)) (setf (ppu-nmi-previous p) nmi))) (defun set-vertical-blank (p) (declare (ppu p)) (psetf (ppu-front p) (ppu-back p) (ppu-back p) (ppu-front p)) (setf (ppu-nmi-occurred p) T) (nmi-change p)) (defun clear-vertical-blank (p) (declare (ppu p)) (setf (ppu-nmi-occurred p) nil) (nmi-change p)) (defun fetch-name-table (p) (declare (ppu p)) (setf (ppu-name-table p) (read-ppu p (logior #x2000 (logand (ppu-v p) #x0FFF))))) (defun fetch-attribute-table (p) (declare (ppu p)) (let* ((v (ppu-v p)) (address (logior #x23C0 (logand v #x0C00) (logand #x38 (ash v -4)) (logand #x07 (ash v -2)))) (shift (logior (logand (ash v -4) 4) (logand v 2)))) (setf (ppu-attribute-table p) (ash (ldb (byte 2 0) (ash (the (unsigned-byte 8) (read-ppu p address)) (* -1 shift))) 2)))) (defun fetch-low-tile (p) (declare (ppu p)) (let* ((fine-y (logand 7 (ash (ppu-v p) -12))) (table (ppu-flag-background-table p)) (tile (ppu-name-table p)) (address (+ (* #x1000 table) (* 16 tile) fine-y))) (setf (ppu-low-tile p) (read-ppu p address)))) (defun fetch-high-tile (p) (declare (ppu p)) (let* ((fine-y (logand 7 (ash (ppu-v p) -12))) (table (ppu-flag-background-table p)) (tile (ppu-name-table p)) (address (+ (* #x1000 table) (* 16 tile) fine-y))) (setf (ppu-high-tile p) (read-ppu p (wrap-word (+ address 8)))))) (defun store-tile-data (p) (declare (ppu p)) (let ((data 0)) (declare ((unsigned-byte 32) data)) (loop for i from 0 to 7 do (let ((a (ppu-attribute-table p)) (p1 (ash (logand #x80 (ppu-low-tile p)) -7)) (p2 (ash (logand #x80 (ppu-high-tile p)) -6))) (declare ((unsigned-byte 8) a p1 p2)) (setf (ppu-low-tile p) (wrap-byte (ash (ppu-low-tile p) 1))) (setf (ppu-high-tile p) (wrap-byte (ash (ppu-high-tile p) 1))) (setf data (logior a p1 p2 (ash data 4))))) (setf (ppu-tile-data p) (logior (ppu-tile-data p) data)))) (defun fetch-tile-data (p) (declare (ppu p)) (ldb (byte 32 32) (ppu-tile-data p))) (defun background-pixel (p) (declare (ppu p)) (if (= (ppu-flag-show-background p) 0) 0 (ldb (byte 4 0) (ash (fetch-tile-data p) (the fixnum (* (the fixnum (- 7 (ppu-x p))) 4 -1)))))) (defun sprite-pixel (p) (declare (ppu p)) (when (= (ppu-flag-show-sprites p) 0) (return-from sprite-pixel (values 0 0))) (loop for i from 0 to (- (ppu-sprite-count p) 1) do (let ((offset (- (- (ppu-cycle p) 1) (aref (ppu-sprite-positions p) i)))) (declare (fixnum offset)) (when (and (>= offset 0) (<= offset 7)) (setf offset (- 7 offset)) (let ((color (logand #x0F (ash (aref (ppu-sprite-patterns p) i) (* -1 (wrap-byte (* offset 4))))))) (when (/= (mod color 4) 0) (return-from sprite-pixel (values (wrap-byte i) color))))))) (return-from sprite-pixel (values 0 0))) (defun render-pixel (p) (declare (ppu p)) (multiple-value-bind (i sprite) (sprite-pixel p) (declare ((unsigned-byte 8) i sprite)) (let ((x (- (ppu-cycle p) 1)) (y (ppu-scanline p)) (background (background-pixel p))) (declare ((unsigned-byte 16) x y) ((unsigned-byte 8) background)) (when (and (< x 8) (= (ppu-flag-show-left-background p) 0)) (setf background 0)) (when (and (< x 8) (= (ppu-flag-show-left-sprites p) 0)) (setf sprite 0)) (let ((b (/= (mod background 4) 0)) (s (/= (mod sprite 4) 0)) (color #x00)) (cond ((and (not b) (not s)) (setf color 0)) ((and (not b) s) (setf color (logior #x10 sprite))) ((and b (not s)) (setf color background)) (T (progn (when (and (< x 255) (= (aref (ppu-sprite-indexes p) i) 0)) (setf (ppu-flag-sprite-zero-hit p) 1)) (if (= (aref (ppu-sprite-priorities p) i) 0) (setf color (logior sprite #x10)) (setf color background))))) (setf (aref (ppu-back p) (+ (* y screen-width) x)) (aref (the (simple-array color 1) *palette*) (mod (read-palette p (wrap-word color)) 64))))))) (defun fetch-sprite-pattern (p i r) (declare (ppu p) ((signed-byte 16) i r)) (let* ((tile (aref (ppu-oam-data p) (1+ (* i 4)))) (attributes (aref (ppu-oam-data p) (+ 2 (* i 4)))) (address #x0000) (a (ash (logand attributes 3) 2)) (row r)) (declare (fixnum row) ((unsigned-byte 8) a attributes tile) ((unsigned-byte 16) address)) (if (= (ppu-flag-sprite-size p) 0) (let ((table (ppu-flag-sprite-table p))) (declare ((unsigned-byte 1) table)) (when (= (logand attributes #x80) #x80) (setf row (- 7 row))) (setf address (+ (* #x1000 table) (* 16 tile) row))) (let ((table (logand tile 1))) (when (= (logand attributes #x80) #x80) (setf row (- 15 row))) (setf tile (logand tile #xFE)) (when (> row 7) (incf tile) (decf row 8)) (setf address (+ (* #x1000 table) (* tile 16) row)))) (let ((low-tile (read-ppu p address)) (high-tile (read-ppu p (wrap-word (+ address 8)))) (data #x00000000)) (declare ((unsigned-byte 8) low-tile high-tile)) (loop for i from 0 to 7 do (let ((p1 0) (p2 0)) (if (= (logand attributes #x40) #x40) (progn (setf p1 (logand low-tile 1)) (setf p2 (ash (logand high-tile 1) 1)) (setf low-tile (ash low-tile -1)) (setf high-tile (ash high-tile -1))) (progn (setf p1 (ash (logand low-tile #x80) -7)) (setf p2 (ash (logand high-tile #x80) -6)) (setf low-tile (wrap-byte (ash low-tile 1))) (setf high-tile (wrap-byte (ash high-tile 1))))) (setf data (logand #xFFFFFFFF (logior (ash data 4) a p1 p2))))) (the (unsigned-byte 32) data)))) (defun evaluate-sprites (p) (declare (ppu p)) (let ((h (if (= (ppu-flag-sprite-size p) 0) 8 16)) (count 0)) (declare (fixnum count) ((unsigned-byte 8) h)) (loop for i from 0 to 63 do (let* ((y (aref (ppu-oam-data p) (* i 4))) (a (aref (ppu-oam-data p) (+ 2 (* i 4)))) (x (aref (ppu-oam-data p) (+ 3 (* i 4)))) (row (- (ppu-scanline p) y))) (declare ((unsigned-byte 8) y a x) (fixnum row)) (when (and (>= row 0) (< row h)) (when (< count 8) (setf (aref (ppu-sprite-patterns p) count) (fetch-sprite-pattern p i row)) (setf (aref (ppu-sprite-positions p) count) x) (setf (aref (ppu-sprite-priorities p) count) (logand 1 (ash a -5))) (setf (aref (ppu-sprite-indexes p) count) i)) (incf count)))) (when (> count 8) (setf count 8) (setf (ppu-flag-sprite-overflow p) 1)) (setf (ppu-sprite-count p) count))) (defun reset-ppu (p) (declare (ppu p)) (setf (ppu-cycle p) 340) (setf (ppu-scanline p) 240) (setf (ppu-frame p) 0) (write-control p 0) (write-mask p 0) (write-oam-address p 0)) (defun tick (p) (declare (ppu p)) ;While the nmi delay is greater than zero... (when (> (ppu-nmi-delay p) 0) ;Decrement it... (decf (ppu-nmi-delay p)) ;Trigger it if we have run out of time and there even is one (when (and (= (ppu-nmi-delay p) 0) (ppu-nmi-output p) (ppu-nmi-occurred p)) (funcall (ppu-trigger-nmi-callback p)))) (when (or (/= 0 (ppu-flag-show-background p)) (/= 0 (ppu-flag-show-sprites p))) (when (and (= (ppu-f p) 1) (= (ppu-scanline p) 261) (= (ppu-cycle p) 339)) (setf (ppu-cycle p) 0) (setf (ppu-scanline p) 0) (setf (ppu-frame p) (wrap-word (1+ (ppu-frame p)))) (setf (ppu-f p) (logxor (ppu-f p) 1)) (return-from tick 0))) (incf (ppu-cycle p)) ;We've hit the end of the scanline (when (> (ppu-cycle p) 340) ;Reset the cycle number (setf (ppu-cycle p) 0) ;Increment the scanline (incf (ppu-scanline p)) ;And finally do housework if we need to go back to top (when (> (ppu-scanline p) 261) (setf (ppu-scanline p) 0) (setf (ppu-frame p) (wrap-word (1+ (ppu-frame p)))) (setf (ppu-f p) (logxor (ppu-f p) 1))))) (defun step-ppu (p step) (declare (ppu p) ((unsigned-byte 8) step)) (loop for i from 1 to step do (progn (tick p) (let* ((cycle (ppu-cycle p)) (scanline (ppu-scanline p)) (rendering-enabled (not (= 0 (ppu-flag-show-background p) (ppu-flag-show-sprites p)))) (pre-line (= scanline 261)) (visible-line (< scanline 240)) (render-line (or pre-line visible-line)) (pre-fetch-cycle (and (>= cycle 321) (<= cycle 336))) (visible-cycle (and (>= cycle 1) (<= cycle 256))) (fetch-cycle (or pre-fetch-cycle visible-cycle))) (when rendering-enabled ;Begin background logic (when (and visible-line visible-cycle) (render-pixel p)) ;When we are on a fetch cycle and a render line... (when (and render-line fetch-cycle) ;Shift tile data left four to make room (setf (ppu-tile-data p) ;Make sure it continues to fit in 64 bits (ldb (byte 64 0) (ash (ppu-tile-data p) 4))) ;Depending on what cycle we are in act accordingly (case (mod cycle 8) (0 (store-tile-data p)) (1 (fetch-name-table p)) (3 (fetch-attribute-table p)) (5 (fetch-low-tile p)) (7 (fetch-high-tile p)))) ;When we are on preline and (when (and pre-line (>= (ppu-cycle p) 280) (<= (ppu-cycle p) 304)) (copy-y p)) (when render-line (when (and fetch-cycle (= (mod cycle 8) 0)) (increment-x p)) (when (= cycle 256) (increment-y p)) (when (= cycle 257) (copy-x p))) ;begin sprite logic (when (= cycle 257) (if visible-line (evaluate-sprites p) (setf (ppu-sprite-count p) 0)))) ;Begin vblank logic (when (and (= scanline 241) (= (ppu-cycle p) 1)) (set-vertical-blank p)) (when (and pre-line (= (ppu-cycle p) 1)) (clear-vertical-blank p) (setf (ppu-flag-sprite-zero-hit p) 0) (setf (ppu-flag-sprite-overflow p) 0))))))
24,088
Common Lisp
.lisp
677
29.51551
101
0.58303
samanthadoran/potential-disco
233
19
1
GPL-3.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
51c2c19fbaaa9c275cda561757a7aa10a6dfa9fa5a8fd4c5417e3fdd70425486
280
[ -1 ]
281
cartridge.lisp
samanthadoran_potential-disco/cartridge.lisp
(defpackage #:NES-cartridge (:nicknames #:nes-cart) (:use :cl) (:export #:load-cartridge #:make-cartridge #:cartridge-prg-rom #:cartridge-prg-ram #:cartridge-chr-rom #:cartridge-chr-ram #:cartridge-mirror)) (in-package :NES-cartridge) (defconstant prg-size #x4000) (defconstant chr-size #x2000) (defstruct ines-header "ines header spec" (magic (make-array 4 :element-type '(unsigned-byte 8))) ;Size of prg rom in 16 KiB units (size-of-prg-rom 0 :type (unsigned-byte 8)) ;Size of chr rom in 8 KiB units (size-of-chr-rom 0 :type (unsigned-byte 8)) (flags6 0 :type (unsigned-byte 8)) (flags7 0 :type (unsigned-byte 8)) ;Size of PRG ram in 8 KiB unites (size-of-prg-ram 0 :type (unsigned-byte 8)) (flags9 0 :type (unsigned-byte 8)) (flags10 0 :type (unsigned-byte 8)) (zero-pad (make-array 5 :element-type '(unsigned-byte 8)))) (defstruct cartridge "A model NES cartridge" (prg-rom 0) (prg-rom-window 0 :type (unsigned-byte 8)) ;We ignore prg-ram for now (prg-ram 0) (prg-ram-window 0 :type (unsigned-byte 8)) (chr-rom 0) (chr-ram 0) (chr-window 0 :type (unsigned-byte 8)) (mapper-number 0) (header 0) (mirror)) (defun load-header (seq) (make-ines-header :magic (subseq seq 0 4) :size-of-prg-rom (aref seq 4) :size-of-chr-rom (aref seq 5) :flags6 (aref seq 6) :flags7 (aref seq 7) :size-of-prg-ram (aref seq 8) :flags9 (aref seq 9) :flags10 (aref seq 10) :zero-pad (subseq seq 11 16))) (defun load-cartridge (filepath) (let ((cart (make-cartridge)) (header (make-ines-header))) (with-open-file (stream filepath :element-type '(unsigned-byte 8)) (let ((seq (make-array (file-length stream) :element-type '(unsigned-byte 8)))) (read-sequence seq stream) (setf header (load-header seq)) (let* ;If trainers are present, skip them. ((to-add (if (ldb-test (byte 1 3) (ines-header-flags6 header)) 512 0)) ;Limits of memory areas (begin-prg (+ 16 to-add)) (end-prg (+ begin-prg (* prg-size (ines-header-size-of-prg-rom header)))) (begin-chr end-prg) (end-chr (+ begin-chr (* chr-size (ines-header-size-of-chr-rom header))))) ;Load in prg-rom (setf (cartridge-prg-rom cart) (subseq seq begin-prg end-prg)) ;If there is no rom, there is ram (if (= (ines-header-size-of-chr-rom header) 0) (setf (cartridge-chr-ram cart) (make-array chr-size :element-type '(unsigned-byte 8))) (setf (cartridge-chr-rom cart) (subseq seq begin-chr end-chr))) (setf (cartridge-header cart) header) (let ((mirror1 (logand (ines-header-flags6 header) 1)) (mirror2 (logand (ash (ines-header-flags6 header) -3) 1))) (setf (cartridge-mirror cart) (logior mirror1 (ash mirror2 1)))))) cart)))
3,120
Common Lisp
.lisp
89
27.674157
85
0.59154
samanthadoran/potential-disco
233
19
1
GPL-3.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
546b8b051544a9f780e529d76e4b56fddbcb38430594ebc646a8dd426f541ccd
281
[ -1 ]
282
mmu.lisp
samanthadoran_potential-disco/mmu.lisp
(in-package :NES-console) (declaim (optimize (speed 3) (safety 1))) (defun mirror-address (mode addr) (declare ((unsigned-byte 16) addr) ((unsigned-byte 8) mode)) (let* ((address (mod (- addr #x2000) #x1000)) (table (floor address #x0400)) (offset (mod address #x0400))) (declare ((unsigned-byte 16) address table offset)) (logand #xFFFF (+ #x2000 offset (* #x0400 (the (unsigned-byte 3) (aref (the (simple-array (unsigned-byte 2) 1)mirror-lookup) (+ (* mode 4) table)))))))) (defun ppu-to-name-table-read (n) (lambda (addr) (declare ((unsigned-byte 16) addr) (nes n)) (let ((mirror (logand (mirror-address (NES-cartridge:cartridge-mirror (nes-cart n)) addr) #x7ff))) (aref (NES-ppu:ppu-name-table-data (nes-ppu n)) mirror)))) (defun ppu-to-name-table-write (n) (lambda (addr val) (declare ((unsigned-byte 16) addr) ((unsigned-byte 8) val) (nes n)) (let ((mirror (logand (mirror-address (NES-cartridge:cartridge-mirror (nes-cart n)) addr) #x7ff))) (setf (aref (NES-ppu:ppu-name-table-data (nes-ppu n)) mirror) val)))) (defun ppu-to-palette-read (n) (lambda (addr) (declare ((unsigned-byte 16) addr) (nes n)) (NES-ppu:read-palette (nes-ppu n) (logand addr #x1f)))) (defun ppu-to-palette-write (n) (lambda (addr val) (declare ((unsigned-byte 16) addr) ((unsigned-byte 8) val) (nes n)) (NES-ppu:write-palette (nes-ppu n) (logand addr #x1f) val))) (defun ppu-to-mapper-read (n) (lambda (addr) (declare ((unsigned-byte 16) addr) (nes n)) (aref (if (arrayp (NES-cartridge:cartridge-chr-ram (nes-cart n))) (the (simple-array (unsigned-byte 8) 1) (NES-cartridge:cartridge-chr-ram (nes-cart n))) (the (simple-array (unsigned-byte 8) 1) (NES-cartridge:cartridge-chr-rom (nes-cart n)))) addr))) (defun ppu-to-mapper-write (n) (lambda (addr val) (declare ((unsigned-byte 16) addr) ((unsigned-byte 8) val) (nes n)) (setf (aref (if (arrayp (NES-cartridge:cartridge-chr-ram (nes-cart n))) (the (simple-array (unsigned-byte 8) 1) (NES-cartridge:cartridge-chr-ram (nes-cart n))) (the (simple-array (unsigned-byte 8) 1) (NES-cartridge:cartridge-chr-rom (nes-cart n)))) addr) val))) (defun cpu-to-cpu-read (n) (lambda (addr) (declare ((unsigned-byte 16) addr) (nes n)) (aref (6502-cpu:cpu-memory (nes:nes-cpu n)) (mod addr #x800)))) (defun cpu-to-cpu-write (n) (lambda (addr val) (declare ((unsigned-byte 16) addr) ((unsigned-byte 8) val) (nes n)) (setf (aref (6502-cpu:cpu-memory (nes:nes-cpu n)) (mod addr #x800)) val))) (defun cpu-to-cart-read (n) (lambda (addr) (declare ((unsigned-byte 16) addr) (nes n)) (let ((prg (NES-cartridge:cartridge-prg-rom (nes-cart n)))) (declare ((simple-array (unsigned-byte 8) 1) prg)) (aref prg (mod addr (array-dimension prg 0)))))) (defun cpu-to-cart-write (n) (lambda (addr val) (declare ((unsigned-byte 16) addr) ((unsigned-byte 8) val) (nes n)) (let ((prg (NES-cartridge:cartridge-prg-rom (nes-cart n)))) (declare ((simple-array (unsigned-byte 8) 1) prg)) (setf (aref prg (mod addr (array-dimension prg 0))) val)))) (defun cpu-to-ppu-read (n) (lambda (addr) (declare ((unsigned-byte 16) addr) (nes n)) ;If oam, don't mod the address (if (= addr #x4014) (NES-ppu:read-register (nes-ppu n) addr) (NES-ppu:read-register (nes-ppu n) (mod addr 8))))) (defun cpu-to-ppu-write (n) (lambda (addr val) (declare ((unsigned-byte 16) addr) ((unsigned-byte 8) val) (nes n)) (if (= addr #x4014) (NES-ppu:write-register (nes-ppu n) addr val) (NES-ppu:write-register (nes-ppu n) (mod addr 8) val)))) (defun cpu-to-io-read (n) (lambda (addr) (declare ((unsigned-byte 16) addr) (nes n)) (if (or (= addr #x4016) (= addr #x4017)) (NES-controller:read-controller (aref (nes-controllers n) (mod addr 2))) 0))) (defun cpu-to-io-write (n) (lambda (addr val) (declare ((unsigned-byte 16) addr) ((unsigned-byte 8) val) (nes n)) (if (or (= addr #x4016) (= addr #x4017)) (NES-controller:write-controller (aref (nes-controllers n) (mod addr 2)) val) 0))) (defun map-memory (n) (setf (NES-ppu:ppu-trigger-nmi-callback (nes-ppu n)) (6502-cpu:trigger-nmi-callback (nes-cpu n))) (setf (NES-ppu:ppu-oam-dma-callback (nes-ppu n)) (lambda (addr) (6502-cpu:read-cpu (nes-cpu n) addr))) (setf (NES-ppu:ppu-oam-stall-adder (nes-ppu n)) (6502-cpu:add-to-stall (nes-cpu n))) (setf (aref (NES-ppu:ppu-memory-get (nes-ppu n)) 0) (ppu-to-mapper-read n)) (setf (aref (NES-ppu:ppu-memory-set (nes-ppu n)) 0) (ppu-to-mapper-write n)) (setf (aref (NES-ppu:ppu-memory-get (nes-ppu n)) 1) (ppu-to-name-table-read n)) (setf (aref (NES-ppu:ppu-memory-set (nes-ppu n)) 1) (ppu-to-name-table-write n)) (setf (aref (NES-ppu:ppu-memory-get (nes-ppu n)) 2) (ppu-to-palette-read n)) (setf (aref (NES-ppu:ppu-memory-set (nes-ppu n)) 2) (ppu-to-palette-write n)) (setf (aref (6502-cpu:cpu-memory-get (nes-cpu n)) 0) (cpu-to-cpu-read n)) (setf (aref (6502-cpu:cpu-memory-set (nes-cpu n)) 0) (cpu-to-cpu-write n)) (setf (aref (6502-cpu:cpu-memory-get (nes-cpu n)) 1) (cpu-to-ppu-read n)) (setf (aref (6502-cpu:cpu-memory-set (nes-cpu n)) 1) (cpu-to-ppu-write n)) (setf (aref (6502-cpu:cpu-memory-get (nes-cpu n)) 2) (cpu-to-io-read n)) (setf (aref (6502-cpu:cpu-memory-set (nes-cpu n)) 2) (cpu-to-io-write n)) (setf (aref (6502-cpu:cpu-memory-get (nes-cpu n)) 5) (cpu-to-cart-read n)) (setf (NES-controller:controller-buttons-callback (aref (nes-controllers n) 0)) #'get-buttons))
5,985
Common Lisp
.lisp
114
44.973684
156
0.602836
samanthadoran/potential-disco
233
19
1
GPL-3.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
2b3045928c7477e562219e51a3023ef9ce282f97539213ba1777d5c2cf0113b3
282
[ -1 ]
283
console.lisp
samanthadoran_potential-disco/console.lisp
(defpackage #:NES-console (:nicknames #:nes) (:use :cl :6502-cpu :NES-cartridge :NES-ppu :NES-controller) (:export #:make-nes #:console-on #:nes-cpu #:nes-ppu #:nes-cart #:step-nes #:step-frame #:setup-and-emulate #:render-nes #:read-rom)) (in-package :NES-console) (declaim (optimize (speed 3) (safety 1))) (defstruct nes "A model nes" (cpu (6502-cpu:make-cpu)) (cart (NES-cartridge:make-cartridge)) (ppu (NES-ppu:make-ppu)) (controllers (make-array 2 :initial-contents `(,(nes-controller:make-controller) ,(nes-controller:make-controller))) :type (simple-array NES-controller:controller 1))) (defvar mirror-lookup (make-array 20 :element-type '(unsigned-byte 2) :initial-contents '(0 0 1 1 0 1 0 1 0 0 0 0 1 1 1 1 0 1 2 3))) (defun read-rom (n rom-name) (declare (nes n)) (setf (nes-cart n) (NES-cartridge:load-cartridge rom-name))) (defun console-on (n) (declare (nes n)) (NES-ppu:reset-ppu (nes-ppu n)) (map-memory n) (6502-cpu:power-on (nes-cpu n))) (defun step-nes (n steps) (declare (nes n) ((unsigned-byte 32) steps)) (loop for s from 1 to steps do (let ((cycles (* 3 (the (unsigned-byte 8)(6502-CPU:step-cpu (nes-cpu n)))))) (declare ((unsigned-byte 8) cycles)) (NES-ppu:step-ppu (nes-ppu n) cycles)))) (defun step-frame (n) (declare (nes n)) (let ((frame (NES-ppu:ppu-frame (nes-ppu n))) (controller (aref (the (simple-array nes-controller:controller 1)(nes-controllers n)) 0))) (declare ((unsigned-byte 16) frame)) (loop do (progn (when (not (= frame (NES-ppu:ppu-frame (nes-ppu n)))) (return)) (nes-controller:update-controller controller) (step-nes n 1))))) (defun test-render-clear (renderer) (sdl2:set-render-draw-color renderer 0 0 0 255) (sdl2:render-clear renderer)) (defun render-nes (front renderer tex rect) (multiple-value-bind (pixels pitch) (sdl2:lock-texture tex rect) (loop for y from 0 to (- NES-ppu:screen-height 1) do (loop for x from 0 to (- NES-ppu:screen-width 1) do (let* ((color (aref (the (simple-array NES-ppu:color 1) front) (+ (* y NES-ppu:screen-width) x))) (r (color-r color)) (g (color-g color)) (b (color-b color)) (col (logior (ash #xFF 24) (ash r 16) (ash g 8) (ash b 0)))) (setf (sb-sys:sap-ref-32 pixels (* 4 (+ (* y NES-ppu:screen-width) x))) col)))) (sdl2:update-texture tex rect pixels pitch) (sdl2:unlock-texture tex)) (sdl2:render-copy renderer tex :dest-rect rect)) (defun setup-and-emulate (cart-name) (let ((a (make-nes))) (read-rom a cart-name) (console-on a) (sdl2:with-init (:everything) (sdl2:with-window (win :title "Potential-Disco" :w NES-ppu:screen-width :h NES-ppu:screen-height :flags '(:shown)) (sdl2:with-renderer (renderer win :flags '(:accelerated)) (let* ((tex (sdl2:create-texture renderer :argb8888 :streaming NES-ppu:screen-width NES-ppu:screen-height)) (rect (sdl2:make-rect 0 0 NES-ppu:screen-width NES-ppu:screen-height))) (sdl2:with-event-loop (:method :poll) (:keyup (:keysym keysym) (when (sdl2:scancode= (sdl2:scancode-value keysym) :scancode-escape) (sdl2:push-event :quit))) (:idle () ;Update Controller (step-frame a) (test-render-clear renderer) (render-nes (NES-ppu:ppu-front (nes-ppu a)) renderer tex rect) (sdl2:render-present renderer)) (:quit () t))))))))
3,757
Common Lisp
.lisp
94
32.446809
120
0.59688
samanthadoran/potential-disco
233
19
1
GPL-3.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
f43e6799637fa170656b74b43612adc825666f745dba45d74c1e3804989868e5
283
[ -1 ]
284
cpu.lisp
samanthadoran_potential-disco/cpu.lisp
(defpackage #:6502-cpu (:nicknames #:cpu) (:use :cl) (:export #:make-cpu #:reset #:power-on #:cpu-cycles #:cpu-accumulator #:cpu-pc #:cpu-memory #:step-pc #:fetch #:step-cpu #:make-instruction #:cpu-memory-get #:cpu-memory-set #:to-signed-byte-8 #:read-cpu #:trigger-nmi-callback #:trigger-irq-callback #:add-to-stall)) (in-package :6502-cpu) (declaim (optimize (speed 3) (safety 1))) (defvar instructions (make-hash-table :test 'equal)) (defvar cycles-per-instruction (make-array 256 :element-type '(unsigned-byte 8) :initial-contents '(7 6 2 8 3 3 5 5 3 2 2 2 4 4 6 6 2 5 2 8 4 4 6 6 2 4 2 7 4 4 7 7 6 6 2 8 3 3 5 5 4 2 2 2 4 4 6 6 2 5 2 8 4 4 6 6 2 4 2 7 4 4 7 7 6 6 2 8 3 3 5 5 3 2 2 2 3 4 6 6 2 5 2 8 4 4 6 6 2 4 2 7 4 4 7 7 6 6 2 8 3 3 5 5 4 2 2 2 5 4 6 6 2 5 2 8 4 4 6 6 2 4 2 7 4 4 7 7 2 6 2 6 3 3 3 3 2 2 2 2 4 4 4 4 2 6 2 6 4 4 4 4 2 5 2 5 5 5 5 5 2 6 2 6 3 3 3 3 2 2 2 2 4 4 4 4 2 5 2 5 4 4 4 4 2 4 2 4 4 4 4 4 2 6 2 8 3 3 5 5 2 2 2 2 4 4 6 6 2 5 2 8 4 4 6 6 2 4 2 7 4 4 7 7 2 6 2 8 3 3 5 5 2 2 2 2 4 4 6 6 2 5 2 8 4 4 6 6 2 4 2 7 4 4 7 7))) (defvar instruction-page-cycles (make-array 256 :element-type '(unsigned-byte 8) :initial-contents '(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 1 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 1 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 1 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 1 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 1 0 0 0 0 0 1 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 1 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 1 0 0 1 1 0 0))) (defvar instructions (make-hash-table :test 'equal)) (defstruct flags "Flag register" (carry nil) (zero nil) (interrupt nil) (bcd nil) (soft-interrupt nil) (unused T) (overflow nil) (negative nil)) (defstruct cpu "A model 6502" (cycles 0 :type (unsigned-byte 16)) (stall 0 :type (unsigned-byte 16)) (accumulator 0 :type (unsigned-byte 8)) (x 0 :type (unsigned-byte 8)) (y 0 :type (unsigned-byte 8)) (pc 0 :type (unsigned-byte 16)) (sp 0 :type (unsigned-byte 8)) (sr (make-flags) :type flags) (memory-get (make-array 6 :element-type 'function :initial-element (lambda ())) :type (simple-array function 1)) (memory-set (make-array 3 :element-type 'function :initial-element (lambda ())) :type (simple-array function 1)) (memory (make-array #x800 :element-type '(unsigned-byte 8)) :type (simple-array (unsigned-byte 8) 1)) (interrupt :none)) (defstruct instruction "6502 instruction" (unmasked-opcode 0 :type (unsigned-byte 8)) (opcode 0 :type (unsigned-byte 8)) (hi-byte 0 :type (unsigned-byte 8)) (lo-byte 0 :type (unsigned-byte 8)) (addressing-mode :implicit)) (defun add-to-stall (c) (lambda (to-add) (declare ((unsigned-byte 16) to-add) (cpu c)) (incf (cpu-stall c) to-add) (when (= (mod (cpu-cycles c) 2) 1) (incf (cpu-stall c))))) (defun trigger-nmi-callback (c) (declare (cpu c)) (lambda () (setf (cpu-interrupt c) :nmi))) (defun trigger-irq-callback (c) (declare (cpu c)) (lambda () (when (not (flags-interrupt (cpu-sr c))) (setf (cpu-interrupt c) :irq)))) (defun wrap-byte (val) (declare ((signed-byte 64) val)) (ldb (byte 8 0) val)) (defun wrap-word (val) (declare ((signed-byte 64) val)) (ldb (byte 16 0) val)) (defun make-byte-from-flags (f) (declare (flags f)) (logior (if (flags-carry f) 1 0) (ash (if (flags-zero f) 1 0) 1) (ash (if (flags-interrupt f) 1 0) 2) (ash (if (flags-bcd f) 1 0) 3) (ash (if (flags-soft-interrupt f) 1 0) 4) (ash (if (flags-unused f) 1 0) 5) (ash (if (flags-overflow f) 1 0) 6) (ash (if (flags-negative f) 1 0) 7))) (defun make-flags-from-byte (val) (declare ((unsigned-byte 8) val)) (make-flags :carry (ldb-test (byte 1 0) val) :zero (ldb-test (byte 1 1) val) :interrupt (ldb-test (byte 1 2) val) :bcd (ldb-test (byte 1 3) val) :soft-interrupt (ldb-test (byte 1 4) val) :unused (ldb-test (byte 1 5) val) :overflow (ldb-test (byte 1 6) val) :negative (ldb-test (byte 1 7) val))) (defun to-signed-byte-8 (val) (declare ((unsigned-byte 8) val)) (if (ldb-test (byte 1 7) val) (* -1 (wrap-byte (1+ (lognot val)))) val)) (defun make-word-from-bytes (hi lo) (declare ((unsigned-byte 8) hi lo)) (the (unsigned-byte 16) (logior (ash hi 8) lo))) (defun pages-differ (a b) (declare ((unsigned-byte 16) a b)) (/= (ldb (byte 8 8) a) (ldb (byte 8 8) b))) (defun read-cpu (c addr) (declare (cpu c) ((unsigned-byte 16) addr)) "Reads the memory at the specified address" (cond ;CPU internal memory ((<= addr #x1FFF) (funcall (aref (cpu-memory-get c) 0) addr)) ;PPU ((<= addr #x3FFF) (funcall (aref (cpu-memory-get c) 1) addr)) ;APU and IO Registers ((<= addr #x401F) (funcall (aref (cpu-memory-get c) 2) addr)) ;Mapper Registers ((<= addr #x5FFF) (progn (print "Reads from cpu to mapper unimplemented....") 0)) ;SAVE RAM ((<= addr #x7FFF) (progn (print "Reads from cpu to save ram unimplemented....") 0)) ;PRG ROM ((<= addr #xFFFF) (funcall (aref (cpu-memory-get c) 5) addr)))) (defun read16 (c addr bug) (declare (cpu c) ((unsigned-byte 16) addr)) "Emulate indirect bugs..." (let ((lo (read-cpu c addr)) (hi (read-cpu c (wrap-word (1+ addr)))) (hi-bug (read-cpu c (logior (logand addr #xFF00) (wrap-byte (1+ addr)))))) (the (unsigned-byte 16) (make-word-from-bytes (if bug hi-bug hi) lo)))) (defun write-cpu (c addr val) (declare (cpu c) ((unsigned-byte 16) addr) ((unsigned-byte 8) val)) (cond ;CPU internal memory ((<= addr #x1FFF) (funcall (aref (cpu-memory-set c) 0) addr val)) ;PPU Registers ((<= addr #x3FFF) (funcall (aref (cpu-memory-set c) 1) addr val)) ;Don't forget oam-dma ((= addr #x4014) (funcall (aref (cpu-memory-set c) 1) addr val)) ;APU and IO Registers ((<= addr #x401F) (funcall (aref (cpu-memory-set c) 2) addr val)) ;SAVE RAM ((and (<= addr #x7FFF) (>= addr #x6000)) (progn (print "Writes to save ram unimplemented...") 0)) (T 0))) (defun reset (c) (declare (cpu c)) "Reset state of cpu" (setf (cpu-sp c) (wrap-byte (- (cpu-sp c) 3))) (setf (flags-interrupt (cpu-sr c)) T)) (defun power-on (c) (declare (cpu c)) "Power on state of cpu" (setf (cpu-sr c) (make-flags :carry nil :zero nil :interrupt T :bcd nil :soft-interrupt T :unused T :overflow nil :negative nil)) (setf (cpu-sp c) #xFD) (setf (cpu-pc c) (read16 c #xFFFC nil))) (defun pull-stack (c) (declare (cpu c)) "Empty stack pull" (setf (cpu-sp c) (wrap-byte (1+ (cpu-sp c)))) (aref (cpu-memory c) (logior (cpu-sp c) #x100))) (defun push-stack (c val) (declare (cpu c) ((unsigned-byte 8) val)) "Put a value on the stack and then push it forwards" (setf (aref (cpu-memory c) (logior (cpu-sp c) #x100)) val) (setf (cpu-sp c) (wrap-byte (- (cpu-sp c) 1)))) (defun pull16 (c) (declare (cpu c)) "Pull twice and make a 16 bit address." (the (unsigned-byte 16) (logior (pull-stack c) (ash (pull-stack c) 8)))) (defun push16 (c val) (declare (cpu c) ((unsigned-byte 16) val)) "Push twice." (push-stack c (ldb (byte 8 8) val)) (push-stack c (ldb (byte 8 0) val))) (defun step-pc (c inst) (declare (cpu c) (instruction inst)) "Step the pc according to the addressing mode." (let ((mode (instruction-addressing-mode inst))) (setf (cpu-pc c) (wrap-word (+ (cpu-pc c) (case mode (:implicit 1) (:accumulator 1) (:immediate 2) (:zero-page 2) (:absolute 3) (:relative 2) (:indirect 3) (:zero-page-indexed-x 2) (:zero-page-indexed-y 2) (:absolute-indexed-x 3) (:absolute-indexed-y 3) (:indexed-indirect 2) (:indirect-indexed 2) (otherwise 1))))))) (defun set-zn (c val) (declare (cpu c) ((unsigned-byte 8) val)) "Sets the zero or negative flag" ;If zero, set the bit (setf (flags-zero (cpu-sr c)) (= val 0)) ;If the MSB is set, it's negative. (setf (flags-negative (cpu-sr c)) (ldb-test (byte 1 7) val))) (defun get-address (c inst) (declare (cpu c) (instruction inst)) "Get the address the instruction is talking about" (let ((mode (instruction-addressing-mode inst)) (lo-byte (instruction-lo-byte inst)) (hi-byte (instruction-hi-byte inst))) (declare ((unsigned-byte 8) lo-byte hi-byte)) (case mode ;Somewhere in zero page... (:zero-page lo-byte) ;Super simple, just make a two byte address from the supplied two bytes (:absolute (make-word-from-bytes hi-byte lo-byte)) ;Treat the low byte as though it were signed, use it as an offset for PC (:relative (wrap-word (+ (cpu-pc c) (to-signed-byte-8 lo-byte)))) ;Read the address contained at the supplied two byte address. (:indirect (let ((ptr-addr (make-word-from-bytes hi-byte lo-byte))) (read16 c ptr-addr T))) ;Add the x register to the low-byte for zero-page addressing (:zero-page-indexed-x (wrap-byte (+ lo-byte (cpu-x c)))) ;Add the y register to the low-byte for zero-page addressing (:zero-page-indexed-y (wrap-byte (+ lo-byte (cpu-y c)))) ;Add the x register to the supplied two byte address (:absolute-indexed-x (wrap-word (+ (make-word-from-bytes hi-byte lo-byte) (cpu-x c)))) ;Add the y register to the supplied two byte address (:absolute-indexed-y (wrap-word (+ (make-word-from-bytes hi-byte lo-byte) (cpu-y c)))) ;Get the address contained at lo-byte + x (:indexed-indirect (read16 c (wrap-byte (+ lo-byte (cpu-x c))) T)) ;Get the address containted at lo-byte + y (:indirect-indexed (wrap-word (+ (cpu-y c) (read16 c lo-byte T)))) (otherwise 0)))) (defun get-value (c inst) (declare (cpu c) (instruction inst)) "Get the value from an instruction" (case (instruction-addressing-mode inst) (:immediate (instruction-lo-byte inst)) (:accumulator (cpu-accumulator c)) (otherwise (read-cpu c (get-address c inst))))) (defun fetch (c) (declare (cpu c)) "Fetch the next instruction from memory" (make-instruction :unmasked-opcode (read-cpu c (cpu-pc c)) :lo-byte (read-cpu c (wrap-word (+ (cpu-pc c) 1))) :hi-byte (read-cpu c (wrap-word (+ (cpu-pc c) 2))))) (defun determine-addressing-mode (opcode) (declare ((unsigned-byte 8) opcode)) ;We really only care about the opcode as: AAA???CC ;BBB is normally just addressing mode, which we store in the intstruction (let ((cc (ldb (byte 2 0) opcode)) (bbb (ldb (byte 3 2) opcode)) (aaa (ldb (byte 3 5) opcode))) (case cc (0 (case bbb (0 :immediate) (1 :zero-page) (3 :absolute) (5 :zero-page-indexed-x) (7 :absolute-indexed-x))) (1 (case bbb (0 :indexed-indirect) (1 :zero-page) (2 :immediate) (3 :absolute) (4 :indirect-indexed) (5 :zero-page-indexed-x) (6 :absolute-indexed-y) (7 :absolute-indexed-x))) (2 (case bbb (0 :immediate) (1 :zero-page) (2 :accumulator) (3 :absolute) (5 (if (member aaa '(4 5)) :zero-page-indexed-y :zero-page-indexed-x)) (7 (if (= aaa 5) :absolute-indexed-y :absolute-indexed-x)))) (otherwise (print "Bad opcode"))))) ;TODO: Test this somehow... (defun decode (inst) (declare (instruction inst)) "Decodes the opcode and returns a constructed instruction." (let* ((opcode (instruction-unmasked-opcode inst)) (lo-byte (instruction-lo-byte inst)) (hi-byte (instruction-hi-byte inst)) (masked-opcode (logand opcode #xE3)) (addressing-mode (determine-addressing-mode opcode))) ;If it is a special case, modify (cond ((member opcode '(#x10 #x30 #x50 #x70 #x90 #xB0 #xD0 #xF0)) (progn (setf addressing-mode :relative) (setf masked-opcode opcode))) ((member opcode '(#x20 #x2C #x4C)) (progn (setf addressing-mode :absolute) (setf masked-opcode opcode))) ((= opcode #x6C) (progn (setf addressing-mode :indirect) (setf masked-opcode opcode))) ((= opcode #x24) (progn (setf addressing-mode :zero-page) (setf masked-opcode opcode))) ((member opcode '(#x08 #x28 #x48 #x68 #x88 #xA8 #xC8 #xE8 #x18 #x38 #x58 #x78 #x98 #xB8 #xD8 #xF8 #x8A #x9A #xAA #xBA #xCA #xEA #x00 #x40 #x60)) (progn (setf addressing-mode :implicit) (setf masked-opcode opcode)))) ;Make the instruction (make-instruction :addressing-mode addressing-mode :opcode masked-opcode :unmasked-opcode opcode :hi-byte hi-byte :lo-byte lo-byte))) (defun instruction-cycles (c inst) (declare (cpu c) (instruction inst)) (let* ((address (get-address c inst)) (mode (instruction-addressing-mode inst)) (unmasked (instruction-unmasked-opcode inst)) (page-cycles (aref (the (simple-array (unsigned-byte 8) 1) instruction-page-cycles) unmasked))) (declare ((unsigned-byte 16) address) ((unsigned-byte 8) unmasked page-cycles) (type (simple-array (unsigned-byte 8) 1) cycles-per-instruction)) (+ ;Get the number of cycles as per usual (aref cycles-per-instruction unmasked) ;Add page-cycles if we crossed a bound (case mode (:absolute-indexed-x (if (pages-differ address (wrap-word (- address (cpu-x c)))) page-cycles 0)) (:absolute-indexed-y (if (pages-differ address (wrap-word (- address (cpu-y c)))) page-cycles 0)) (:indirect-indexed (if (pages-differ address (wrap-word (- address (cpu-y c)))) page-cycles 0)) (otherwise 0))))) (defun execute (c inst) (declare (cpu c) (instruction inst)) (let ((cycles (instruction-cycles c inst)) (instruction (gethash (instruction-opcode inst) instructions))) (declare ((unsigned-byte 8) cycles) (function instruction)) (funcall instruction c inst) (setf (cpu-cycles c) (wrap-word (+ cycles (cpu-cycles c)))) cycles)) (defun nmi (c) (declare (cpu c)) (push16 c (cpu-pc c)) (php c nil) (setf (cpu-pc c) (read16 c #xFFFA nil)) (setf (flags-interrupt (cpu-sr c)) T) (setf (cpu-cycles c) (wrap-word (+ 7 (cpu-cycles c))))) (defun irq (c) (declare (cpu c)) (push16 c (cpu-pc c)) (php c nil) (setf (cpu-pc c) (read16 c #xFFFE nil)) (setf (flags-interrupt (cpu-sr c)) T) (setf (cpu-cycles c) (wrap-word (+ 7 (cpu-cycles c))))) (defun step-cpu (c) (declare (cpu c)) "Steps the cpu through an instruction, returns the number of cycles it took." (if (> (cpu-stall c) 0) (progn (decf (cpu-stall c)) 1) (progn (case (cpu-interrupt c) (:none 0) (:irq (irq c)) (:nmi (nmi c))) (setf (cpu-interrupt c) :none) (let ((inst (decode (fetch c)))) ;Remember to step the pc before execution. (step-pc c inst) (execute c inst)))))
15,851
Common Lisp
.lisp
455
29.068132
87
0.594023
samanthadoran/potential-disco
233
19
1
GPL-3.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
f6a89fb441704612c4d333070707caa3e23fa170f4b8b511f2a8f3a200c05db1
284
[ -1 ]
285
controller.lisp
samanthadoran_potential-disco/controller.lisp
(defpackage #:NES-controller (:nicknames #:controller) (:use #:cl) (:export #:make-controller #:read-controller #:write-controller #:update-controller #:controller #:controller-buttons-callback #:*keymap* #:get-buttons)) (in-package :NES-controller) (declaim (optimize (speed 3) (safety 1))) (defstruct controller (buttons (make-array 8 :element-type '(unsigned-byte 8) :initial-element 0) :type (simple-array (unsigned-byte 8) 1)) (index 0 :type (unsigned-byte 3)) (strobe 0 :type (unsigned-byte 1)) (buttons-callback (lambda()) :type function)) (defun read-controller (c) (declare (controller c)) (let ((value (aref (controller-buttons c) (controller-index c)))) (setf (controller-index c) (if (not (ldb-test (byte 1 0) (controller-strobe c))) (ldb (byte 3 0) (1+ (controller-index c))) 0)) value)) (defun write-controller (c val) (declare (controller c) ((unsigned-byte 8) val)) (when (ldb-test (byte 1 0) (setf (controller-strobe c) (ldb (byte 1 0) val))) (setf (controller-index c) 0))) (defun update-controller (c) (declare (controller c)) (when (ldb-test (byte 1 0) (controller-strobe c)) (setf (controller-buttons c) (the (simple-array (unsigned-byte 8) 1) (funcall (controller-buttons-callback c)))))) (defvar *keymap* '((:a . :scancode-left) (:b . :scancode-down) (:select . :scancode-grave) (:start . :scancode-tab) (:up . :scancode-w) (:down . :scancode-s) (:left . :scancode-a) (:right . :scancode-d)) "The mapping of the controller #1 buttons to SDL keycodes. Caveat Emptor, the button-names are for reference, the mapping is determined by the Order.") (defun get-buttons () (let ((buttons (make-array 8 :element-type '(unsigned-byte 8) :initial-element 0))) (loop :for index :from 0 :for (button-name . button-key) :in *keymap* :do (setf (aref buttons index) (if (sdl2:keyboard-state-p button-key) 1 0))) buttons))
2,083
Common Lisp
.lisp
55
32.636364
118
0.63236
samanthadoran/potential-disco
233
19
1
GPL-3.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
b99a9d19c589eb9ca36fb5699edfbf7c6c25fa99387153196ec47519255e6256
285
[ -1 ]
286
flagops.lisp
samanthadoran_potential-disco/instructions/flagops.lisp
(in-package :6502-cpu) (declaim (optimize (speed 3) (safety 1))) (defun sei (c inst) (declare (cpu c) (instruction inst) (ignore inst)) "SEI: set interrupt flag" (setf (flags-interrupt (cpu-sr c)) T)) (defun sec (c inst) (declare (cpu c) (instruction inst) (ignore inst)) "SEC: set carry flag" (setf (flags-carry (cpu-sr c)) T)) (defun clv (c inst) (declare (cpu c) (instruction inst) (ignore inst)) "CLV: clear overflow flag" (setf (flags-overflow (cpu-sr c)) nil)) (defun clc (c inst) (declare (cpu c) (instruction inst) (ignore inst)) "CLC: clear carry flag" (setf (flags-carry (cpu-sr c)) nil)) (defun cld (c inst) (declare (cpu c) (instruction inst) (ignore inst)) "Clear decimal flag" (setf (flags-bcd (cpu-sr c)) nil)) (defun sed (c inst) (declare (cpu c) (instruction inst) (ignore inst)) "Set decimal flag" (setf (flags-bcd (cpu-sr c)) T))
890
Common Lisp
.lisp
26
31.653846
52
0.668219
samanthadoran/potential-disco
233
19
1
GPL-3.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
1715aece5c80c28e0f4d85c3cc2527224ea33c709f1d71a4cfb6416a78c93d4c
286
[ -1 ]
287
arithmeticops.lisp
samanthadoran_potential-disco/instructions/arithmeticops.lisp
(in-package :6502-cpu) (declaim (optimize (speed 3) (safety 1))) (defun nop (c inst) (declare (cpu c) (instruction inst) (ignore c inst))) (defun adc (c inst) (declare (cpu c) (instruction inst)) (let* ((a (cpu-accumulator c)) (b (get-value c inst)) (carry (if (flags-carry (cpu-sr c)) 1 0)) (result (+ a b carry))) (declare ((unsigned-byte 8) a b carry)) (set-zn c (setf (cpu-accumulator c) (wrap-byte result))) (setf (flags-carry (cpu-sr c)) (> result 255)) (setf (flags-overflow (cpu-sr c)) (and (= (logand #x80 (logxor a b)) 0) (/= (logand #x80 (logxor a (cpu-accumulator c))) 0))))) (defun sbc (c inst) (declare (cpu c) (instruction inst)) (let* ((a (cpu-accumulator c)) (b (get-value c inst)) (carry (if (flags-carry (cpu-sr c)) 1 0)) (result (- a b (- 1 carry)))) (declare ((unsigned-byte 8) a b carry)) (set-zn c (setf (cpu-accumulator c) (wrap-byte result))) (setf (flags-carry (cpu-sr c)) (>= result 0)) (setf (flags-overflow (cpu-sr c)) (and (/= (logand #x80 (logxor a b)) 0) (/= (logand #x80 (logxor a (cpu-accumulator c))) 0))))) (defun asl (c inst) (declare (cpu c) (instruction inst)) "ASL: Shift left one bit" (let ((mode (instruction-addressing-mode inst)) (val (get-value c inst)) (addr (get-address c inst))) (declare ((unsigned-byte 8) val) ((unsigned-byte 16) addr)) (setf (flags-carry (cpu-sr c)) (ldb-test (byte 1 7) val)) (set-zn c (if (equal mode :accumulator) (setf (cpu-accumulator c) (wrap-byte (ash val 1))) (write-cpu c addr (wrap-byte (ash val 1))))))) (defun lsr (c inst) (declare (cpu c) (instruction inst)) "LSR:Shift one bit right" (let ((mode (instruction-addressing-mode inst)) (val (get-value c inst)) (addr (get-address c inst))) (declare ((unsigned-byte 8) val) ((unsigned-byte 16) addr)) (setf (flags-carry (cpu-sr c)) (ldb-test (byte 1 0) val)) (set-zn c (if (equal mode :accumulator) (setf (cpu-accumulator c) (wrap-byte (ash val -1))) (write-cpu c addr (wrap-byte (ash val -1))))))) (defun rol (c inst) (declare (cpu c) (instruction inst)) "ROL: Rotate all bits left" (let ((mode (instruction-addressing-mode inst)) (val (get-value c inst)) (addr (get-address c inst)) (carry (if (flags-carry (cpu-sr c)) 1 0))) (declare ((unsigned-byte 8) val carry) ((unsigned-byte 16) addr)) (setf (flags-carry (cpu-sr c)) (ldb-test (byte 1 7) val)) (set-zn c (if (equal mode :accumulator) (setf (cpu-accumulator c) (wrap-byte (logior carry (ash val 1)))) (write-cpu c addr (wrap-byte (logior carry (ash val 1)))))))) (defun ror (c inst) (declare (cpu c) (instruction inst)) "ROR: Rotate all bits rights" (let ((mode (instruction-addressing-mode inst)) (val (get-value c inst)) (addr (get-address c inst)) (carry (if (flags-carry (cpu-sr c)) 128 0))) (declare ((unsigned-byte 8) carry val) ((unsigned-byte 16) addr)) (setf (flags-carry (cpu-sr c)) (ldb-test (byte 1 0) val)) (set-zn c (if (equal mode :accumulator) (setf (cpu-accumulator c) (logior carry (ash val -1))) (write-cpu c addr (logior carry (ash val -1))))))) (defun ora (c inst) (declare (cpu c) (instruction inst)) "ORA: or value with accumulator" (let ((val (get-value c inst))) (declare ((unsigned-byte 8) val)) (set-zn c (setf (cpu-accumulator c) (logior val (cpu-accumulator c)))))) (defun eor (c inst) (declare (cpu c) (instruction inst)) "EOR: xor with accumulator" (let ((val (get-value c inst))) (declare ((unsigned-byte 8) val)) (set-zn c (setf (cpu-accumulator c) (logxor val (cpu-accumulator c)))))) (defun anda (c inst) (declare (cpu c) (instruction inst)) "ANDA: and value with accumulator" (let ((val (get-value c inst))) (declare ((unsigned-byte 8) val)) (set-zn c (setf (cpu-accumulator c) (logand val (cpu-accumulator c)))))) (defun bit-shadow (c inst) (declare (cpu c) (instruction inst)) "BIT: and value with accumulator, don't store." (let ((val (get-value c inst))) (declare ((unsigned-byte 8) val)) (set-zn c (logand val (cpu-accumulator c))) (setf (flags-negative (cpu-sr c)) (ldb-test (byte 1 7) val)) (setf (flags-overflow (cpu-sr c)) (ldb-test (byte 1 6) val)))) (defun cmp (c inst) (declare (cpu c) (instruction inst)) (let ((val (get-value c inst))) (declare ((unsigned-byte 8) val)) (setf (flags-carry (cpu-sr c)) (>= (cpu-accumulator c) val)) (set-zn c (wrap-byte (- (cpu-accumulator c) val))))) (defun cpy (c inst) (declare (cpu c) (instruction inst)) (let ((val (get-value c inst))) (declare ((unsigned-byte 8) val)) (setf (flags-carry (cpu-sr c)) (>= (cpu-y c) val)) (set-zn c (wrap-byte (- (cpu-y c) val))))) (defun cpx (c inst) (declare (cpu c) (instruction inst)) (let ((val (get-value c inst))) (declare ((unsigned-byte 8) val)) (setf (flags-carry (cpu-sr c)) (>= (cpu-x c) val)) (set-zn c (wrap-byte (- (cpu-x c) val))))) (defun dey (c inst) (declare (cpu c) (instruction inst) (ignore inst)) "DEY: Decrement y register" (set-zn c (setf (cpu-y c) (wrap-byte (- (cpu-y c) 1))))) (defun dex (c inst) (declare (cpu c) (instruction inst) (ignore inst)) "DEY: Decrement y register" (set-zn c (setf (cpu-x c) (wrap-byte (- (cpu-x c) 1))))) (defun dec (c inst) (declare (cpu c) (instruction inst)) (let ((val (get-value c inst)) (addr (get-address c inst))) (declare ((unsigned-byte 8) val) ((unsigned-byte 16) addr)) (set-zn c (write-cpu c addr (wrap-byte (- val 1)))))) (defun inc (c inst) (declare (cpu c) (instruction inst)) (let ((val (get-value c inst)) (addr (get-address c inst))) (declare ((unsigned-byte 8) val) ((unsigned-byte 16) addr)) (set-zn c (write-cpu c addr (wrap-byte (1+ val)))))) (defun inx (c inst) (declare (cpu c) (instruction inst) (ignore inst)) (set-zn c (setf (cpu-x c) (wrap-byte (1+ (cpu-x c)))))) (defun iny (c inst) (declare (cpu c) (instruction inst) (ignore inst)) (set-zn c (setf (cpu-y c) (wrap-byte (1+ (cpu-y c))))))
6,219
Common Lisp
.lisp
150
36.866667
99
0.610789
samanthadoran/potential-disco
233
19
1
GPL-3.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
2d9d9b512329e950a353b9ebac61a13e63b59e3e0324e7cf15f4d459e0452084
287
[ -1 ]
288
branchops.lisp
samanthadoran_potential-disco/instructions/branchops.lisp
(in-package :6502-cpu) (declaim (optimize (speed 3) (safety 1))) (defun brk (c inst) (declare (cpu c) (instruction inst) (ignore inst)) "BRK: cause nmi" (push16 c (wrap-word (1+ (cpu-pc c)))) (php c nil) (sei c nil) (setf (cpu-pc c) (read16 c #xFFFE nil))) (defun rti (c inst) (declare (cpu c) (instruction inst) (ignore inst)) "Return from interrupt" (setf (cpu-sr c) (make-flags-from-byte (logior #x20 (logand (pull-stack c) #xEF)))) (setf (cpu-pc c) (pull16 c))) (defun jsr (c inst) (declare (cpu c) (instruction inst)) "JSR: jump subroutine" (push16 c (wrap-word (- (cpu-pc c) 1))) (setf (cpu-pc c) (get-address c inst))) (defun jmp-absolute (c inst) (declare (cpu c) (instruction inst)) (setf (cpu-pc c) (get-address c inst))) (defun jmp-indirect (c inst) (declare (cpu c) (instruction inst)) (setf (cpu-pc c) (get-address c inst))) (defun rts (c inst) (declare (cpu c) (instruction inst) (ignore inst)) (setf (cpu-pc c) (wrap-word (1+ (the (unsigned-byte 16) (pull16 c)))))) (defun bpl (c inst) (declare (cpu c) (instruction inst)) (when (not (flags-negative (cpu-sr c))) ;Branch taken means increment cycles (setf (cpu-cycles c) (wrap-word (1+ (cpu-cycles c)))) (setf (cpu-pc c) (get-address c inst)))) (defun bmi (c inst) (declare (cpu c) (instruction inst)) (when (flags-negative (cpu-sr c)) ;Branch taken means increment cycles (setf (cpu-cycles c) (wrap-word (1+ (cpu-cycles c)))) (setf (cpu-pc c) (get-address c inst)))) (defun bcs (c inst) (declare (cpu c) (instruction inst)) (when (flags-carry (cpu-sr c)) ;Branch taken means increment cycles (setf (cpu-cycles c) (wrap-word (1+ (cpu-cycles c)))) (setf (cpu-pc c) (get-address c inst)))) (defun bvc (c inst) (declare (cpu c) (instruction inst)) (when (not (flags-overflow (cpu-sr c))) ;Branch taken means increment cycles (setf (cpu-cycles c) (wrap-word (1+ (cpu-cycles c)))) (setf (cpu-pc c) (get-address c inst)))) (defun bvs (c inst) (declare (cpu c) (instruction inst)) (when (flags-overflow (cpu-sr c)) ;Branch taken means increment cycles (setf (cpu-cycles c) (wrap-word (1+ (cpu-cycles c)))) (setf (cpu-pc c) (get-address c inst)))) (defun bcc (c inst) (declare (cpu c) (instruction inst)) (when (not (flags-carry (cpu-sr c))) (setf (cpu-cycles c) (wrap-word (1+ (cpu-cycles c)))) (setf (cpu-pc c) (get-address c inst)))) (defun bne (c inst) (declare (cpu c) (instruction inst)) (when (not (flags-zero (cpu-sr c))) ;Branch taken means increment cycles (setf (cpu-cycles c) (wrap-word (1+ (cpu-cycles c)))) (setf (cpu-pc c) (get-address c inst)))) (defun beq (c inst) (declare (cpu c) (instruction inst)) (when (flags-zero (cpu-sr c)) ;Branch taken means increment cycles (setf (cpu-cycles c) (wrap-word (1+ (cpu-cycles c)))) (setf (cpu-pc c) (get-address c inst))))
2,922
Common Lisp
.lisp
77
34.558442
73
0.642529
samanthadoran/potential-disco
233
19
1
GPL-3.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
8175a2bed1443515d65b13fe2c7f772bc1a720147456b5b7b6975e5e4322840d
288
[ -1 ]
289
instructions.lisp
samanthadoran_potential-disco/instructions/instructions.lisp
(in-package :6502-cpu) (setf (gethash #x00 instructions) #'brk) (setf (gethash #x01 instructions) #'ora) (setf (gethash #x02 instructions) #'asl) (setf (gethash #x08 instructions) #'php) (setf (gethash #x10 instructions) #'bpl) (setf (gethash #x18 instructions) #'clc) (setf (gethash #x20 instructions) #'jsr) (setf (gethash #x21 instructions) #'anda) (setf (gethash #x22 instructions) #'rol) (setf (gethash #x24 instructions) #'bit-shadow) (setf (gethash #x28 instructions) #'plp) (setf (gethash #x2C instructions) #'bit-shadow) (setf (gethash #x30 instructions) #'bmi) (setf (gethash #x38 instructions) #'sec) (setf (gethash #x40 instructions) #'rti) (setf (gethash #x4C instructions) #'jmp-absolute) (setf (gethash #x41 instructions) #'eor) (setf (gethash #x42 instructions) #'lsr) (setf (gethash #x48 instructions) #'pha) (setf (gethash #x50 instructions) #'bvc) (setf (gethash #x60 instructions) #'rts) (setf (gethash #x61 instructions) #'adc) (setf (gethash #x62 instructions) #'ror) (setf (gethash #x68 instructions) #'pla) (setf (gethash #x6C instructions) #'jmp-indirect) (setf (gethash #x70 instructions) #'bvs) (setf (gethash #x78 instructions) #'sei) (setf (gethash #x80 instructions) #'sty) (setf (gethash #x81 instructions) #'sta) (setf (gethash #x82 instructions) #'stx) (setf (gethash #x88 instructions) #'dey) (setf (gethash #x8A instructions) #'txa) (setf (gethash #x90 instructions) #'bcc) (setf (gethash #x98 instructions) #'tya) (setf (gethash #x9A instructions) #'txs) (setf (gethash #xA0 instructions) #'ldy) (setf (gethash #xA1 instructions) #'lda) (setf (gethash #xA2 instructions) #'ldx) (setf (gethash #xA8 instructions) #'tay) (setf (gethash #xAA instructions) #'tax) (setf (gethash #xB0 instructions) #'bcs) (setf (gethash #xB8 instructions) #'clv) (setf (gethash #xBA instructions) #'tsx) (setf (gethash #xC0 instructions) #'cpy) (setf (gethash #xC1 instructions) #'cmp) (setf (gethash #xC2 instructions) #'dec) (setf (gethash #xC8 instructions) #'iny) (setf (gethash #xCA instructions) #'dex) (setf (gethash #xD0 instructions) #'bne) (setf (gethash #xD8 instructions) #'cld) (setf (gethash #xE0 instructions) #'cpx) (setf (gethash #xE1 instructions) #'sbc) (setf (gethash #xE2 instructions) #'inc) (setf (gethash #xE8 instructions) #'inx) (setf (gethash #xEA instructions) #'nop) (setf (gethash #xF0 instructions) #'beq) (setf (gethash #xF8 instructions) #'sed)
2,394
Common Lisp
.lisp
58
40.258621
49
0.727195
samanthadoran/potential-disco
233
19
1
GPL-3.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
3a7fbce752a550e7105a3a2a05e784c2f6c0d5f133e760d1571a1643934d3e69
289
[ -1 ]
290
loadstoreops.lisp
samanthadoran_potential-disco/instructions/loadstoreops.lisp
(in-package :6502-cpu) (declaim (optimize (speed 3) (safety 1))) (defun ldy (c inst) (declare (cpu c) (instruction inst)) "LDY. Load value to y" (set-zn c (setf (cpu-y c) (get-value c inst)))) (defun lda (c inst) (declare (cpu c) (instruction inst)) "LDA. Load value to accumulator" (set-zn c (setf (cpu-accumulator c) (get-value c inst)))) (defun ldx (c inst) (declare (cpu c) (instruction inst)) "LDX. Load value to cpu-x" (set-zn c (setf (cpu-x c) (get-value c inst)))) (defun sty (c inst) (declare (cpu c) (instruction inst)) (write-cpu c (get-address c inst) (cpu-y c))) (defun sta (c inst) (declare (cpu c) (instruction inst)) (write-cpu c (get-address c inst) (cpu-accumulator c))) (defun stx (c inst) (declare (cpu c) (instruction inst)) (write-cpu c (get-address c inst) (cpu-x c))) (defun tax (c inst) (declare (cpu c) (instruction inst) (ignore inst)) "TAX. Transfer accumulator to x" (set-zn c (setf (cpu-x c) (cpu-accumulator c)))) (defun tay (c inst) (declare (cpu c) (instruction inst) (ignore inst)) "TAY. Transfer accumulator to y" (set-zn c (setf(cpu-y c) (cpu-accumulator c)))) (defun txa (c inst) (declare (cpu c) (instruction inst) (ignore inst)) "TXA. Transfer x to accumulator" (set-zn c (setf (cpu-accumulator c) (cpu-x c)))) (defun tya (c inst) (declare (cpu c) (instruction inst) (ignore inst)) "TYA. Transfer y to accumulator" (set-zn c (setf (cpu-accumulator c) (cpu-y c)))) (defun tsx (c inst) (declare (cpu c) (instruction inst) (ignore inst)) "TSX. Transfer stack to x" (set-zn c (setf (cpu-x c) (cpu-sp c)))) (defun txs (c inst) (declare (cpu c) (instruction inst) (ignore inst)) "TXS. Transfer x to stack" (setf (cpu-sp c) (cpu-x c))) (defun php (c inst) (declare (cpu c) (ignore inst)) (push-stack c (logior #x10 (the (unsigned-byte 8)(make-byte-from-flags (cpu-sr c)))))) (defun pha (c inst) (declare (cpu c) (instruction inst) (ignore inst)) (push-stack c (cpu-accumulator c))) (defun pla (c inst) (declare (cpu c) (instruction inst) (ignore inst)) (set-zn c (setf (cpu-accumulator c) (pull-stack c)))) (defun plp (c inst) (declare (cpu c) (instruction inst) (ignore inst)) (setf (cpu-sr c) (make-flags-from-byte (logior #x20 (logand #xEF (pull-stack c))))))
2,293
Common Lisp
.lisp
59
36.20339
88
0.662308
samanthadoran/potential-disco
233
19
1
GPL-3.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
ac690e7946a8c823923715195b257c0b19a73d7750c9325403006a731209f241
290
[ -1 ]
291
console.asd
samanthadoran_potential-disco/console.asd
(in-package #:asdf-user) (defsystem #:console :depends-on (#:sdl2) :components ((:file "cpu") (:file "console" :depends-on ("cpu" "cartridge" "ppu" "controller")) (:file "mmu" :depends-on ("controller" "console")) (:file "ppu") (:file "controller") (:file "cartridge") (:file "instructions/arithmeticops") (:file "instructions/branchops") (:file "instructions/flagops") (:file "instructions/loadstoreops") (:file "instructions/instructions")))
599
Common Lisp
.asd
14
30.714286
83
0.527397
samanthadoran/potential-disco
233
19
1
GPL-3.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
ae338b2ebb1344f99e854079ef267776e977fe02675c8d78c636146e553cb039
291
[ -1 ]
319
gdk-pixbuf2.lisp
bohonghuang_cl-gtk4/gdk-pixbuf2.lisp
(cl:defpackage gdk-pixbuf2 (:use) (:nicknames #:gdk-pixbuf) (:export #:*ns*)) (in-package #:gdk-pixbuf2) (gir-wrapper:define-gir-namespace "GdkPixbuf" "2.0")
166
Common Lisp
.lisp
6
25.333333
52
0.689873
bohonghuang/cl-gtk4
213
9
23
LGPL-3.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
2c448611eb994dda0bf1d7fd90950698f7a163dbbb4bf35e49731de455bc02ef
319
[ -1 ]
320
webkit.lisp
bohonghuang_cl-gtk4/webkit.lisp
;;;; webkit.lisp ;;;; Copyright (C) 2022-2023 Bohong Huang ;;;; ;;;; This program is free software: you can redistribute it and/or modify ;;;; it under the terms of the GNU Lesser General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; This program is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;;; GNU Lesser General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU Lesser General Public License ;;;; along with this program. If not, see <https://www.gnu.org/licenses/>. (cl:defpackage webkit (:use) (:nicknames #:webkit) (:export #:*ns*)) (cl:in-package #:webkit) (gir-wrapper:define-gir-namespace "WebKit" "6.0")
910
Common Lisp
.lisp
21
41.857143
80
0.724294
bohonghuang/cl-gtk4
213
9
23
LGPL-3.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
b93a582a82eafe11f53e5ddd1d93f119fe2797dcb4774bdb21cfe92d511b6105
320
[ -1 ]
321
sourceview.lisp
bohonghuang_cl-gtk4/sourceview.lisp
;;;; sourceview.lisp ;;;; Copyright (C) 2022-2023 Bohong Huang ;;;; ;;;; This program is free software: you can redistribute it and/or modify ;;;; it under the terms of the GNU Lesser General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; This program is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;;; GNU Lesser General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU Lesser General Public License ;;;; along with this program. If not, see <https://www.gnu.org/licenses/>. (cl:defpackage gtksourceview (:use) (:nicknames #:sourceview) (:export #:*ns*)) (in-package #:sourceview) (gir-wrapper:define-gir-namespace "GtkSource" "5")
927
Common Lisp
.lisp
21
42.666667
80
0.731707
bohonghuang/cl-gtk4
213
9
23
LGPL-3.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
fc78cbdf78f9a793f63a0b6b8a744b6867111d79cf0284056944830611914968
321
[ -1 ]
322
gtk4.lisp
bohonghuang_cl-gtk4/gtk4.lisp
;;;; gtk4.lisp ;;;; Copyright (C) 2022-2023 Bohong Huang ;;;; ;;;; This program is free software: you can redistribute it and/or modify ;;;; it under the terms of the GNU Lesser General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; This program is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;;; GNU Lesser General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU Lesser General Public License ;;;; along with this program. If not, see <https://www.gnu.org/licenses/>. (defpackage gtk4 (:use #:cl) (:nicknames #:gtk) (:import-from #:gio #:*application*) (:import-from #:gir #:property) (:export #:*ns* #:*application* #:property)) (in-package #:gtk4) (eval-when (:execute :compile-toplevel :load-toplevel) (setf gir-wrapper:*quoted-name-alist* '((("TextBuffer" . "get_insert") . text-buffer-get-insert) (("Gesture" . "group") . group-gestures) (("Widget" . "is_sensitive") . widget-is-sensitive-p) (("Widget" . "is_visible") . widget-is-visible-p) (("EntryBuffer" . "set_text")) (("TextBuffer" . "set_text"))))) (gir-wrapper:define-gir-namespace "Gtk" "4.0") (eval-when (:execute :compile-toplevel :load-toplevel) (setf gir-wrapper:*quoted-name-alist* nil)) (defun (setf entry-buffer-text) (value instance) (declare (type string value)) (gir:invoke (instance 'set-text) value -1)) (export 'entry-buffer-text) (defun text-buffer-text (instance) (gir:invoke (instance 'get-text) (text-buffer-start-iter instance) (text-buffer-end-iter instance) t)) (defun (setf text-buffer-text) (value instance) (declare (type string value)) (gir:invoke (instance 'set-text) value -1)) (export 'text-buffer-text) (defun (setf widget-margin-all) (value instance) (setf (widget-margin-top instance) value (widget-margin-bottom instance) value (widget-margin-start instance) value (widget-margin-end instance) value)) (export 'widget-margin-all) (defun destroy-all-windows () "Destroy all windows currently open in the application." (mapcar (alexandria:compose #'window-close (alexandria:rcurry #'gobj:pointer-object 'window)) (glib:glist-list (application-windows gio:*application*)))) (defun destroy-all-windows-and-quit () "Destroy all windows currently open in the application and exit the application." (destroy-all-windows) (idle-add (lambda () (gio:application-quit gio:*application*)))) (defun read-return-value () (format *query-io* "~&Enter the return value: ") (finish-output *query-io*) (multiple-value-list (eval (read *query-io*)))) (defun attach-restarts (function) "Return a wrapper function with restarts attached to FUNCTION." (lambda (&rest args) (restart-case (apply function args) (return () :report "Return from current handler." (values nil)) (return-and-abort () :report "Return from current handler and abort the GTK application." (destroy-all-windows-and-quit) (values nil)) (return-value (value) :report "Return from current handler with specified value." :interactive read-return-value (values value)) (return-value-and-abort (value) :report "Return from current handler with specified value and abort the GTK application." :interactive read-return-value (destroy-all-windows-and-quit) (values value))))) (defun connect (g-object signal c-handler &key after swapped) "Similar to GIR:CONNECT, but calls to C-HANDLER will attach restarts to safely exit the application in case of errors." (gir:connect g-object signal (attach-restarts c-handler) :after after :swapped swapped)) (export 'connect) (defun idle-add (function &optional (priority glib:+priority-default+)) "Similar to GLIB:IDLE-ADD, but calls to C-HANDLER will attach restarts to safely exit the application in case of errors." (glib:idle-add (attach-restarts function) priority)) (export 'idle-add) (defun timeout-add (interval function &optional (priority glib:+priority-default+)) "Similar to GLIB:TIMEOUT-ADD, but calls to C-HANDLER will attach restarts to safely exit the application in case of errors." (glib:timeout-add interval (attach-restarts function) priority)) (export 'timeout-add) (defun timeout-add-seconds (interval function &optional (priority glib:+priority-default+)) "Similar to GLIB:TIMEOUT-ADD-SECONDS, but calls to C-HANDLER will attach restarts to safely exit the application in case of errors." (glib:timeout-add-seconds interval (attach-restarts function) priority)) (export 'timeout-add-seconds) (defmacro run-in-main-event-loop ((&key (priority 'glib:+priority-default+)) &body body) "Execute BODY in the main event loop of the GTK application with PRIORITY." `(idle-add (lambda () ,@body nil) ,priority)) (export 'run-in-main-event-loop) (setf (fdefinition 'application-run) (fdefinition 'gio:application-run)) (export 'application-run) (defun simple-break-symbol () (find-symbol "SIMPLE-BREAK" (cond ((member :slynk *features*) :slynk) ((member :swank *features*) :swank) (t (return-from simple-break-symbol nil))))) (defvar *simple-break-function* nil) (defun break-from-main-event-loop () "A custom BREAK function to break the GTK event loop and safely exit the GTK application." (if gio:*application* (glib:idle-add (lambda () (restart-case (funcall *simple-break-function*) (abort-application () :report "Abort the GTK application." (destroy-all-windows-and-quit))) (values nil)) glib:+priority-high+) (funcall *simple-break-function*))) (defun install-break-handler () "Install the custom BREAK function as the break handler." (when *simple-break-function* (error "Cannot install the break handler twice.")) (setf *simple-break-function* (fdefinition (simple-break-symbol)) (fdefinition (simple-break-symbol)) (fdefinition 'break-from-main-event-loop))) (export 'install-break-handler) (defun uninstall-break-handler () "Uninstall the custom BREAK function as the break handler." (unless *simple-break-function* (error "The break handler has not been installed.")) (setf (fdefinition (simple-break-symbol)) *simple-break-function* *simple-break-function* nil)) (export 'uninstall-break-handler) (when (simple-break-symbol) (unless *simple-break-function* (install-break-handler))) (defmacro define-main-window (binding &body body) "Bind the window created based on BINDING to a variable and make it the main window of the application. This window automatically runs during the execution of the application and is updated automatically with the compilation of DEFINE-APPLICATION form. This macro can only be used within the DEFINE-APPLICATION macro, otherwise an error will be signaled during expansion." (declare (ignore binding body)) (error "Cannot expand DEFINE-MAIN-WINDOW outside DEFINE-APPLICATION.")) (defmacro define-application ((&key (id "org.bohonghunag.cl-gtk4" id-specified-p) (flags gio:+application-flags-flags-none+) (name nil)) &body body) "Define the entry function NAME for the application, in which an application object is created using ID and the application flags FLAGS. In the BODY, variables and functions related to the application can be defined, so that they can be compiled simultaneously when compiling this toplevel form. Typically, DEFINE-MAIN-WINDOW is used in the BODY to define the main window, which enables interactive hot-reloading during compilation." (let ((prefix (if id-specified-p (format nil "~A." id) ""))) (let ((window (intern (format nil "*~AMAIN-WINDOW*" (string-upcase prefix)))) (content (intern (format nil "~AMAIN-WINDOW-CONTENT" (string-upcase prefix)))) (main (intern (format nil "~AMAIN" (string-upcase prefix))))) `(macrolet ((define-main-window (binding &body body) (destructuring-bind (win-bind win-form) (etypecase binding (list binding) (symbol (list (gensym) binding))) `(progn (defun ,',content (,win-bind) (declare (ignorable ,win-bind)) ,@body) (defun ,',main (&optional argv) (let ((app (make-application :application-id ,',id :flags ,',flags))) (connect app "activate" (lambda (app) (declare (ignore app)) (let ((win (setf ,',window ,win-form))) (,',content win) (connect win "destroy" (lambda (win) (declare (ignore win)) (setf ,',window nil)))))) (application-run app argv))) ,(when ',name `(setf (fdefinition ',',name) (fdefinition ',',main))) (eval-when (:load-toplevel) (when ,',window (idle-add (lambda () (,',content ,',window) nil)))))))) (defvar ,window nil) ,@body)))) (export '(define-application define-main-window))
10,211
Common Lisp
.lisp
193
42.963731
142
0.631621
bohonghuang/cl-gtk4
213
9
23
LGPL-3.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
8688bc0eadc3ec4ef1ce5524d727d0fa91fdf9dfb619b9083ced96b50ba01834
322
[ -1 ]
323
gdk4.lisp
bohonghuang_cl-gtk4/gdk4.lisp
;;;; gdk4.lisp ;;;; Copyright (C) 2022-2023 Bohong Huang ;;;; ;;;; This program is free software: you can redistribute it and/or modify ;;;; it under the terms of the GNU Lesser General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; This program is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;;; GNU Lesser General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU Lesser General Public License ;;;; along with this program. If not, see <https://www.gnu.org/licenses/>. (uiop:define-package gdk4 (:use) (:use-reexport #:gdk-pixbuf2) (:shadow #:*ns*) (:nicknames #:gdk) (:export #:*ns*)) (cl:in-package #:gdk4) (cl:eval-when (:execute :compile-toplevel :load-toplevel) (cl:setf gir-wrapper:*quoted-name-alist* '(("KEY_a" . |+KEY-a+|) ("KEY_ae" . |+KEY-ae+|) ("KEY_aacute" . |+KEY-aacute+|) ("KEY_abelowdot" . |+KEY-abelowdot+|) ("KEY_abreve" . |+KEY-abreve+|) ("KEY_abreveacute" . |+KEY-abreveacute+|) ("KEY_abrevebelowdot" . |+KEY-abrevebelowdot+|) ("KEY_abrevegrave" . |+KEY-abrevegrave+|) ("KEY_abrevehook" . |+KEY-abrevehook+|) ("KEY_abrevetilde" . |+KEY-abrevetilde+|) ("KEY_acircumflex" . |+KEY-acircumflex+|) ("KEY_acircumflexacute" . |+KEY-acircumflexacute+|) ("KEY_acircumflexbelowdot" . |+KEY-acircumflexbelowdot+|) ("KEY_acircumflexgrave" . |+KEY-acircumflexgrave+|) ("KEY_acircumflexhook" . |+KEY-acircumflexhook+|) ("KEY_acircumflextilde" . |+KEY-acircumflextilde+|) ("KEY_adiaeresis" . |+KEY-adiaeresis+|) ("KEY_agrave" . |+KEY-agrave+|) ("KEY_ahook" . |+KEY-ahook+|) ("KEY_amacron" . |+KEY-amacron+|) ("KEY_aogonek" . |+KEY-aogonek+|) ("KEY_aring" . |+KEY-aring+|) ("KEY_Armenian_at" . |+KEY-ARMENIAN-at+|) ("KEY_Armenian_ayb" . |+KEY-ARMENIAN-ayb+|) ("KEY_Armenian_ben" . |+KEY-ARMENIAN-ben+|) ("KEY_Armenian_cha" . |+KEY-ARMENIAN-cha+|) ("KEY_Armenian_da" . |+KEY-ARMENIAN-da+|) ("KEY_Armenian_dza" . |+KEY-ARMENIAN-dza+|) ("KEY_Armenian_e" . |+KEY-ARMENIAN-e+|) ("KEY_Armenian_fe" . |+KEY-ARMENIAN-fe+|) ("KEY_Armenian_ghat" . |+KEY-ARMENIAN-ghat+|) ("KEY_Armenian_gim" . |+KEY-ARMENIAN-gim+|) ("KEY_Armenian_hi" . |+KEY-ARMENIAN-hi+|) ("KEY_Armenian_ho" . |+KEY-ARMENIAN-ho+|) ("KEY_Armenian_ini" . |+KEY-ARMENIAN-ini+|) ("KEY_Armenian_je" . |+KEY-ARMENIAN-je+|) ("KEY_Armenian_ke" . |+KEY-ARMENIAN-ke+|) ("KEY_Armenian_ken" . |+KEY-ARMENIAN-ken+|) ("KEY_Armenian_khe" . |+KEY-ARMENIAN-khe+|) ("KEY_Armenian_lyun" . |+KEY-ARMENIAN-lyun+|) ("KEY_Armenian_men" . |+KEY-ARMENIAN-men+|) ("KEY_Armenian_nu" . |+KEY-ARMENIAN-nu+|) ("KEY_Armenian_o" . |+KEY-ARMENIAN-o+|) ("KEY_Armenian_pe" . |+KEY-ARMENIAN-pe+|) ("KEY_Armenian_pyur" . |+KEY-ARMENIAN-pyur+|) ("KEY_Armenian_ra" . |+KEY-ARMENIAN-ra+|) ("KEY_Armenian_re" . |+KEY-ARMENIAN-re+|) ("KEY_Armenian_se" . |+KEY-ARMENIAN-se+|) ("KEY_Armenian_sha" . |+KEY-ARMENIAN-sha+|) ("KEY_Armenian_tche" . |+KEY-ARMENIAN-tche+|) ("KEY_Armenian_to" . |+KEY-ARMENIAN-to+|) ("KEY_Armenian_tsa" . |+KEY-ARMENIAN-tsa+|) ("KEY_Armenian_tso" . |+KEY-ARMENIAN-tso+|) ("KEY_Armenian_tyun" . |+KEY-ARMENIAN-tyun+|) ("KEY_Armenian_vev" . |+KEY-ARMENIAN-vev+|) ("KEY_Armenian_vo" . |+KEY-ARMENIAN-vo+|) ("KEY_Armenian_vyun" . |+KEY-ARMENIAN-vyun+|) ("KEY_Armenian_yech" . |+KEY-ARMENIAN-yech+|) ("KEY_Armenian_za" . |+KEY-ARMENIAN-za+|) ("KEY_Armenian_zhe" . |+KEY-ARMENIAN-zhe+|) ("KEY_atilde" . |+KEY-atilde+|) ("KEY_b" . |+KEY-b+|) ("KEY_babovedot" . |+KEY-babovedot+|) ("KEY_Byelorussian_shortu" . |+KEY-BYELORUSSIAN-shortu+|) ("KEY_c" . |+KEY-c+|) ("KEY_Ch" . |+KEY-Ch+|) ("KEY_ch" . |+KEY-ch+|) ("KEY_C_h" . |+KEY-C-h+|) ("KEY_c_h" . |+KEY-c-h+|) ("KEY_cabovedot" . |+KEY-cabovedot+|) ("KEY_cacute" . |+KEY-cacute+|) ("KEY_ccaron" . |+KEY-ccaron+|) ("KEY_ccedilla" . |+KEY-ccedilla+|) ("KEY_ccircumflex" . |+KEY-ccircumflex+|) ("KEY_ch" . |+KEY-ch+|) ("KEY_Cyrillic_a" . |+KEY-CYRILLIC-a+|) ("KEY_Cyrillic_be" . |+KEY-CYRILLIC-be+|) ("KEY_Cyrillic_che" . |+KEY-CYRILLIC-che+|) ("KEY_Cyrillic_che_descender" . |+KEY-CYRILLIC_che-DESCENDER+|) ("KEY_Cyrillic_che_vertstroke" . |+KEY-CYRILLIC_che-VERTSTROKE+|) ("KEY_Cyrillic_de" . |+KEY-CYRILLIC-de+|) ("KEY_Cyrillic_dzhe" . |+KEY-CYRILLIC-dzhe+|) ("KEY_Cyrillic_e" . |+KEY-CYRILLIC-e+|) ("KEY_Cyrillic_ef" . |+KEY-CYRILLIC-ef+|) ("KEY_Cyrillic_el" . |+KEY-CYRILLIC-el+|) ("KEY_Cyrillic_em" . |+KEY-CYRILLIC-em+|) ("KEY_Cyrillic_en" . |+KEY-CYRILLIC-en+|) ("KEY_Cyrillic_en_descender" . |+KEY-CYRILLIC_en-DESCENDER+|) ("KEY_Cyrillic_er" . |+KEY-CYRILLIC-er+|) ("KEY_Cyrillic_es" . |+KEY-CYRILLIC-es+|) ("KEY_Cyrillic_ghe" . |+KEY-CYRILLIC-ghe+|) ("KEY_Cyrillic_ghe_bar" . |+KEY-CYRILLIC_ghe-BAR+|) ("KEY_Cyrillic_ha" . |+KEY-CYRILLIC-ha+|) ("KEY_Cyrillic_hardsign" . |+KEY-CYRILLIC-hardsign+|) ("KEY_Cyrillic_ha_descender" . |+KEY-CYRILLIC_ha-DESCENDER+|) ("KEY_Cyrillic_i" . |+KEY-CYRILLIC-i+|) ("KEY_Cyrillic_ie" . |+KEY-CYRILLIC-ie+|) ("KEY_Cyrillic_io" . |+KEY-CYRILLIC-io+|) ("KEY_Cyrillic_i_macron" . |+KEY-CYRILLIC_i-MACRON+|) ("KEY_Cyrillic_je" . |+KEY-CYRILLIC-je+|) ("KEY_Cyrillic_ka" . |+KEY-CYRILLIC-ka+|) ("KEY_Cyrillic_ka_descender" . |+KEY-CYRILLIC-ka-DESCENDER+|) ("KEY_Cyrillic_ka_vertstroke" . |+KEY-CYRILLIC-ka-VERTSTROKE+|) ("KEY_Cyrillic_lje" . |+KEY-CYRILLIC-lje+|) ("KEY_Cyrillic_nje" . |+KEY-CYRILLIC-nje+|) ("KEY_Cyrillic_o" . |+KEY-CYRILLIC-o+|) ("KEY_Cyrillic_o_bar" . |+KEY-CYRILLIC_O-bar+|) ("KEY_Cyrillic_pe" . |+KEY-CYRILLIC-pe+|) ("KEY_Cyrillic_schwa" . |+KEY-CYRILLIC-schwa+|) ("KEY_Cyrillic_sha" . |+KEY-CYRILLIC-sha+|) ("KEY_Cyrillic_shcha" . |+KEY-CYRILLIC-shcha+|) ("KEY_Cyrillic_shha" . |+KEY-CYRILLIC-shha+|) ("KEY_Cyrillic_shorti" . |+KEY-CYRILLIC-shorti+|) ("KEY_Cyrillic_softsign" . |+KEY-CYRILLIC-softsign+|) ("KEY_Cyrillic_te" . |+KEY-CYRILLIC-te+|) ("KEY_Cyrillic_tse" . |+KEY-CYRILLIC-tse+|) ("KEY_Cyrillic_u" . |+KEY-CYRILLIC-u+|) ("KEY_Cyrillic_u_macron" . |+KEY-CYRILLIC-u-MACRON+|) ("KEY_Cyrillic_u_straight" . |+KEY-CYRILLIC-u-STRAIGHT+|) ("KEY_Cyrillic_u_straight_bar" . |+KEY-CYRILLIC-u-STRAIGHT-BAR+|) ("KEY_Cyrillic_ve" . |+KEY-CYRILLIC-ve+|) ("KEY_Cyrillic_ya" . |+KEY-CYRILLIC-ya+|) ("KEY_Cyrillic_yeru" . |+KEY-CYRILLIC-yeru+|) ("KEY_Cyrillic_yu" . |+KEY-CYRILLIC-yu+|) ("KEY_Cyrillic_ze" . |+KEY-CYRILLIC-ze+|) ("KEY_Cyrillic_zhe" . |+KEY-CYRILLIC-zhe+|) ("KEY_Cyrillic_zhe_descender" . |+KEY-CYRILLIC_ZHE-descender+|) ("KEY_d" . |+KEY-d+|) ("KEY_dabovedot" . |+KEY-dabovedot+|) ("KEY_dcaron" . |+KEY-dcaron+|) ("KEY_dstroke" . |+KEY-dstroke+|) ("KEY_e" . |+KEY-e+|) ("KEY_eng" . |+KEY-eng+|) ("KEY_eth" . |+KEY-eth+|) ("KEY_ezh" . |+KEY-ezh+|) ("KEY_eabovedot" . |+KEY-eabovedot+|) ("KEY_eacute" . |+KEY-eacute+|) ("KEY_ebelowdot" . |+KEY-ebelowdot+|) ("KEY_ecaron" . |+KEY-ecaron+|) ("KEY_ecircumflex" . |+KEY-ecircumflex+|) ("KEY_ecircumflexacute" . |+KEY-ecircumflexacute+|) ("KEY_ecircumflexbelowdot" . |+KEY-ecircumflexbelowdot+|) ("KEY_ecircumflexgrave" . |+KEY-ecircumflexgrave+|) ("KEY_ecircumflexhook" . |+KEY-ecircumflexhook+|) ("KEY_ecircumflextilde" . |+KEY-ecircumflextilde+|) ("KEY_ediaeresis" . |+KEY-ediaeresis+|) ("KEY_egrave" . |+KEY-egrave+|) ("KEY_ehook" . |+KEY-ehook+|) ("KEY_emacron" . |+KEY-emacron+|) ("KEY_eogonek" . |+KEY-eogonek+|) ("KEY_eth" . |+KEY-eth+|) ("KEY_etilde" . |+KEY-etilde+|) ("KEY_f" . |+KEY-f+|) ("KEY_fabovedot" . |+KEY-fabovedot+|) ("KEY_g" . |+KEY-g+|) ("KEY_gabovedot" . |+KEY-gabovedot+|) ("KEY_gbreve" . |+KEY-gbreve+|) ("KEY_gcaron" . |+KEY-gcaron+|) ("KEY_gcedilla" . |+KEY-gcedilla+|) ("KEY_gcircumflex" . |+KEY-gcircumflex+|) ("KEY_Greek_alpha" . |+KEY-GREEK-alpha+|) ("KEY_Greek_alphaaccent" . |+KEY-GREEK-alphaaccent+|) ("KEY_Greek_beta" . |+KEY-GREEK-beta+|) ("KEY_Greek_chi" . |+KEY-GREEK-chi+|) ("KEY_Greek_delta" . |+KEY-GREEK-delta+|) ("KEY_Greek_epsilon" . |+KEY-GREEK-epsilon+|) ("KEY_Greek_epsilonaccent" . |+KEY-GREEK-epsilonaccent+|) ("KEY_Greek_eta" . |+KEY-GREEK-eta+|) ("KEY_Greek_etaaccent" . |+KEY-GREEK-etaaccent+|) ("KEY_Greek_gamma" . |+KEY-GREEK-gamma+|) ("KEY_Greek_iota" . |+KEY-GREEK-iota+|) ("KEY_Greek_iotaaccent" . |+KEY-GREEK-iotaaccent+|) ("KEY_Greek_iotadieresis" . |+KEY-GREEK-iotadieresis+|) ("KEY_Greek_kappa" . |+KEY-GREEK-kappa+|) ("KEY_Greek_lambda" . |+KEY-GREEK-lambda+|) ("KEY_Greek_lamda" . |+KEY-GREEK-lamda+|) ("KEY_Greek_mu" . |+KEY-GREEK-mu+|) ("KEY_Greek_nu" . |+KEY-GREEK-nu+|) ("KEY_Greek_omega" . |+KEY-GREEK-omega+|) ("KEY_Greek_omegaaccent" . |+KEY-GREEK-omegaaccent+|) ("KEY_Greek_omicron" . |+KEY-GREEK-omicron+|) ("KEY_Greek_omicronaccent" . |+KEY-GREEK-omicronaccent+|) ("KEY_Greek_phi" . |+KEY-GREEK-phi+|) ("KEY_Greek_pi" . |+KEY-GREEK-pi+|) ("KEY_Greek_psi" . |+KEY-GREEK-psi+|) ("KEY_Greek_rho" . |+KEY-GREEK-rho+|) ("KEY_Greek_sigma" . |+KEY-GREEK-sigma+|) ("KEY_Greek_tau" . |+KEY-GREEK-tau+|) ("KEY_Greek_theta" . |+KEY-GREEK-theta+|) ("KEY_Greek_upsilon" . |+KEY-GREEK-upsilon+|) ("KEY_Greek_upsilonaccent" . |+KEY-GREEK-upsilonaccent+|) ("KEY_Greek_upsilondieresis" . |+KEY-GREEK-upsilondieresis+|) ("KEY_Greek_xi" . |+KEY-GREEK-xi+|) ("KEY_Greek_zeta" . |+KEY-GREEK-zeta+|) ("KEY_h" . |+KEY-h+|) ("KEY_hcircumflex" . |+KEY-hcircumflex+|) ("KEY_hstroke" . |+KEY-hstroke+|) ("KEY_i" . |+KEY-i+|) ("KEY_iacute" . |+KEY-iacute+|) ("KEY_ibelowdot" . |+KEY-ibelowdot+|) ("KEY_ibreve" . |+KEY-ibreve+|) ("KEY_icircumflex" . |+KEY-icircumflex+|) ("KEY_idiaeresis" . |+KEY-idiaeresis+|) ("KEY_igrave" . |+KEY-igrave+|) ("KEY_ihook" . |+KEY-ihook+|) ("KEY_imacron" . |+KEY-imacron+|) ("KEY_iogonek" . |+KEY-iogonek+|) ("KEY_itilde" . |+KEY-itilde+|) ("KEY_j" . |+KEY-j+|) ("KEY_jcircumflex" . |+KEY-jcircumflex+|) ("KEY_k" . |+KEY-k+|) ("KEY_kcedilla" . |+KEY-kcedilla+|) ("KEY_l" . |+KEY-l+|) ("KEY_lacute" . |+KEY-lacute+|) ("KEY_lbelowdot" . |+KEY-lbelowdot+|) ("KEY_lcaron" . |+KEY-lcaron+|) ("KEY_lcedilla" . |+KEY-lcedilla+|) ("KEY_lstroke" . |+KEY-lstroke+|) ("KEY_m" . |+KEY-m+|) ("KEY_mabovedot" . |+KEY-mabovedot+|) ("KEY_Macedonia_dse" . |+KEY-MACEDONIA-dse+|) ("KEY_Macedonia_gje" . |+KEY-MACEDONIA-gje+|) ("KEY_Macedonia_kje" . |+KEY-MACEDONIA-kje+|) ("KEY_n" . |+KEY-n+|) ("KEY_nacute" . |+KEY-nacute+|) ("KEY_ncaron" . |+KEY-ncaron+|) ("KEY_ncedilla" . |+KEY-ncedilla+|) ("KEY_ntilde" . |+KEY-ntilde+|) ("KEY_o" . |+KEY-o+|) ("KEY_oe" . |+KEY-oe+|) ("KEY_oacute" . |+KEY-oacute+|) ("KEY_obarred" . |+KEY-obarred+|) ("KEY_obelowdot" . |+KEY-obelowdot+|) ("KEY_ocaron" . |+KEY-ocaron+|) ("KEY_ocircumflex" . |+KEY-ocircumflex+|) ("KEY_ocircumflexacute" . |+KEY-ocircumflexacute+|) ("KEY_ocircumflexbelowdot" . |+KEY-ocircumflexbelowdot+|) ("KEY_ocircumflexgrave" . |+KEY-ocircumflexgrave+|) ("KEY_ocircumflexhook" . |+KEY-ocircumflexhook+|) ("KEY_ocircumflextilde" . |+KEY-ocircumflextilde+|) ("KEY_odiaeresis" . |+KEY-odiaeresis+|) ("KEY_odoubleacute" . |+KEY-odoubleacute+|) ("KEY_ograve" . |+KEY-ograve+|) ("KEY_ohook" . |+KEY-ohook+|) ("KEY_ohorn" . |+KEY-ohorn+|) ("KEY_ohornacute" . |+KEY-ohornacute+|) ("KEY_ohornbelowdot" . |+KEY-ohornbelowdot+|) ("KEY_ohorngrave" . |+KEY-ohorngrave+|) ("KEY_ohornhook" . |+KEY-ohornhook+|) ("KEY_ohorntilde" . |+KEY-ohorntilde+|) ("KEY_omacron" . |+KEY-omacron+|) ("KEY_ooblique" . |+KEY-ooblique+|) ("KEY_oslash" . |+KEY-oslash+|) ("KEY_otilde" . |+KEY-otilde+|) ("KEY_p" . |+KEY-p+|) ("KEY_pabovedot" . |+KEY-pabovedot+|) ("KEY_q" . |+KEY-q+|) ("KEY_r" . |+KEY-r+|) ("KEY_racute" . |+KEY-racute+|) ("KEY_rcaron" . |+KEY-rcaron+|) ("KEY_rcedilla" . |+KEY-rcedilla+|) ("KEY_s" . |+KEY-s+|) ("KEY_schwa" . |+KEY-schwa+|) ("KEY_sabovedot" . |+KEY-sabovedot+|) ("KEY_sacute" . |+KEY-sacute+|) ("KEY_scaron" . |+KEY-scaron+|) ("KEY_scedilla" . |+KEY-scedilla+|) ("KEY_scircumflex" . |+KEY-scircumflex+|) ("KEY_Serbian_dje" . |+KEY-SERBIAN-dje+|) ("KEY_Serbian_dze" . |+KEY-SERBIAN-dze+|) ("KEY_Serbian_je" . |+KEY-SERBIAN-je+|) ("KEY_Serbian_lje" . |+KEY-SERBIAN-lje+|) ("KEY_Serbian_nje" . |+KEY-SERBIAN-nje+|) ("KEY_Serbian_tshe" . |+KEY-SERBIAN-tshe+|) ("KEY_t" . |+KEY-t+|) ("KEY_thorn" . |+KEY-thorn+|) ("KEY_tabovedot" . |+KEY-tabovedot+|) ("KEY_tcaron" . |+KEY-tcaron+|) ("KEY_tcedilla" . |+KEY-tcedilla+|) ("KEY_thorn" . |+KEY-thorn+|) ("KEY_tslash" . |+KEY-tslash+|) ("KEY_u" . |+KEY-u+|) ("KEY_uacute" . |+KEY-uacute+|) ("KEY_ubelowdot" . |+KEY-ubelowdot+|) ("KEY_ubreve" . |+KEY-ubreve+|) ("KEY_ucircumflex" . |+KEY-ucircumflex+|) ("KEY_udiaeresis" . |+KEY-udiaeresis+|) ("KEY_udoubleacute" . |+KEY-udoubleacute+|) ("KEY_ugrave" . |+KEY-ugrave+|) ("KEY_uhook" . |+KEY-uhook+|) ("KEY_uhorn" . |+KEY-uhorn+|) ("KEY_uhornacute" . |+KEY-uhornacute+|) ("KEY_uhornbelowdot" . |+KEY-uhornbelowdot+|) ("KEY_uhorngrave" . |+KEY-uhorngrave+|) ("KEY_uhornhook" . |+KEY-uhornhook+|) ("KEY_uhorntilde" . |+KEY-uhorntilde+|) ("KEY_Ukrainian_ghe_with_upturn" . |+KEY-UKRAINIAN-ghe-WITH-UPTURN+|) ("KEY_Ukrainian_i" . |+KEY-UKRAINIAN-i+|) ("KEY_Ukrainian_ie" . |+KEY-UKRAINIAN-ie+|) ("KEY_Ukrainian_yi" . |+KEY-UKRAINIAN-yi+|) ("KEY_Ukranian_i" . |+KEY-UKRANIAN-i+|) ("KEY_Ukranian_je" . |+KEY-UKRANIAN-je+|) ("KEY_Ukranian_yi" . |+KEY-UKRANIAN-yi+|) ("KEY_umacron" . |+KEY-umacron+|) ("KEY_uogonek" . |+KEY-uogonek+|) ("KEY_uring" . |+KEY-uring+|) ("KEY_utilde" . |+KEY-utilde+|) ("KEY_v" . |+KEY-v+|) ("KEY_w" . |+KEY-w+|) ("KEY_wacute" . |+KEY-wacute+|) ("KEY_wcircumflex" . |+KEY-wcircumflex+|) ("KEY_wdiaeresis" . |+KEY-wdiaeresis+|) ("KEY_wgrave" . |+KEY-wgrave+|) ("KEY_x" . |+KEY-x+|) ("KEY_xabovedot" . |+KEY-xabovedot+|) ("KEY_y" . |+KEY-y+|) ("KEY_yacute" . |+KEY-yacute+|) ("KEY_ybelowdot" . |+KEY-ybelowdot+|) ("KEY_ycircumflex" . |+KEY-ycircumflex+|) ("KEY_ydiaeresis" . |+KEY-ydiaeresis+|) ("KEY_ygrave" . |+KEY-ygrave+|) ("KEY_yhook" . |+KEY-yhook+|) ("KEY_ytilde" . |+KEY-ytilde+|) ("KEY_z" . |+KEY-z+|) ("KEY_zabovedot" . |+KEY-zabovedot+|) ("KEY_zacute" . |+KEY-zacute+|) ("KEY_zcaron" . |+KEY-zcaron+|) ("KEY_zstroke" . |+KEY-zstroke+|) ("KEY_dead_a" . |+KEY-DEAD-a+|) ("KEY_dead_e" . |+KEY-DEAD-e+|) ("KEY_dead_i" . |+KEY-DEAD-i+|) ("KEY_dead_o" . |+KEY-DEAD-o+|) ("KEY_dead_u" . |+KEY-DEAD-u+|) ("KEY_kana_a" . |+KEY-KANA-a+|) ("KEY_kana_e" . |+KEY-KANA-e+|) ("KEY_kana_i" . |+KEY-KANA-i+|) ("KEY_kana_o" . |+KEY-KANA-o+|) ("KEY_kana_tsu" . |+KEY-KANA-tsu+|) ("KEY_kana_tu" . |+KEY-KANA-tu+|) ("KEY_kana_u" . |+KEY-KANA-u+|) ("KEY_kana_ya" . |+KEY-KANA-ya+|) ("KEY_kana_yo" . |+KEY-KANA-yo+|) ("KEY_kana_yu" . |+KEY-KANA-yu+|)))) (gir-wrapper:define-gir-namespace "Gdk" "4.0") (cffi:defcstruct rectangle "A GdkRectangle data type for representing rectangles." (x :int) (y :int) (width :int) (height :int)) (cl:eval-when (:execute :compile-toplevel :load-toplevel) (cl:setf gir-wrapper:*quoted-name-alist* cl:nil))
35,384
Common Lisp
.lisp
375
52.234667
114
0.260385
bohonghuang/cl-gtk4
213
9
23
LGPL-3.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
9951cc2620c477512204ae2310e2ac80f3bd82d478cf6f0605bfb5a3ca754862
323
[ -1 ]
324
adw.lisp
bohonghuang_cl-gtk4/adw.lisp
;;;; adw.lisp ;;;; Copyright (C) 2022-2023 Bohong Huang ;;;; ;;;; This program is free software: you can redistribute it and/or modify ;;;; it under the terms of the GNU Lesser General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; This program is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;;; GNU Lesser General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU Lesser General Public License ;;;; along with this program. If not, see <https://www.gnu.org/licenses/>. (cl:defpackage adw (:use) (:export #:*ns*)) (cl:in-package #:adw) (cl:eval-when (:execute :compile-toplevel :load-toplevel) (cl:setf gir-wrapper:*quoted-name-alist* '(("t" . time)))) (gir-wrapper:define-gir-namespace "Adw") (cl:eval-when (:execute :compile-toplevel :load-toplevel) (cl:setf gir-wrapper:*quoted-name-alist* cl:nil))
1,099
Common Lisp
.lisp
24
44.208333
80
0.72217
bohonghuang/cl-gtk4
213
9
23
LGPL-3.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
8dd5956aaeee8b80862b7b878b078c52aed817e3ad971bac7ee3b23e9021d9ea
324
[ -1 ]
325
webkit.lisp
bohonghuang_cl-gtk4/examples/webkit.lisp
;;;; examples/webkit.lisp ;;;; Copyright (C) 2022-2023 Bohong Huang ;;;; ;;;; This program is free software: you can redistribute it and/or modify ;;;; it under the terms of the GNU Lesser General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; This program is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;;; GNU Lesser General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU Lesser General Public License ;;;; along with this program. If not, see <https://www.gnu.org/licenses/>. (defpackage webkit.example (:use #:cl #:gtk4) (:export #:main)) (in-package #:webkit.example) (defparameter *home-uri* "https://google.com") (define-application (:name main :id "org.bohonghuang.webkit-example") (define-main-window (window (make-application-window :application *application*)) (let ((web-view (webkit:make-web-view ))) (setf (window-title window) "CL-GTK4-WEBKIT-EXAMPLE" (window-default-size window) '(800 600)) (connect web-view "load-changed" (lambda (web-view event) (declare (ignore event)) (setf (window-title window) (if (webkit:web-view-loading-p web-view) (webkit:web-view-uri web-view) (webkit:web-view-title web-view))))) (let ((box (make-box :orientation +orientation-vertical+ :spacing 0))) (let ((toolbar (make-center-box))) (widget-add-css-class toolbar "toolbar") (let ((box (make-box :orientation +orientation-horizontal+ :spacing 4))) (let ((button (make-button :icon-name "go-previous-symbolic"))) (connect button "clicked" (lambda (button) (declare (ignore button)) (webkit:web-view-go-back web-view))) (connect web-view "load-changed" (lambda (web-view event) (declare (ignore event)) (setf (widget-sensitive-p button) (webkit:web-view-can-go-back-p web-view)))) (box-append box button)) (let ((button (make-button :icon-name "go-next-symbolic"))) (connect button "clicked" (lambda (button) (declare (ignore button)) (webkit:web-view-go-forward web-view))) (connect web-view "load-changed" (lambda (web-view event) (declare (ignore event)) (setf (widget-sensitive-p button) (webkit:web-view-can-go-forward-p web-view)))) (box-append box button)) (let ((button (make-button :icon-name "go-home-symbolic"))) (connect button "clicked" (lambda (button) (declare (ignore button)) (webkit:web-view-load-uri web-view *home-uri*))) (box-append box button)) (setf (center-box-start-widget toolbar) box)) (let ((box (make-box :orientation +orientation-horizontal+ :spacing 4))) (setf (widget-halign box) +align-fill+ (widget-hexpand-p box) t (widget-margin-start box) 50 (widget-margin-end box) 50) (let ((entry (make-entry))) (setf (widget-halign entry) +align-fill+ (widget-hexpand-p entry) t) (connect entry "activate" (lambda (entry) (webkit:web-view-load-uri web-view (entry-buffer-text (entry-buffer entry))))) (connect web-view "load-changed" (lambda (web-view event) (declare (ignore event)) (setf (entry-buffer-text (entry-buffer entry)) (webkit:web-view-uri web-view)))) (box-append box entry)) (let ((button (make-button :icon-name "view-refresh-symbolic"))) (connect button "clicked" (lambda (button) (declare (ignore button)) (if (webkit:web-view-loading-p web-view) (webkit:web-view-stop-loading web-view) (webkit:web-view-reload web-view)))) (connect web-view "load-changed" (lambda (web-view event) (declare (ignore event)) (setf (button-icon-name button) (if (webkit:web-view-loading-p web-view) "process-stop-symbolic" "view-refresh-symbolic")))) (box-append box button)) (setf (center-box-center-widget toolbar) box)) (box-append box toolbar)) (let ((progress-bar (make-progress-bar))) (widget-add-css-class progress-bar "osd") (connect web-view "load-changed" (lambda (web-view event) (declare (ignore event)) (setf (progress-bar-fraction progress-bar) (if (webkit:web-view-loading-p web-view) (webkit:web-view-estimated-load-progress web-view) 0.0d0)))) (box-append box progress-bar)) (let ((web-view web-view)) (setf (widget-vexpand-p web-view) t (widget-hexpand-p web-view) t) (webkit:web-view-load-uri web-view *home-uri*) (box-append box web-view)) (setf (window-child window) box))) (unless (widget-visible-p window) (window-present window))))
6,577
Common Lisp
.lisp
105
40.542857
129
0.489157
bohonghuang/cl-gtk4
213
9
23
LGPL-3.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
ba819e1c80bb2b7d72d4f7eb402af5ea5336457b614bcc04a8e08f40be132bc7
325
[ -1 ]
326
sourceview.lisp
bohonghuang_cl-gtk4/examples/sourceview.lisp
;;;; examples/sourceview.lisp ;;;; Copyright (C) 2022-2023 Bohong Huang ;;;; ;;;; This program is free software: you can redistribute it and/or modify ;;;; it under the terms of the GNU Lesser General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; This program is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;;; GNU Lesser General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU Lesser General Public License ;;;; along with this program. If not, see <https://www.gnu.org/licenses/>. (defpackage gtksourceview.example (:use #:cl #:gtk4) (:nicknames sourceview.example) (:local-nicknames (#:sv #:sourceview)) (:export #:main)) (in-package #:sourceview.example) (defun system-absolute-pathname (pathname) (merge-pathnames pathname (asdf:component-pathname (asdf:find-system '#:cl-gtk4.sourceview/example)))) (define-application (:name main :id "org.bohonghuang.gtksourceview-example") (define-main-window (window (make-application-window :application *application*)) (setf (window-title window) "GtkSourceView Example") (let ((scrolled-window (make-scrolled-window))) (let ((buffer (sv:make-buffer :language (sv:language-manager-get-language (sv:make-language-manager) "commonlisp")))) (setf (gtk:text-buffer-text buffer) (alexandria:read-file-into-string (system-absolute-pathname "sourceview.lisp"))) (block setup-dark-scheme (let* ((manager (sv:make-style-scheme-manager)) (scheme (sv:style-scheme-manager-get-scheme manager (or (find-if (alexandria:curry #'search "Adwaita-dark") (sv:style-scheme-manager-scheme-ids manager)) (find-if (alexandria:curry #'search "dark") (sv:style-scheme-manager-scheme-ids manager)) (return-from setup-dark-scheme nil))))) (setf (sv:buffer-style-scheme buffer) scheme))) (let ((view (sv:make-view :buffer buffer))) (setf (sv:view-show-line-numbers-p view) t (sv:view-highlight-current-line-p view) t) (let ((provider (make-css-provider))) (css-provider-load-from-data provider "textview { font-family: Monospace; font-size: 12pt; }") (style-context-add-provider (widget-style-context view) provider +style-provider-priority-application+)) (setf (scrolled-window-child scrolled-window) view))) (setf (widget-size-request scrolled-window) '(1000 1000)) (setf (window-child window) scrolled-window)) (unless (widget-visible-p window) (window-present window))))
3,135
Common Lisp
.lisp
54
46.740741
116
0.623537
bohonghuang/cl-gtk4
213
9
23
LGPL-3.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
23930bd9d076bed7c5b0ccb93c49472d5616b0b22533447ba46c73fdd56e57e5
326
[ -1 ]
327
gdk4-cairo.lisp
bohonghuang_cl-gtk4/examples/gdk4-cairo.lisp
;;;; examples/gdk4-cairo.lisp ;;;; Copyright (C) 2022-2023 Bohong Huang ;;;; ;;;; This program is free software: you can redistribute it and/or modify ;;;; it under the terms of the GNU Lesser General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; This program is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;;; GNU Lesser General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU Lesser General Public License ;;;; along with this program. If not, see <https://www.gnu.org/licenses/>. (cl:defpackage cairo-gobject (:use) (:export #:*ns*)) (cl:in-package #:cairo-gobject) (gir-wrapper:define-gir-namespace "cairo") (cl:in-package #:gdk4.example) (cffi:defcstruct gdk-rgba (red :float) (green :float) (blue :float) (alpha :float)) (defmacro with-gdk-rgba ((pointer color) &body body) `(locally #+sbcl (declare (sb-ext:muffle-conditions sb-ext:compiler-note)) (cffi:with-foreign-object (,pointer '(:struct gdk-rgba)) (let ((,pointer (make-instance 'gir::struct-instance :class (gir:nget gdk::*ns* "RGBA") :this ,pointer))) (gdk:rgba-parse ,pointer ,color) (locally #+sbcl (declare (sb-ext:unmuffle-conditions sb-ext:compiler-note)) ,@body))))) (declaim (ftype (function (t t t t) t) draw-func)) (cffi:defcallback %draw-func :void ((area :pointer) (cr :pointer) (width :int) (height :int) (data :pointer)) (declare (ignore data)) (let ((cairo:*context* (make-instance 'cairo:context :pointer cr :width width :height height :pixel-based-p nil))) (draw-func (make-instance 'gir::object-instance :class (gir:nget gtk:*ns* "DrawingArea") :this area) (make-instance 'gir::struct-instance :class (gir:nget cairo-gobject:*ns* "Context") :this cr) width height))) (define-application (:name cairo-test :id "org.bohonghuang.gdk4-cairo-example") (defun draw-func (area cr width height) (declare (ignore area) (optimize (speed 3) (debug 0) (safety 0))) (let ((width (coerce (the fixnum width) 'single-float)) (height (coerce (the fixnum height) 'single-float)) (fpi (coerce pi 'single-float))) (let* ((radius (/ (min width height) 2.0)) (stroke-width (/ radius 8.0)) (button-radius (* radius 0.4))) (declare (type single-float radius stroke-width button-radius)) (with-gdk-rgba (color "#000000") (cairo:arc (/ width 2.0) (/ height 2.0) radius 0.0 (* 2.0 fpi)) (gdk:cairo-set-source-rgba cr color) (cairo:fill-path)) (with-gdk-rgba (color "#FF0000") (cairo:arc (/ width 2.0) (/ height 2.0) (- radius stroke-width) pi (* 2.0 fpi)) (gdk:cairo-set-source-rgba cr color) (cairo:fill-path)) (with-gdk-rgba (color "#FFFFFF") (cairo:arc (/ width 2.0) (/ height 2.0) (- radius stroke-width) 0.0 fpi) (gdk:cairo-set-source-rgba cr color) (cairo:fill-path)) (with-gdk-rgba (color "#000000") (let ((bar-length (sqrt (- (expt (* radius 2) 2.0) (expt stroke-width 2.0))))) (declare (type single-float bar-length)) (cairo:rectangle (+ (- (/ width 2.0) radius) (- radius (/ bar-length 2.0))) (+ (- (/ height 2.0) radius) (- radius (/ stroke-width 2.0))) bar-length stroke-width)) (gdk:cairo-set-source-rgba cr color) (cairo:fill-path)) (with-gdk-rgba (color "#000000") (cairo:arc (/ width 2.0) (/ height 2.0) button-radius 0.0 (* 2.0 fpi)) (gdk:cairo-set-source-rgba cr color) (cairo:fill-path)) (with-gdk-rgba (color "#FFFFFF") (cairo:arc (/ width 2.0) (/ height 2.0) (- button-radius stroke-width) 0.0 (* 2.0 fpi)) (gdk:cairo-set-source-rgba cr color) (cairo:fill-path))))) (define-main-window (window (make-application-window :application *application*)) (setf (window-title window) "Drawing Area Test") (let ((area (gtk:make-drawing-area))) (setf (drawing-area-content-width area) 200 (drawing-area-content-height area) 200 (drawing-area-draw-func area) (list (cffi:callback %draw-func) (cffi:null-pointer) (cffi:null-pointer))) (setf (window-child window) area)) (unless (widget-visible-p window) (window-present window))))
5,364
Common Lisp
.lisp
110
36.109091
97
0.542143
bohonghuang/cl-gtk4
213
9
23
LGPL-3.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
c5bedb265711ea08ab4c5b0269531e58a6715ebd5718031c8ab75ccdd81e2140
327
[ -1 ]
328
gtk4.lisp
bohonghuang_cl-gtk4/examples/gtk4.lisp
;;;; examples/gtk4.lisp ;;;; Copyright (C) 2022-2023 Bohong Huang ;;;; ;;;; This program is free software: you can redistribute it and/or modify ;;;; it under the terms of the GNU Lesser General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; This program is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;;; GNU Lesser General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU Lesser General Public License ;;;; along with this program. If not, see <https://www.gnu.org/licenses/>. (defpackage gtk4.example (:use #:cl #:gtk4) (:export #:simple-counter #:fibonacci #:simple-menu #:simple-text-view #:string-list-view #:ui-file)) (in-package #:gtk4.example) (define-application (:name simple-counter :id "org.bohonghuang.gtk4-example.simple-counter") (define-main-window (window (make-application-window :application *application*)) (setf (window-title window) "Simple Counter") (let ((box (make-box :orientation +orientation-vertical+ :spacing 4))) (let ((label (make-label :str "0"))) (setf (widget-hexpand-p label) t (widget-vexpand-p label) t) (box-append box label) (let ((button (make-button :label "Add")) (count 0)) (connect button "clicked" (lambda (button) (declare (ignore button)) (setf (label-text label) (format nil "~A" (incf count))))) (box-append box button)) (let ((button (make-button :label "Exit"))) (connect button "clicked" (lambda (button) (declare (ignore button)) (window-destroy window))) (box-append box button))) (setf (window-child window) box)) (unless (widget-visible-p window) (window-present window)))) (define-application (:name fibonacci :id "org.bohonghuang.gtk4-example.fibonacci") (defun fib (n) (if (<= n 2) 1 (+ (fib (- n 1)) (fib (- n 2))))) (define-main-window (window (make-application-window :application *application*)) (let ((n 40)) (setf (window-title window) "Fibonacci Calculator") (let ((box (make-box :orientation +orientation-vertical+ :spacing 4))) (let ((label (make-label :str "0"))) (setf (widget-hexpand-p label) t (widget-vexpand-p label) t) (box-append box label) (let ((parent box) (box (make-box :orientation +orientation-horizontal+ :spacing 4))) (setf (widget-hexpand-p box) t (widget-halign box) +align-center+) (let ((label (make-label :str "n: "))) (box-append box label)) (let ((entry (make-entry))) (setf (widget-hexpand-p label) t (widget-halign label) +align-fill+ (entry-buffer-text (entry-buffer entry)) (format nil "~A" n)) (connect entry "changed" (lambda (entry) (setf n (ignore-errors (parse-integer (entry-buffer-text (entry-buffer entry))))))) (box-append box entry)) (box-append parent box)) (let ((button (make-button :label "Calculate"))) (connect button "clicked" (lambda (button) (bt:make-thread (lambda () (when n (run-in-main-event-loop () (setf (button-label button) "Calculating..." (widget-sensitive-p button) nil)) (let ((result (fib n))) (run-in-main-event-loop () (setf (label-text label) (format nil "~A" result) (button-label button) "Calculate" (widget-sensitive-p button) t)))))))) (box-append box button))) (setf (window-child window) box))) (unless (widget-visible-p window) (window-present window)))) (define-application (:name simple-menu :id "org.bohonghuang.gtk4-example.simple-menu") (defun simple-menu-menu () (let ((menu (gio:make-menu))) (let ((submenu (gio:make-menu))) (gio:menu-append-item submenu (gio:make-menu-item :model menu :label "Open" :detailed-action "app.open")) (gio:menu-append-item submenu (gio:make-menu-item :model menu :label "Exit" :detailed-action "app.exit")) (gio:menu-append-submenu menu "File" submenu)) (let ((submenu (gio:make-menu))) (gio:menu-append-item submenu (gio:make-menu-item :model menu :label "About" :detailed-action "app.about")) (gio:menu-append-submenu menu "Help" submenu)) (values menu))) (defun menu-test-about-dialog () (let ((dialog (make-about-dialog)) (system (asdf:find-system :cl-gtk4))) (setf (about-dialog-authors dialog) (list (asdf:system-author system)) (about-dialog-website dialog) (asdf:system-homepage system) (about-dialog-version dialog) (asdf:component-version system) (about-dialog-program-name dialog) (asdf:component-name system) (about-dialog-comments dialog) (asdf:system-description system) (about-dialog-logo-icon-name dialog) "application-x-addon") (values dialog))) (define-main-window (window (make-application-window :application *application*)) (setf (window-title window) "Simple Menu") (let ((header-bar (make-header-bar))) (let ((menu-button (make-menu-button))) (setf (menu-button-menu-model menu-button) (simple-menu-menu) (button-icon-name menu-button) "open-menu-symbolic") (header-bar-pack-end header-bar menu-button)) (setf (window-titlebar window) header-bar)) (let ((action (gio:make-simple-action :name "exit" :parameter-type nil))) (gio:action-map-add-action *application* action) (connect action "activate" (lambda (action param) (declare (ignore action param)) (gtk::destroy-all-windows-and-quit)))) (let ((action (gio:make-simple-action :name "about" :parameter-type nil))) (gio:action-map-add-action *application* action) (connect action "activate" (lambda (action param) (declare (ignore action param)) (let ((dialog (menu-test-about-dialog))) (setf (window-modal-p dialog) t (window-transient-for dialog) window) (window-present dialog))))) (let ((window-box (make-box :orientation +orientation-vertical+ :spacing 0))) (let ((menu-bar (make-popover-menu-bar :model (simple-menu-menu)))) (box-append window-box menu-bar)) (let ((empty-box (make-box :orientation +orientation-vertical+ :spacing 0))) (setf (widget-size-request empty-box) '(400 200)) (box-append window-box empty-box)) (setf (window-child window) window-box)) (unless (widget-visible-p window) (window-present window)))) (define-application (:name simple-text-view :id "org.bohonghuang.gtk4-example.simple-text-view") (define-main-window (window (make-application-window :application *application*)) (setf (window-title window) "Simple Text View") (let ((window-box (make-box :orientation +orientation-vertical+ :spacing 0))) (let ((body-box (make-box :orientation +orientation-vertical+ :spacing 0))) (let ((scrolled-window (make-scrolled-window))) (setf (widget-hexpand-p scrolled-window) t (widget-vexpand-p scrolled-window) t) (let ((view (make-text-view))) (setf (scrolled-window-child scrolled-window) view) (box-append body-box scrolled-window) (let ((buffer (text-view-buffer view))) (setf (text-buffer-text buffer) "Hello world!") (let ((button (make-button :label "Insert markup"))) (connect button "clicked" (lambda (button) (declare (ignore button)) (multiple-value-bind (has-selection-p start end) (text-buffer-selection-bounds buffer) (let ((pos (text-iter-offset start)) (text (if has-selection-p (prog1 (text-buffer-get-text buffer start end nil) (text-buffer-delete-selection buffer nil nil)) "Hello World!"))) (text-buffer-insert-markup buffer (text-buffer-get-iter-at-offset buffer pos) (format nil "<span foreground=\"red\" font=\"Serif 20\">~A</span>" text)))))) (box-append body-box button))))) (setf (widget-size-request body-box) '(400 200)) (box-append window-box body-box)) (setf (window-child window) window-box)) (unless (widget-visible-p window) (window-present window)))) (define-application (:name string-list-view :id "org.bohonghuang.gtk4-example.string-list-view") (define-main-window (window (make-application-window :application *application*)) (let ((box (make-box :orientation +orientation-vertical+ :spacing 1))) (let* ((model (make-string-list :strings (loop :for i :from 1 :to 10 :collect (format nil "Item ~D" i)))) (factory (make-signal-list-item-factory)) (list-view (make-list-view :model (make-single-selection :model model) :factory factory))) (flet ((setup (factory item) (declare (ignore factory)) (setf (list-item-child item) (make-label :str ""))) (bind (factory item) (declare (ignore factory)) (setf (label-text (gobj:coerce (list-item-child item) 'label)) (string-object-string (gobj:coerce (list-item-item item) 'string-object)))) (unbind (factory item) (declare (ignore factory item))) (teardown (factory item) (declare (ignore factory item)))) (connect factory "setup" #'setup) (connect factory "bind" #'bind) (connect factory "unbind" #'unbind) (connect factory "teardown" #'teardown)) (let ((scrolled-window (make-scrolled-window))) (setf (widget-size-request scrolled-window) '(250 250) (widget-vexpand-p scrolled-window) t (widget-hexpand-p scrolled-window) t (scrolled-window-child scrolled-window) list-view) (box-append box scrolled-window)) (let ((button-append (make-button :label "Append")) (button-remove (make-button :label "Remove"))) (connect button-append "clicked" (lambda (button) (declare (ignore button)) (string-list-append model (format nil "Item ~D" (1+ (gio:list-model-n-items model)))))) (box-append box button-append) (connect button-remove "clicked" (lambda (button) (declare (ignore button)) (when (plusp (gio:list-model-n-items model)) (string-list-remove model (1- (gio:list-model-n-items model)))))) (box-append box button-remove))) (setf (window-title window) "String List View" (window-child window) box (window-default-size window) '(300 300))) (unless (widget-visible-p window) (window-present window)))) (defun system-absolute-pathname (pathname) (merge-pathnames pathname (asdf:component-pathname (asdf:find-system '#:cl-gtk4/example)))) (defun ui-file () (let ((app (make-application :application-id "org.bohonghuang.gtk4-example.ui-file" :flags gio:+application-flags-flags-none+))) (connect app "activate" (lambda (app) (let ((builder (gtk:make-builder))) (gtk:builder-add-from-file builder (namestring (system-absolute-pathname "example-ui-file.ui"))) (let ((window (gobj:coerce (builder-get-object builder "window") 'application-window)) (button (gobj:coerce (builder-get-object builder "button-exit") 'button))) (setf (window-application window) app) (connect button "clicked" (lambda (button) (declare (ignore button)) (window-destroy window))) (window-present window))))) (application-run app nil)))
13,816
Common Lisp
.lisp
239
41.866109
203
0.547284
bohonghuang/cl-gtk4
213
9
23
LGPL-3.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
af88a110044c836827e0420f86f3394c133ba3045f9bae6fac172afdb43c0d39
328
[ -1 ]
329
gdk4.lisp
bohonghuang_cl-gtk4/examples/gdk4.lisp
;;;; examples/gdk4.lisp ;;;; Copyright (C) 2022-2023 Bohong Huang ;;;; ;;;; This program is free software: you can redistribute it and/or modify ;;;; it under the terms of the GNU Lesser General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; This program is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;;; GNU Lesser General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU Lesser General Public License ;;;; along with this program. If not, see <https://www.gnu.org/licenses/>. (cl:defpackage gdk4.example (:use #:cl #:gtk4) (:export #:cairo-test #:popover-test)) (cl:in-package #:gdk4.example) (define-application (:name popover-test :id "org.bohonghuang.gdk4-example.popover-test") (define-main-window (window (make-application-window :application *application*)) (setf (window-title window) "Popover Test") (let ((box (make-box :orientation +orientation-vertical+ :spacing 0))) (setf (widget-size-request box) '(200 200)) (let ((controller (make-gesture-click))) (connect controller 'pressed (lambda (self n-press x y) (declare (ignore self n-press)) (let ((popover (make-popover))) (box-append box popover) (cffi:with-foreign-object (rect '(:struct gdk4:rectangle)) (cffi:with-foreign-slots ((gdk::x gdk::y gdk::width gdk::height) rect (:struct gdk4:rectangle)) (setf gdk::x (round x) gdk::y (round y) gdk::width (round 0) gdk::height (round 0))) (setf (popover-child popover) (make-label :str "Popover") (popover-pointing-to popover) (gobj:pointer-object rect 'gdk:rectangle)) (popover-popup popover))))) (widget-add-controller box controller)) (let ((label (make-label :str "Click to pop up a Popover"))) (setf (widget-vexpand-p label) t) (box-append box label)) (setf (window-child window) box)) (unless (widget-visible-p window) (window-present window))))
2,690
Common Lisp
.lisp
46
43.543478
138
0.55947
bohonghuang/cl-gtk4
213
9
23
LGPL-3.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
d80bcbd16c9ccba86ab3062334a5f8609c0d08778808191379a94892b8618185
329
[ -1 ]
330
adw.lisp
bohonghuang_cl-gtk4/examples/adw.lisp
;;;; examples/adw.lisp ;;;; Copyright (C) 2022-2023 Bohong Huang ;;;; ;;;; This program is free software: you can redistribute it and/or modify ;;;; it under the terms of the GNU Lesser General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; This program is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;;; GNU Lesser General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU Lesser General Public License ;;;; along with this program. If not, see <https://www.gnu.org/licenses/>. (defpackage adw.example (:use #:cl #:gtk4) (:export #:main)) (in-package #:adw.example) (define-application (:name simple-repl :id "org.bohonghuang.libadwaita-example.simple-repl") (define-main-window (window (adw:make-application-window :app *application*)) (let ((expression nil)) (widget-add-css-class window "devel") (setf (widget-size-request window) '(400 600)) (let ((box (make-box :orientation +orientation-vertical+ :spacing 0))) (setf (adw:window-content window) box) (let ((header-bar (adw:make-header-bar))) (setf (adw:header-bar-title-widget header-bar) (adw:make-window-title :title (lisp-implementation-type) :subtitle (lisp-implementation-version))) (box-append box header-bar)) (let ((carousel (adw:make-carousel))) (setf (widget-hexpand-p carousel) t (widget-vexpand-p carousel) t (adw:carousel-interactive-p carousel) t) (let ((page (adw:make-status-page))) (setf (widget-hexpand-p page) t (widget-vexpand-p page) t (adw:status-page-icon-name page) "utilities-terminal-symbolic" (adw:status-page-title page) "Simple Lisp REPL" (adw:status-page-description page) " ") (flet ((eval-expression (widget) (declare (ignore widget)) (when expression (setf (adw:status-page-description page) (princ-to-string (handler-case (eval expression) (error (err) err))))))) (let ((box (make-box :orientation +orientation-vertical+ :spacing 0))) (let ((group (adw:make-preferences-group))) (setf (widget-margin-all group) 10) (let ((row (adw:make-action-row))) (setf (adw:preferences-row-title row) (format nil "~A>" (or (car (package-nicknames *package*)) (package-name *package*)))) (let ((entry (make-entry))) (setf (widget-valign entry) +align-center+ (widget-hexpand-p entry) t) (connect entry "changed" (lambda (entry) (setf expression (ignore-errors (read-from-string (entry-buffer-text (entry-buffer entry))))) (funcall (if expression #'widget-remove-css-class #'widget-add-css-class) entry "error"))) (connect entry "activate" #'eval-expression) (adw:action-row-add-suffix row entry)) (adw:preferences-group-add group row)) (box-append box group)) (let ((carousel-box box) (box (make-box :orientation +orientation-horizontal+ :spacing 0))) (setf (widget-hexpand-p box) t (widget-halign box) +align-fill+) (let ((button (make-button :label "Exit"))) (setf (widget-css-classes button) '("pill") (widget-margin-all button) 10 (widget-hexpand-p button) t) (connect button "clicked" (lambda (button) (declare (ignore button)) (window-destroy window))) (box-append box button)) (let ((button (make-button :label "Eval"))) (setf (widget-css-classes button) '("suggested-action" "pill") (widget-margin-all button) 10 (widget-hexpand-p button) t) (connect button "clicked" #'eval-expression) (box-append box button)) (box-append carousel-box box)) (setf (adw:status-page-child page) box))) (adw:carousel-append carousel page)) (box-append box carousel))) (unless (widget-visible-p window) (window-present window))))) (defun main () (unless (adw:initialized-p) (adw:init)) (simple-repl))
5,258
Common Lisp
.lisp
96
38.0625
142
0.526081
bohonghuang/cl-gtk4
213
9
23
LGPL-3.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
0d358dbe9571187400cb8fe2e00a5bd9d2efb48cc22fb612df515dead71866f0
330
[ -1 ]
331
cl-gtk4.webkit.asd
bohonghuang_cl-gtk4/cl-gtk4.webkit.asd
(defsystem cl-gtk4.webkit :version "1.0.0" :author "Bohong Huang <[email protected]>" :maintainer "Bohong Huang <[email protected]>" :license "LGPLv3" :description "WebKitGTK bindings for Common Lisp." :homepage "https://github.com/bohonghuang/cl-gtk4" :bug-tracker "https://github.com/bohonghuang/cl-gtk4/issues" :source-control (:git "https://github.com/bohonghuang/cl-gtk4.git") :serial t :components ((:file "webkit")) :depends-on (#:cl-gobject-introspection-wrapper #:cl-gtk4)) (uiop:register-image-restore-hook (lambda () (let ((package (find-package :webkit))) (when package (setf (symbol-value (find-symbol "*NS*" package)) (uiop:symbol-call :gir :require-namespace "WebKit" "6.0")))))) (defsystem cl-gtk4.webkit/example :depends-on (#:asdf #:cl-gtk4 #:cl-gtk4.webkit) :build-operation program-op :build-pathname "cl-gtk4-webkit-example" :entry-point "webkit.example:main" :pathname "examples/" :components ((:file "webkit")))
1,030
Common Lisp
.asd
27
33.62963
75
0.683317
bohonghuang/cl-gtk4
213
9
23
LGPL-3.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
fb3628600b5cb535b5917f2fac0bf178d4976eb6d8bda3df4f6820f10a8f4554
331
[ -1 ]
332
cl-gtk4.sourceview.asd
bohonghuang_cl-gtk4/cl-gtk4.sourceview.asd
(defsystem cl-gtk4.sourceview :version "1.0.0" :author "Bohong Huang <[email protected]>" :maintainer "Bohong Huang <[email protected]>" :license "LGPLv3" :description "GtkSourceView bindings for Common Lisp." :homepage "https://github.com/bohonghuang/cl-gtk4" :bug-tracker "https://github.com/bohonghuang/cl-gtk4/issues" :source-control (:git "https://github.com/bohonghuang/cl-gtk4.git") :serial t :components ((:file "sourceview")) :depends-on (#:cl-gobject-introspection-wrapper #:cl-gtk4)) (uiop:register-image-restore-hook (lambda () (let ((package (find-package :sourceview))) (when package (setf (symbol-value (find-symbol "*NS*" package)) (uiop:symbol-call :gir :require-namespace "GtkSource" "5")))))) (defsystem cl-gtk4.sourceview/example :depends-on (#:asdf #:cl-gtk4 #:cl-gtk4.sourceview) :build-operation program-op :build-pathname "cl-gtk4-sourceview-example" :entry-point "sourceview.example:main" :pathname "examples/" :components ((:file "sourceview")))
1,067
Common Lisp
.asd
27
35
76
0.695568
bohonghuang/cl-gtk4
213
9
23
LGPL-3.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
b2d05c5c7f48695307b9c524724b9648b70e008cb4142feed5f450632e105de1
332
[ -1 ]
333
cl-gdk4.asd
bohonghuang_cl-gtk4/cl-gdk4.asd
#+sbcl (eval-when (:compile-toplevel :load-toplevel :execute) (sb-int:set-floating-point-modes :traps nil)) (defsystem cl-gdk4 :version "1.0.0" :author "Bohong Huang <[email protected]>" :maintainer "Bohong Huang <[email protected]>" :license "LGPLv3" :description "GDK4 bindings for Common Lisp." :homepage "https://github.com/bohonghuang/cl-gtk4" :bug-tracker "https://github.com/bohonghuang/cl-gtk4/issues" :source-control (:git "https://github.com/bohonghuang/cl-gtk4.git") :serial t :components ((:file "gdk-pixbuf2") (:file "gdk4" :depends-on ("gdk-pixbuf2"))) :depends-on (#:cl-gobject-introspection-wrapper)) (uiop:register-image-restore-hook (lambda () (let* ((namespace "Gdk") (package (find-package (string-upcase namespace)))) (when package (setf (symbol-value (find-symbol "*NS*" package)) (uiop:symbol-call :gir :require-namespace namespace "4.0")))) (let* ((namespace "GdkPixbuf") (package (find-package '#:gdk-pixbuf2))) (when package (setf (symbol-value (find-symbol "*NS*" package)) (uiop:symbol-call :gir :require-namespace namespace "2.0")))))) (defsystem cl-gdk4/example :depends-on (#:asdf #:cl-gtk4 #:cl-gdk4 #:cl-cairo2) :build-operation program-op :build-pathname "cl-gdk4-example" :entry-point "gdk4.example:cairo-test" :pathname "examples/" :components ((:file "gdk4") (:file "gdk4-cairo" :depends-on ("gdk4"))))
1,531
Common Lisp
.asd
39
33.358974
76
0.646743
bohonghuang/cl-gtk4
213
9
23
LGPL-3.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
9b32082df3b70bd1382bd409fc6cfaa53751c936c7f1bfbbfb8ee490cada8961
333
[ -1 ]
334
cl-gtk4.asd
bohonghuang_cl-gtk4/cl-gtk4.asd
(defsystem cl-gtk4 :version "1.0.0" :author "Bohong Huang <[email protected]>" :maintainer "Bohong Huang <[email protected]>" :license "LGPLv3" :description "GTK4 bindings for Common Lisp." :homepage "https://github.com/bohonghuang/cl-gtk4" :bug-tracker "https://github.com/bohonghuang/cl-gtk4/issues" :source-control (:git "https://github.com/bohonghuang/cl-gtk4.git") :serial t :components ((:file "gtk4")) :depends-on (#:uiop #:cl-gobject-introspection-wrapper #:cl-glib #:cl-gio #:cl-gobject)) ;; (uiop:register-image-dump-hook (lambda () (uiop:symbol-call :tg :gc :full t) (sleep 1.0))) (uiop:register-image-restore-hook (lambda () (let* ((namespace "Gtk") (package (find-package (string-upcase namespace)))) (when package (setf (symbol-value (find-symbol "*NS*" package)) (uiop:symbol-call :gir :require-namespace namespace "4.0")))))) (defsystem cl-gtk4/example :depends-on (#:asdf #:bordeaux-threads #:cl-glib #:cl-gtk4) :build-operation program-op :build-pathname "cl-gtk4-example" :entry-point "gtk4.example:simple-menu" :pathname "examples/" :components ((:file "gtk4")))
1,204
Common Lisp
.asd
30
35.1
93
0.665243
bohonghuang/cl-gtk4
213
9
23
LGPL-3.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
455f407b967a0392d7a54644a1eeb9ac10f650244a107bd09a33b0264f8b16f4
334
[ -1 ]
335
cl-gtk4.adw.asd
bohonghuang_cl-gtk4/cl-gtk4.adw.asd
(defsystem cl-gtk4.adw :version "1.0.0" :author "Bohong Huang <[email protected]>" :maintainer "Bohong Huang <[email protected]>" :license "LGPLv3" :description "Libadwaita bindings for Common Lisp." :homepage "https://github.com/bohonghuang/cl-gtk4" :bug-tracker "https://github.com/bohonghuang/cl-gtk4/issues" :source-control (:git "https://github.com/bohonghuang/cl-gtk4.git") :serial t :components ((:file "adw")) :depends-on (#:cl-gobject-introspection-wrapper #:cl-gtk4)) (uiop:register-image-restore-hook (lambda () (let* ((namespace "Adw") (package (find-package (string-upcase namespace)))) (when package (setf (symbol-value (find-symbol "*NS*" package)) (uiop:symbol-call :gir :require-namespace namespace)))))) (defsystem cl-gtk4.adw/example :depends-on (#:asdf #:cl-gtk4 #:cl-gtk4.adw) :build-operation program-op :build-pathname "cl-gtk4-libadwaita-example" :entry-point "adw.example:main" :pathname "examples/" :components ((:file "adw")))
1,059
Common Lisp
.asd
28
33.071429
70
0.6793
bohonghuang/cl-gtk4
213
9
23
LGPL-3.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
f732e7388d1237d9261ecc3fedf53e736d84ae1c3ce558d246a58e36b66c7b52
335
[ -1 ]
352
example-ui-file.ui
bohonghuang_cl-gtk4/examples/example-ui-file.ui
<?xml version='1.0' encoding='UTF-8'?> <!-- Created with Cambalache 0.12.1 --> <interface> <!-- interface-name hellobuilder.ui --> <requires lib="gtk" version="4.10"/> <object class="GtkApplicationWindow" id="window"> <property name="title">UI File Example</property> <child> <object class="GtkBox"> <property name="orientation">vertical</property> <child> <object class="GtkLabel" id="label"> <property name="height-request">50</property> <property name="label">&lt;i&gt;Hello&lt;/i&gt; &lt;b&gt;World&lt;/b&gt;!</property> <property name="use-markup">True</property> <property name="vexpand">True</property> <property name="width-request">100</property> </object> </child> <child> <object class="GtkButton" id="button-exit"> <property name="label">Exit</property> </object> </child> </object> </child> </object> </interface>
1,011
Common Lisp
.l
28
28.535714
96
0.591048
bohonghuang/cl-gtk4
213
9
23
LGPL-3.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
6f3f7f0ce7405a389c1892ca0bbb245a21e8132ee545e115a6d910db3c7d7eb0
352
[ -1 ]
369
cl-dino.lisp
VitoVan_cl-dino/cl-dino.lisp
(eval-when (:compile-toplevel :load-toplevel :execute) #-clautogui (load "cl-autogui.lisp") #-clppcre (ql:quickload 'cl-ppcre)) (defpackage #:cl-dino (:use #:common-lisp #:cl-autogui) (:export #:dino-jump #:dino-play)) (in-package #:cl-dino) ;; === These keycode values should be changed according to your keyboard === (defvar *f5-key* 71) (defvar *space-key* 65) (defvar *down-key* 116) (defparameter *scan-interval* 1/60) ;; === These coordinates values should be changed according to your screen === ;; game over text position (position of 'G' and 'R') (defvar *game-over-points* '((385 175) (480 220) (575 173))) ;; background points (defvar *background-color-point* '(50 150)) ;; dino on the ground (defvar *dino-standing-points* '((207 238) (242 223))) ;; dino bending points (defvar *dino-bending-points* '((209 240) (262 243))) ;; the block search squre (x y weight height) (defvar *block-search-squre* '(265 220 500 35)) ;; Position to click (focus the game) (defvar *mouse-focus-point* '(190 150)) ;; the y of middle flying bird (defvar *middle-bird-y* 220) (defun first-pixel->color (snap-data) (cl-autogui::pixel->color snap-data 0 0)) (defun points-exists? (points &key color (test #'(lambda (a b) (not (equal a b))))) (let* ((all-points (if color points (push *background-color-point* points))) (all-colors (apply #'x-get-color all-points)) (base-color (or color (pop all-colors))) (other-colors all-colors)) (every #'identity (mapcar #'(lambda (c) (funcall test base-color c)) other-colors)))) (defun game-over? () (points-exists? *game-over-points*)) (defun find-block () "find properties of the first block (cactus or bird) in front of dino, (x y)" (let* ((x (first *block-search-squre*)) (y (second *block-search-squre*)) (w (third *block-search-squre*)) (h (fourth *block-search-squre*)) (snap-data (x-snapshot :x x :y y :width w :height h)) (first-color (first-pixel->color snap-data))) (x-find-color first-color :x x :y y :width w :height h :test #'(lambda (a b) (not (equal a b))) :data snap-data))) (defun dino-jump () (when (or ; only jump if dino is on the ground. (points-exists? *dino-standing-points*) (points-exists? *dino-bending-points*)) (x-key-up *down-key*) (x-press *space-key*) (sleep 0.1))) (defun dino-bend () (when (points-exists? *dino-standing-points*) ; only bend if dino is on the ground. (x-key-down *down-key*))) (defparameter *distance-stack* nil) (defun dino-restart () ;; move to dino and click (setf *distance-stack* nil) (x-click :x (car *mouse-focus-point*) :y (cadr *mouse-focus-point*)) (sleep 1) (x-press *f5-key*) (sleep 1) (x-press *space-key*) ;; move away, annoying mouse (x-move (- (car *mouse-focus-point*) 150) (cadr *mouse-focus-point*))) (defun find-gap (predicate lst &key (test #'>)) (if (or (null lst) (null (cdr lst)) (not (funcall predicate (car lst))) (not (funcall predicate (cadr lst)))) -1 (if (funcall test (car lst) (cadr lst)) 1 (1+ (find-gap predicate (cdr lst) :test test))))) (defun chunk-list (predicate lst &key (test #'>)) (labels ((rec (lst acc) (let* ((n (find-gap predicate lst :test test)) (rest (when (not (equal -1 n)) (nthcdr n lst)))) (if (and (consp rest) (not (zerop n))) (rec rest (cons (subseq lst 0 n) acc)) (nreverse (cons lst acc)))))) (if lst (rec lst nil) nil))) (defun map-a/b (fn lst) (if (cdr lst) (cons (funcall fn (car lst) (cadr lst)) (when (cddr lst) (map-a/b fn (cdr lst)))) nil)) (defun avg-speed () "px per second" (when (< (length *distance-stack*) 2) (return-from avg-speed 1)) ;; cut *distance-stack*, only save recent 1000 values, for memory good. (when (> (length *distance-stack*) 1000) (setf *distance-stack* (subseq *distance-stack* 0 1000))) (let ((block-dist-group (chunk-list #'numberp *distance-stack*))) (labels ((cal-avg (lst) (if (> (length lst) 0) (/ (apply #'+ lst) (length lst)) 0)) (cal-speed (dist-list) (cal-avg (map-a/b #'(lambda (a b) (/ (- b a) *scan-interval*)) dist-list)))) (round (cal-avg (mapcar #'cal-speed block-dist-group)))))) (defun jump? (distance speed) (when (and (numberp distance) (numberp speed) (not (zerop speed))) (<= (/ distance speed) 0.15))) (defmacro dino-format (destination control-string &rest format-arguments) `(format ,destination ,(cl-ppcre:regex-replace-all "~S" control-string "~VS") ,@(mapcan #'(lambda (x) (list 10 x)) format-arguments))) (defun dino-play () "Awesome! http://imgur.com/kjRnw5G" (dino-restart) (loop (when (game-over?) (return)) (let* ((block-position (find-block)) (block-distance (when block-position (- (car block-position) (first *block-search-squre*)))) (block-y (cadr block-position)) (speed (avg-speed)) (should-jump (jump? block-distance speed))) (when block-distance (push block-distance *distance-stack*)) (dino-format t "Distance: ~S Jump?: ~S Speed: ~S Y-Coord: ~S~%" block-distance should-jump speed block-y) (cond ((null block-position) nil) ((= *middle-bird-y* block-y) (dino-bend)) ((= block-distance 0) nil) (should-jump (dino-jump)))) (sleep *scan-interval*)))
5,795
Common Lisp
.lisp
144
33.458333
112
0.591652
VitoVan/cl-dino
213
11
0
GPL-3.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
41a5ad38b6becade78dbd1dafe18085b19f014726cded6f01d87ff7d48144d1f
369
[ -1 ]
370
cl-autogui.lisp
VitoVan_cl-dino/cl-autogui.lisp
(eval-when (:compile-toplevel :load-toplevel :execute) #-clx (ql:quickload 'clx) #-zpng (ql:quickload 'zpng)) (defpackage #:cl-autogui (:use #:common-lisp #:xlib) (:export #:x-position #:x-size #:x-position #:x-move #:x-mouse-down #:x-mouse-up #:x-click #:x-dbclick #:x-vscroll #:x-hscroll #:x-scroll #:x-key-down #:x-key-up #:x-press #:x-snapshot #:x-find-color #:x-get-color)) (in-package #:cl-autogui) (defmacro with-default-display ((display &key (force nil)) &body body) `(let ((,display (open-default-display))) (unwind-protect (unwind-protect ,@body (when ,force (display-force-output ,display))) (close-display ,display)))) (defmacro with-default-display-force ((display) &body body) `(with-default-display (,display :force t) ,@body)) (defmacro with-default-screen ((screen) &body body) (let ((display (gensym))) `(with-default-display (,display) (let ((,screen (display-default-screen ,display))) ,@body)))) (defmacro with-default-window ((window) &body body) (let ((screen (gensym))) `(with-default-screen (,screen) (let ((,window (screen-root ,screen))) ,@body)))) (defun x-position () (with-default-window (w) (query-pointer w))) (defun x-size () (with-default-screen (s) (values (screen-width s) (screen-height s)))) (defun x-move (x y) (if (and (integerp x) (integerp y)) (with-default-display-force (d) (xlib/xtest:fake-motion-event d x y)) (error "Integer only for position, (x: ~S, y: ~S)" x y))) (defun mklist (obj) (if (and (listp obj) (not (null obj))) obj (list obj))) (defmacro defun-with-actions (name params actions &body body) "This macro defun a function which witch do mouse or keyboard actions, body is called on each action." `(defun ,name ,params (mapcar #'(lambda (action) ,@body) (mklist ,actions)))) (defun perform-mouse-action (press? button &key x y) (and x y (x-move x y)) (with-default-display-force (d) (xlib/xtest:fake-button-event d button press?))) (macrolet ((def (name actions) `(defun-with-actions ,name (&key (button 1) x y) ,actions (funcall #'perform-mouse-action action button :x x :y y)))) (def x-mouse-down t) (def x-mouse-up nil) (def x-click '(t nil)) (def x-dbclick '(t nil t nil))) (defmacro with-scroll (pos neg clicks x y) `(let ((button (cond ((= 0 ,clicks) nil) ((> 0 ,clicks) ,pos) ; scroll up/right ((< 0 ,clicks) ,neg)))) ; scroll down/left (dotimes (_ (abs ,clicks)) (x-click :button button :x ,x :y ,y)))) (defun x-vscroll (clicks &key x y) (with-scroll 4 5 clicks x y)) (defun x-scroll (clicks &key x y) (x-vscroll clicks :x x :y y)) (defun x-hscroll (clicks &key x y) (with-scroll 7 6 clicks x y)) (defun perform-key-action (press? keycode) ; use xev to get keycode (with-default-display-force (d) (xlib/xtest:fake-key-event d keycode press?))) (macrolet ((def (name actions) `(defun-with-actions ,name (keycode) ,actions (funcall #'perform-key-action action keycode)))) (def x-key-down t) (def x-key-up nil) (def x-press '(t nil))) (defun raw-image->png (data width height) (let* ((png (make-instance 'zpng:png :width width :height height :color-type :truecolor-alpha :image-data data)) (data (zpng:data-array png))) (dotimes (y height) (dotimes (x width) ;; BGR -> RGB, ref code: https://goo.gl/slubfW ;; diffs between RGB and BGR: https://goo.gl/si1Ft5 (rotatef (aref data y x 0) (aref data y x 2)) (setf (aref data y x 3) 255))) png)) (multiple-value-bind (default-width default-height) (x-size) (defun x-snapshot (&key (x 0) (y 0) (width default-width) (height default-height) (delay 0) path) "Return RGB data array (The dimensions correspond to the height, width, and pixel components, see comments in x-find-color for more details), or write to file (PNG only), depend on if you provide the path keyword" (sleep delay) (with-default-window (w) (let ((image (raw-image->png (get-raw-image w :x x :y y :width width :height height :format :z-pixmap) width height))) (if path (let* ((ext (pathname-type path)) (path (if ext path (concatenate 'string path ".png"))) (png? (or (null ext) (equal ext "png")))) (cond (png? (zpng:write-png image path)) (t (error "Only PNG file is supported")))) (zpng:data-array image))))) (defun x-find-color (rgba &key (x 0) (y 0) (width default-width) (height default-height) (test #'equal) (data (x-snapshot :x x :y y :width width :height height))) "Search screen for specific Color (PNG's RGBA mode, where 'A' should be 0~255)" (labels ((get-rgba (data x y) (mapcar #'(lambda (i) (aref data y x i)) ;; why reversed order? http://xach.com/lisp/zpng/#data-array ;; what is row-major? https://goo.gl/eF1F28 '(0 1 2 3)))) (dotimes (s-x width) (dotimes (s-y height) (when (funcall test rgba (get-rgba data s-x s-y)) (return-from x-find-color (list (+ x s-x) (+ y s-y))))))))) (defun pixel->color (image-data x y) (funcall #'(lambda (data) (mapcar #'(lambda (i) (aref data y x i)) '(0 1 2 3))) image-data)) (defun x-get-color (&rest coordinates) "Get colors by coordinates" (with-default-window (w) (let* ((x-list (mapcar #'(lambda (c) (car c)) coordinates)) (y-list (mapcar #'(lambda (c) (cadr c)) coordinates)) (min-x (apply #'min x-list)) (max-x (apply #'max x-list)) (min-y (apply #'min y-list)) (max-y (apply #'max y-list)) (width (1+ (- max-x min-x))) (height (1+ (- max-y min-y))) (x min-x) (y min-y) (image-data (zpng:data-array (raw-image->png (get-raw-image w :x x :y y :width width :height height :format :z-pixmap) width height)))) (mapcar #'(lambda (cod) (pixel->color image-data (- (car cod) x) (- (cadr cod) y))) coordinates))))
7,070
Common Lisp
.lisp
189
27.78836
88
0.533839
VitoVan/cl-dino
213
11
0
GPL-3.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
55bd63a39effcb63c79a349db6d970b238f37e7fa5ccc1fcf636dd6b4a4cb10a
370
[ -1 ]
374
FUNDING.yml
VitoVan_cl-dino/.github/FUNDING.yml
# These are supported funding model platforms github: VitoVan # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] patreon: # Replace with a single Patreon username open_collective: # Replace with a single Open Collective username ko_fi: # Replace with a single Ko-fi username tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry liberapay: # Replace with a single Liberapay username issuehunt: # Replace with a single IssueHunt username otechie: # Replace with a single Otechie username lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
811
Common Lisp
.l
12
66.5
93
0.793233
VitoVan/cl-dino
213
11
0
GPL-3.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
87b75b14538c0d5aedd5bc1570ae5ebb5df3bbcb5f36c48f587a85ed61e610e4
374
[ -1 ]
389
bootstrap.lisp
joinr_clclojure/bootstrap.lisp
;;This is the basis for bootstrapping clojure onto common lisp. ;;I figure if I can define the primitive forms that clojure requires, ;;there's already a ton of clojure written in clojure. The clojurescript ;;runtime actually has a significant portion of clojure defined via protocols, ;;which given limited forms, provides a pretty slick way to bootstrap an ;;implementation. ;;A couple of big hurdles: ;;1) Lisp1 vs Lisp2. I'll hack the evaluator for this. ;;2) Persistent structures. Already built Pvector and 1/2 done with Pmap. ;;3) Protocols. Already implemented as generic functions. ;;4) Multimethods. Need to find a way to implement multiple dispatch. ;;5) Reader. CL macros use , and ,@ in place of ~ and ~@ in Clojure. ;; We'll need to either cook the common lisp reader, or ;; build a separate clojure reader that will perform the ;; appropriate replacements. ;; @ is a literal for #'deref in clojure ;; , is whitespace in clojure. ;; [] denote vectors -> already have a reader macro in pvector.lisp ;; {} denote maps -> already have a reader macro in pmap.lisp ;; #{} denote sets ;;6) Destructuring. This may be a bit tricky, although there are a limited number of ;; clojure forms. Since we have reader ;;7)Seq library. This shouldn't be too hard. I already have a lazy list lib prototype ;; as well as generic functions for the basic ops. I think I'll try to ;; use the protocols defined in the clojurescript version as much possible, ;; rather than baking in a lot of the seq abstraction in the host language ;; like clojure does. (defpackage :clclojure.base (:use :common-lisp :common-utils :clclojure.keywordfunc :clclojure.lexical :clclojure.pvector :clclojure.cowmap :clclojure.protocols :clclojure.eval) (:shadow :let :deftype :defmacro :map :reduce :first :rest :second :dotimes :nth :cons :count :do :get :assoc :when-let :vector :odd? :even? :zero? :identity :filter :loop :if-let :throw :list* :cond :=) (:export :def :defn :fn :meta :with-meta :str :symbol? :first :rest :second :next :deftype :defprotocol :reify :extend-type :nil? :identical? :extend-protocol :let :into :take :drop :filter :seq :vec :empty :conj :concat :map :reduce :dotimes :nth :cons :count :do :get :assoc :when-let :if-let :ns :even? :pos? :zero? :odd? :vector :hash-map :inc :dec :identity :loop :chunk-first :doall :chunk-buffer :every? :chunk-rest :interleave :ffirst :partition :seq->list :fnext :chunk-cons :nthrest :dorun :chunked-seq? :->iterator :chunk-append :throw :ex-info :ex-cause :ex-message :ex-data :list* :cond :try := :true :false) ; :defmacro ) (in-package clclojure.base) ;;move this later... (EVAL-WHEN (:compile-toplevel :load-toplevel :execute) ;;temporary hacks... (define-symbol-macro true 't) (define-symbol-macro false nil) ;;convenient placeholder (defun ns (name &rest opts) (eval `(progn (defpackage ,name (:use :clclojure.base :common-lisp) (:shadowing-import-from :clclojure.base :let :deftype :defmacro :map :reduce :first :rest :second :dotimes :nth :cons :count :do :get :assoc :when-let :vector)) (in-package ,name)))) (common-lisp:defmacro defmacro (name args &rest body) ;`(clclojure.eval:defmacro/literal-walker ,name ,args ,@body) `(common-lisp:defmacro ,name ,args ,@body) ) (defun vector? (x) (typep x 'clclojure.pvector::pvec)) ;;Let's hack let to allow us to infer vector-binds ;;as a clojure let definition... (defmacro let (bindings &body body) (if ;(eq (common-lisp:first bindings) 'persistent-vector) (vector? bindings) `(unified-let* (,@(partition! 2 (vector-to-list bindings))) ,@body) `(cl:let ,bindings ,@body))) (defun macro? (s) (when (macro-function s) 't)) (defun function? (s) (fboundp s)) ;;weak hack around lack of read-time vector creation. (defun vector-form? (expr) (or (vector? expr) (eq (common-lisp:first expr) 'persistent-vector)))) (define-condition not-implemented (error) ()) (define-condition uneven-arguments (error) ()) (defgeneric destructure (bindings)) ;;a single function definition (EVAL-WHEN (:compile-toplevel :load-toplevel :execute) (defstruct fn-def name args body) ;;a macro definition -- later (defstruct macro-def name args body)) ;;At compile-time, [x y] -> (persistent-vector x y). ;;This is upsetting us... (defmacro quoted-vec (v) (if (vector? v) `(quote ,v);;`(persistent-vector ,@(mapcar #'quote-sym (vector-to-list v))) `(persistent-vector ,@(mapcar #'quote-sym (rest v))))) (defun variadic (v) (member '& (vector-to-list v))) ;;Todo: move this out to CLOS? ;;parse a clojure style function definition. ;; (defmacro read-fn (arg-vec body) ;; `(make-fn-def :args (quoted-vec ,arg-vec) ;; :body (quote ,body))) (EVAL-WHEN (:compile-toplevel :load-toplevel :execute) (defun read-fn (arg-vec body &optional name) (make-fn-def :name name :args arg-vec :body body))) (defgeneric arity (fd)) (defmethod arity ((fd clclojure.pvector::pvec)) (values (vector-count fd) (variadic fd))) (defmethod arity ((fd fn-def)) (arity (slot-value fd 'args))) ;;since clojure allows multiple bodies, with fixed arity for each body, we ;;compose multiple function (arg body) pairs into a list of function definitions. ;;We should then be able to dispatch on the count of args, simply invoking ;;the appropriate function matched to arity. ;; (defmacro fn* (&rest specs) ;; `(list ,@(mapcar (lambda (vb) `(read-fn ,(common-lisp:first vb) ,(second vb))) specs))) (EVAL-WHEN (:compile-toplevel :load-toplevel :execute) ;; (defun fn* (&rest specs) ;; (let* ((fst (car specs)) ;; (named? nil) ;; (name (if (symbolp (common-lisp:first fst)) ;; (progn (setf named? t) ;; (common-lisp:first fst) ) ;; (symb (symbol-name (gensym "fn_"))))) ;; (specs (if named? (common-lisp:rest (common-lisp:first specs)) specs))) ;; (pprint (list fst named? name specs)) ;; `(,@(mapcar (lambda (vb) ;; (pprint vb) ;; (read-fn (common-lisp:first vb) ;; (if (cadr vb) ;; (common-lisp:cons 'progn (common-lisp:rest vb)) ;; (second vb)) ;; name)) ;; specs ;; )))) (defun fn* (name &rest specs) `(,@(mapcar (lambda (vb) (read-fn (common-lisp:first vb) (if (cadr vb) (common-lisp:cons 'progn (common-lisp:rest vb)) (common-lisp:second vb)) name)) specs))) ;; (defparameter test-fn ;; '(fn* ([x] x) ;; ([x y] (+ x y)) ;; ([x y & xs] (common-lisp:reduce #'+ xs :initial-value (+ x y))))) (defstruct arg-parse lambda-list outer-let) (define-condition no-matching-function (error) ()) (define-condition multiple-variadic-functions (error) ()) ;;this is going to be somewhat tricky, since we'll probably have a little state ;;machine that parses the args, possibly destructuring recursively. Don't know all ;;the cases yet, but we'll need to be able to destructure vectors and maps into ;;corresponding lambda lists. (defun parse-args (args) (make-arg-parse :lambda-list (mapcar (lambda (x) (if (and (symbolp x) (string-equal (symbol-name x) "&")) '&rest x)) (vector-to-list args))))) ;;Compile a clojure fn special form into a common lisp lambda (EVAL-WHEN (:compile-toplevel :load-toplevel :execute) (defgeneric fndef->sexp (fd)) ;; (defmethod fndef->sexp ((fd fn-def)) ;; (with-slots (args body) fd ;; (with-slots (lambda-list outer-let) (parse-args args) ;; (let ((interior (if outer-let `(let* ,outer-let ,body) ;; body))) ;; `(lambda ,lambda-list ,interior))))) (defmethod fndef->sexp ((fd fn-def)) (with-slots (args body name) fd (with-slots (lambda-list outer-let) (parse-args args) (let ((interior (if outer-let `(let* ,outer-let ,body) body))) `(named-fn ,name ,lambda-list ,interior))))) ;;parse a list of function definitions into an n-lambda dispatching function. ;; (defmethod fndef->sexp ((fd common-lisp:cons)) ;; (if (= (length fd) 1) (fndef->sexp (common-lisp:first fd)) ;simple case ;; ;;case with multiple function definitions. ;; (progn (pprint fd) ;; `(common-utils:lambda* ,@(mapcar (lambda (body) ;; (common-lisp:rest (fndef->sexp body))) fd))))) ;; (defmethod fndef->sexp ((fd common-lisp:cons)) ;; (if (= (length fd) 1) (fndef->sexp (common-lisp:first fd)) ;simple case ;; ;;case with multiple function definitions. ;; (let ((name (fn-def-name (common-lisp:first fd)))) ;; `(common-utils:lambda* ,@(mapcar (lambda (body) ;; (common-lisp:rest (common-lisp:rest (fndef->sexp body)))) fd))))) (defmethod fndef->sexp ((fd common-lisp:cons)) (if (common-lisp:= (length fd) 1) (fndef->sexp (common-lisp:first fd)) ;simple case ;;case with multiple function definitions. (let ((name (fn-def-name (common-lisp:first fd)))) `(common-utils:named-fn* ,name ,@(mapcar (lambda (body) (common-lisp:rest (common-lisp:rest (fndef->sexp body)))) fd))))) ) ;;Clojure's anonymous function special form. ;;Todo: support destructuring in the args. ;; (defmacro fn (&rest specs) ;; (pprint specs) ;; (let* ((res ;; (cond ((symbolp (common-lisp:first specs)) ;; (fndef->sexp (fn* (cons (first specs) (list (rest specs)))))) ;; ((vector-form? (common-lisp:first specs)) ;; (fndef->sexp (fn* specs))) ;; ;;TODO get rid of this eval.... ;; (t ;; (fndef->sexp (apply #'fn* specs)))))) ;; `(,@(clclojure.eval::custom-eval-bindings (sb-cltl2::macroexpand-all res) nil)))) (defmacro fn (&rest specs) (let* ((hd (common-lisp:first specs)) (name (if (symbolp hd) hd (symb (symbol-name (gensym "fn_"))))) (specs (if (symbolp hd) (common-lisp:rest specs) specs)) (res (if (vector-form? (common-lisp:first specs)) (fndef->sexp (fn* name specs)) ;;TODO get rid of this eval.... (let ((bodies (apply #'fn* (common-lisp:cons name specs)))) (fndef->sexp bodies))))) `(,@(clclojure.eval::custom-eval-bindings (sb-cltl2::macroexpand-all res) nil)))) ;;def ;;=== ;;Experimental. Not sure of how to approach this guy. ;;for now, default to everything being public / exported. ;;that should be toggled via metadata in real implementation. (eval-when (:compile-toplevel :load-toplevel :execute) (defmacro def (var &rest init-form) `(progn (defparameter ,var ,@init-form) (with-meta (quote ,var) '((SYMBOL . T) (DOC . "none"))) (when (functionp (symbol-value (quote ,var))) (setf (symbol-function (quote ,var)) (symbol-value (quote ,var)))) (export ',var) (quote ,var) ))) ;;A CHEAP implementation of defn, replace this... (defmacro defn (name args &rest body) `(def ,name (fn ,name ,args ,@body))) ;;Clojure Transformations (PENDING) ;;================================ ;;we need some basic transformations.... ;;I guess we can write a simple clojure reader by swapping some symbols around.. ;;maybe even use read macros... ;;Clojure -- Common Lisp ;;@x (deref x) -> used in quasiquoted expression, splice-collection ,@ ;;~x (insert x)? used to escape a quasiquote -> ,x ;;one simple transform is to scan the clojure expression, and change the following: ;;~ -> , ;;~@ -> ,@ ;;@x -> (deref x) ;;need to implement deref ;;[x] -> (pvector x) ;;more or less implemented ;;{x y} -> (hash-map x y) ;;(Blah. x) -> (make-Blah x) ;;CLOS constructor ;;(. obj method args) -> ((slot-value obj method) args) ;;(. obj (method args)) -> ((slot-value obj method) args) ;;(. obj method) -> ((slot-value obj method)) ;;(.method obj args) -> (slot-value obj method) ;;CLOS accessor ;;(def x val) -> (defparameter x val) ;;(let [x y] expr) -> (let* ((x y)) expr) ;;(some-namespace-alias/the-function x) -> (some-package-alias::the-function x) ;;(ns blah) -> (defpackage blah) ;;#"some-regex" -> (make-regex "some-regex") ;;need to use cl-ppre probably... (defmacro doc (v) `(pprint (rest (common-lisp:assoc 'DOC (meta ,v))))) (defmacro do (&rest exprs) `(progn ,@exprs)) ;;Meta Data ;;========= ;;I think we want to use persistent maps for meta data, as clojure does. ;;I want to get the stubs in place, and am using property lists with a 'meta ;;entry pointing at an assoc list for now. ;;These should be pulled out into a protocol. (defmacro symbol-meta (symb) `(common-lisp:get (quote ,symb) 'meta)) (defmacro with-symbol-meta (symb m) `(setf (common-lisp:get (quote ,symb) 'meta) ,m)) (eval-when (:compile-toplevel :load-toplevel :execute) (defun meta (obj) (-meta obj)) (defun with-meta (obj m) (-with-meta obj m))) ;;One thing about metadata, and how it differs from property lists: ;;You can call meta on datastructures, or objects, and get a map back. ;;Symbols can have meta called on them with (meta #'the-symbol), which ;;uses sharp-quote to get the symbol, vs the symbol-name. ;;Clojure is a lisp-1, so we need to ensure that everything, even ;;functions, gets bound into the a single namespace. ;;another way to do this is to have clojure-specific symbols be actual ;;clos objects, which have meta data fields automatically. Then we ;;lose out on all the built in goodies from common lisp though. ;;Clojure Core (PENDING) ;;====================== ;;hacky way to accomodate both forms... ;;we know we're in clojure if the args are vector (defmacro deftype (&rest args) (if (vector? (common-lisp:nth 1 args)) `(clojure-deftype ,@args) `(common-lisp::deftype ,@args))) ;;reify is interesting. ;;we generate an instance of an anonymous class, ;;ala deftype, with protocol implementations. ;;TODO: look at the consequences of having bunches of ;;anonymous classes laying around, say evaluating ;;reify several times...Should we garbage collect this? ;;Or does that cut into dynamicity? (defmacro reify (&rest implementations) (let [classname (gentemp "REIFY") ctor (gensym "CONSTRUCTOR")] `(let ((,ctor (clojure-deftype ,classname ,'[] ,@implementations))) (funcall ,ctor)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;; core protocols ;;;;;;;;;;;;; ;;Need to get back to this guy...multiple arity is not yet implemented... (eval-when (:compile-toplevel :load-toplevel :execute) (defprotocol IFn (-invoke [this] [this a] [this a b] [this a b c] [this a b c d] [this a b c d e] [this a b c d e f] [this a b c d e f g] [this a b c d e f g h] [this a b c d e f g h i] [this a b c d e f g h i j] [this a b c d e f g h i j k] [this a b c d e f g h i j k l] [this a b c d e f g h i j k l m] [this a b c d e f g h i j k l m n] [this a b c d e f g h i j k l m n o] [this a b c d e f g h i j k l m n o p] [this a b c d e f g h i j k l m n o p q] [this a b c d e f g h i j k l m n o p q s] [this a b c d e f g h i j k l m n o p q s t] [this a b c d e f g h i j k l m n o p q s t rest])) ;;These work (defprotocol ICounted (-count [coll] "constant time count")) (defprotocol IEmptyableCollection (-empty [coll])) (defprotocol ICollection (-conj [coll o])) (defprotocol IOrdinal (-index [coll])) ;;this will break. current implementation of defprotocol doesn't allow for ;;multiple arity functions like this. Need to handle variadic functions... (defprotocol IIndexed (-nth [coll n] [coll n not-found])) (defprotocol ASeq) (defprotocol ISeq (-first [coll]) (-rest [coll])) (defprotocol INext (-next [coll])) (defprotocol ILookup (-lookup [o k] [o k not-found])) (defprotocol IAssociative (-contains-key? [coll k]) (-entry-at [coll k]) (-assoc [coll k v])) (defprotocol IMap (-assoc-ex [coll k v]) (-dissoc [coll k])) (defprotocol IMapEntry (-key [coll]) (-val [coll])) (defprotocol ISet (-disjoin [coll v])) (defprotocol IStack (-peek [coll]) (-pop [coll])) (defprotocol IVector (-assoc-n [coll n val])) (defprotocol IDeref (-deref [o])) (defprotocol IDerefWithTimeout (-deref-with-timeout [o msec timeout-val])) (defprotocol IMeta (-meta [o])) (defprotocol IWithMeta (-with-meta [o meta])) (defprotocol IReduce (-reduce [coll f] [coll f start])) (defprotocol IKVReduce (-kv-reduce [coll f init])) (defprotocol IEquiv (-equiv [o other])) (defprotocol IHash (-hash [o])) (defprotocol ISeqable (-seq [o])) (defprotocol ISequential "Marker interface indicating a persistent collection of sequential items") (defprotocol IList "Marker interface indicating a persistent list") (defprotocol IRecord "Marker interface indicating a record object") (defprotocol IReversible (-rseq [coll])) (defprotocol ISorted (-sorted-seq [coll ascending?]) (-sorted-seq-from [coll k ascending?]) (-entry-key [coll entry]) (-comparator [coll])) ;; (defprotocol ^:deprecated IPrintable ;; "Do not use this. It is kept for backwards compatibility with existing ;; user code that depends on it, but it has been superceded by IPrintWithWriter ;; User code that depends on this should be changed to use -pr-writer instead." ;; (-pr-seq [o opts])) (defprotocol IWriter (-write [writer s]) (-flush [writer])) (defprotocol IPrintWithWriter "The old IPrintable protocol's implementation consisted of building a giant list of strings to concatenate. This involved lots of concat calls, intermediate vectors, and lazy-seqs, and was very slow in some older JS engines. IPrintWithWriter implements printing via the IWriter protocol, so it be implemented efficiently in terms of e.g. a StringBuffer append." (-pr-writer [o writer opts])) (defprotocol IPending (-realized? [d])) (defprotocol IWatchable (-notify-watches [this oldval newval]) (-add-watch [this key f]) (-remove-watch [this key])) (defprotocol IEditableCollection (-as-transient [coll])) (defprotocol ITransientCollection (-conj! [tcoll val]) (-persistent! [tcoll])) (defprotocol ITransientAssociative (-assoc! [tcoll key val])) (defprotocol ITransientMap (-dissoc! [tcoll key])) (defprotocol ITransientVector (-assoc-n! [tcoll n val]) (-pop! [tcoll])) (defprotocol ITransientSet (-disjoin! [tcoll v])) (defprotocol IComparable (-compare [x y])) (defprotocol IChunk (-drop-first [coll])) (defprotocol IChunkedSeq (-chunked-first [coll]) (-chunked-rest [coll])) (defprotocol IChunkedNext (-chunked-next [coll])) (defprotocol INamed (-name [thing])) ) ;;Extending types to native structures and clojure literals: ;;========================================================== (eval-when (:compile-toplevel :load-toplevel :execute) (extend-type null ICounted (-count [c] 0) IEmptyableCollection (-empty [c] nil) ICollection (-conj [coll itm] (common-lisp:cons itm nil)) IStack (-peek [coll] nil) (-pop [coll] nil) ISeqable (-seq [coll] nil) IHash (-hash [o] (sxhash nil)) IEquiv (-equiv [o other] (error 'not-implemented)) ISeq (-first [o] nil) (-rest [o] nil) IReversible (-rseq [coll] nil)) ;;We got a ton of goodies from ;;sb-sequences namespace to leverage here. ;;good opportunity for iterator-seq... (extend-type sequence ICounted (-count [c] (common-lisp:length c)) ;; IEmptyableCollection (-empty [c] (sb-sequence:make-sequence-like c 0)) ;; ICollection ;; (-conj [coll itm] (cons itm nil)) IStack (-peek [coll] (elt coll 0)) (-pop [coll] (error 'not-implemented)) ISeqable (-seq [coll] (error 'not-implemented)) IHash (-hash [o] (sxhash o)) ;; IEquiv ;; (-equiv [o other] (error 'not-implemented)) ISeq (-first [o] (elt o 0)) ;;TODO pull this over... ;;Probably identical to array-seqs (-rest [o] (error 'not-implemented)) IReversible (-rseq [coll] (reverse coll))) (extend-type clclojure.pvector::pvec ICounted (-count [c] (vector-count c)) IIndexed (-nth [coll n] (nth-vec coll n)) (-nth [coll n not-found] (nth-vec coll n)) IEmptyableCollection (-empty [c] []) ICollection (-conj [coll itm] (vector-conj coll itm)) IVector (-assoc-n [coll n val] (vector-assoc coll n val)) IStack (-peek [coll] (when (not (zerop (-count coll) )) (nth-vec coll 0))) (-pop [coll] (subvec coll 1)) ISeqable (-seq [coll] (vector-to-list coll )) IHash (-hash [o] (error 'not-implemented)) IMapEntry (-key [coll] (-nth coll 0)) (-val [coll] (-nth coll 1)) IEquiv (-equiv [o other] (error 'not-implemented)) IKVReduce (-kv-reduce [coll f init] (error 'not-implemented)) IReversible (-rseq [coll] (error 'not-implemented)) IChunk (-drop-first [coll] (error 'not-implemented)) IChunkedSeq (-chunked-first [coll] (error 'not-implemented)) (-chunked-rest [coll] (error 'not-implemented)) IChunkedNext (-chunked-next [coll] (error 'not-implemented)))) (eval-when (:compile-toplevel :load-toplevel :execute) (extend-type symbol IMeta (-meta [obj] (symbol-meta obj)) IWithMeta (-with-meta [obj m] (with-symbol-meta obj m) obj) IEquiv ;;dirty implementation.... ;;We need to unify qualified and unqualified symbols.. ;;in clojure, symbol equality is a bit more complex ;;since they're equiv iff unqualified. ;;unless we hack the reader to reader qualified ;;symbols as unqual, the preponderance of clojure ;;symbol comparisons will not be strict, so ;;we end up with a lot of unqualified symbols. ;;This is just to paper over the bootstrapping ;;process.... (-equiv [l r] (or (eq l r) (when (not (or (keywordp l) (keywordp r))) (common-lisp:= (sxhash l) (sxhash r))) )) INamed (-name [this] (symbol-name this)) ) ;;not applicable. ;; (extend-type keyword ;; IEquiv ;; ;;dirty implementation.... ;; ;;We need to unify qualified and unqualified symbols.. ;; ;;in clojure, symbol equality is a bit more complex ;; ;;since they're equiv iff unqualified. ;; ;;unless we hack the reader to reader qualified ;; ;;symbols as unqual, the preponderance of clojure ;; ;;symbol comparisons will not be strict, so ;; ;;we end up with a lot of unqualified symbols. ;; ;;This is just to paper over the bootstrapping ;; ;;process.... ;; (-equiv [l r] ;; (or (eq l r) ;; ;;I don't even know if this is possible... ;; ;;I think keywords are always interned ;; ;;in the keyword package. ;; ;; (when (keywordp r) ;; ;; (common-lisp:= (sxhash l) (sxhash r))) ;; )) ;; IHash ;; (-hash [k] (hash-code k)) ;; ) ;;subvector impls... (extend-type clclojure.pvector::subvector ICounted (-count [c] (vector-count c)) IEmptyableCollection (-empty [c] []) ICollection (-conj [coll itm] (vector-conj coll itm)) IVector (-assoc-n [coll n val] (vector-assoc coll n val)) IStack (-peek [coll] (when (not (zerop (-count coll) )) (nth-vec coll 0))) (-pop [coll] (subvec coll 1)) ISeqable (-seq [coll] (vector-to-list coll)) ;poorly implemented. should be arrayseq IHash (-hash [o] (error 'not-implemented)) IMapEntry (-key [coll] (-nth coll 0)) (-val [coll] (-nth coll 1)) IEquiv (-equiv [o other] (error 'not-implemented)) IKVReduce (-kv-reduce [coll f init] (error 'not-implemented)) IReversible (-rseq [coll] (error 'not-implemented)) IChunk (-drop-first [coll] (error 'not-implemented)) IChunkedSeq (-chunked-first [coll] (error 'not-implemented)) (-chunked-rest [coll] (error 'not-implemented)) IChunkedNext (-chunked-next [coll] (error 'not-implemented)) )) (eval-when (:compile-toplevel :load-toplevel :execute) ;;list operations. (extend-type common-lisp:cons ICounted (-count [c] (length c)) IEmptyableCollection (-empty [c] '()) ICollection (-conj [coll itm] (common-lisp:cons itm coll)) IStack (-peek [coll] (common-lisp:first coll)) (-pop [coll] (common-lisp:rest coll)) ISeqable (-seq [coll] coll) IHash (-hash [o] (sxhash o)) IEquiv (-equiv [o other] (error 'not-implemented)) IMapEntry (-key [coll] (common-lisp:first coll)) (-val [coll] (common-lisp:second coll)) ISeq (-first [coll] (common-lisp:first coll)) (-rest [coll] (cdr coll)) ) (extend-type sequences::lazyseq ICounted (-count [c] (sequences:seq-count c)) IEmptyableCollection (-empty [c] '()) ICollection (-conj [coll itm] (sequences::cons itm coll)) IStack (-peek [coll] (sequences::first coll)) (-pop [coll] (sequences::rest coll)) ISeqable (-seq [coll] (sequences::seq coll)) IHash (-hash [o] (sxhash o)) ;;poorly implemented... IEquiv (-equiv [o other] (error 'not-implemented)) IMapEntry (-key [coll] (sequences::first coll)) (-val [coll] (sequences::rest coll)) ISeq (-first [coll] (sequences::first coll)) (-rest [coll] (sequences::rest coll)) ) (extend-type sequences::funcseq ICounted (-count [c] (sequences:seq-count c)) IEmptyableCollection (-empty [c] '()) ICollection (-conj [coll itm] (sequences::cons itm coll)) IStack (-peek [coll] (sequences::first coll)) (-pop [coll] (sequences::rest coll)) ISeqable (-seq [coll] (sequences::seq coll)) IHash (-hash [o] (sxhash o)) ;;poorly implemented... IEquiv (-equiv [o other] (error 'not-implemented)) IMapEntry (-key [coll] (sequences::first coll)) (-val [coll] (sequences::rest coll)) ISeq (-first [coll] (sequences::first coll)) (-rest [coll] (sequences::rest coll)) ) (extend-type clclojure.cowmap::cowmap ICounted (-count [c] (map-count c)) IEmptyableCollection (-empty [c] {}) ICollection (-conj [coll itm] (map-assoc coll (common-lisp:first itm) (second itm))) ISeqable (-seq [coll] (map-seq coll)) ILookup (-lookup [o k] (map-get o k)) (-lookup [o k not-found] (or (map-get o k) not-found)) IAssociative (-contains-key? [coll k] (map-contains? coll k)) (-entry-at [coll k] (map-entry-at coll k)) (-assoc [coll k v] (map-assoc coll k v)) IMap (-assoc-ex [coll k v] (error 'not-implemented)) ;;apparently vestigial (-dissoc [coll k] (map-dissoc coll k)) IHash (-hash [o] (error 'not-implemented)) IEquiv (-equiv [o other] (error 'not-implemented)) IKVReduce (-kv-reduce [coll f init] (error 'not-implemented))) (extend-type number IEquiv (-equiv [l r] (when (numberp r) (common-lisp:= l r))) IHash (-hash [n] (hash-code n))) (extend-type string INamed (-name [x] x)) ) ;; IChunk ;; (-drop-first [coll] (error 'not-implemented)) ;; IChunkedSeq ;; (-chunked-first [coll] (error 'not-implemented)) ;; (-chunked-rest [coll] (error 'not-implemented)) ;; IChunkedNext ;; (-chunked-next [coll] (error 'not-implemented)) ;;friendly map printing (defmethod print-object ((obj hash-table) stream) (common-utils::print-map obj stream)) ;;map printing compatibility (defmethod print-object ((obj clclojure.cowmap::cowmap) stream) (common-utils::print-map (cowmap-table obj) stream)) ;;Core Lib ;;======== (eval-when (:compile-toplevel :load-toplevel :execute) (defn seq [coll] (-seq coll)) (defn vec [coll] (if (vector? coll) coll (sequences:apply #'persistent-vector (seq coll)))) (defn vector [& xs] (sequences:apply #'persistent-vector (seq xs))) (defn hash-map [& xs] (sequences:apply #'persistent-map (seq xs)) ) (defn identical? [l r] (common-lisp:eq l r)) (defn nil? [x] (identical? x nil)) ;;need to implement arrayseq... ;;These are lame but easy, we really want to ;;get chunked-first and friends up and running. ;;Also want to bake in typecases for quick ;;dispatch... (defn first [coll] (-first (seq coll))) (defn rest [coll] (-rest (seq coll))) ;;TBD fix this for an actual -next implementation. ;; "Returns a seq of the items after the first. Calls seq on its ;; argument. If there are no more items, returns nil" ;;this isn't great.... (defn implements? [p obj] (satisfies? p obj)) ;;tbd : get metadata reader working... ;^seq (defn next [coll] (when-not (nil? coll) (if (implements? INext coll) (-next coll) (seq (rest coll))))) (defn nnext [coll] (next (next coll))) (defn second [coll] (first (rest coll))) (defn ffirst [coll] (first (first coll))) ;;Inaccurate... (defn fnext [coll] (first (rest coll))) (defn get ([m k] (-lookup m k)) ([m k not-found] (-lookup m k not-found))) (def odd? #'common-utils:odd?) (def even? #'common-utils:even?) (def zero? #'common-utils:zero?) (defn inc [x] (1+ x)) (defn dec [x] (1- x)) (defn = ([x] true) ([x y] (if (and (numberp x) (numberp y)) (common-lisp:= x y) (-equiv x y))) ([x y & more] (if (-equiv x y) (if (next more) (recur y (first more) (next more)) (- y (first more))) nil))) (defn key [e] (-key e)) (defn val [e] (-val e)) (defn name [x] (-name x)) ) (defmacro when-let (binding &rest body) (let [binding (seq binding) arg (-first binding) expr (-first (-rest binding)) tst (gensym "tst")] (clclojure.eval::recover-literals `(let ,(vector tst (second binding)) (when ,tst (let ,(vector arg tst) ,@body)))))) (defmacro if-let (binding body &rest false-body) (let [binding (seq binding) arg (-first binding) expr (-first (-rest binding)) tst (gensym "tst")] (clclojure.eval::recover-literals `(let ,(vector tst (second binding)) (if ,tst (let ,(vector arg tst) ,body) ,@false-body))))) (defn throw [e] (error e)) ;;try-catch-finally... (defn ex-info ([msg map] (make-instance 'exception-info :data map :cause msg :message msg)) ([msg map cause] (make-instance 'exception-info :data map :cause cause :message msg))) (defn ex-data [e] (common-utils::exception-info-data e)) (defn ex-cause [e] (common-utils::exception-info-cause e)) (defn ex-message [e] (common-utils::exception-info-message e)) ;;using cl macros for now to get behavior in place.. ;; "defs name to have the root value of the expr iff the named var has no root value, ;; else expr is unevaluated" ;; {:added "1.0"} ;;Slight deviation from clojure.core implementation, which uses def ;;internally...may revisit. (defmacro defonce (name expr) `(when-not (boundp (quote ,name)) (def ~name ~expr))) (defn assoc ([m k v] (-assoc m k v)) ([m k v & kvs] (reduce (fn [acc kv] (-assoc acc (first kv) (second kv))) (-assoc m k v) kvs))) (defn dissoc ([m k] (-dissoc m k)) ([m k & ks] (reduce (fn [acc k] (-dissoc acc k)) (-dissoc m k) ks))) (eval-when (:compile-toplevel :load-toplevel :execute) (defn count [coll] (-count coll))) (defn nth ([coll index] (-nth coll index)) ([coll index not-found] (-nth coll index not-found))) (defn take [n coll] (sequences:take n (seq coll))) (defn drop [n coll] (sequences:drop n (seq coll))) (defn conj ([] []) ([coll] coll) ([coll x] (-conj coll x)) ([coll x & xs] (if (seq xs) (recur (-conj coll x) (first xs) (rest xs)) (conj coll x)))) (eval-when (:compile-toplevel :load-toplevel :execute) (defn chunked-seq? [x] nil) (defn chunk-first [coll] (-chunked-first coll)) (defn chunk-rest [coll] (-chunked-rest coll)) (defn chunk-buffer [coll]) (defn seq->list [xs] (sequences::seq->list (seq xs))) (defn cons [x coll] (-conj coll x)) ;; "Takes a set of test/expr pairs. It evaluates each test one at a ;; time. If a test returns logical true, cond evaluates and returns ;; the value of the corresponding expr and doesn't evaluate any of the ;; other tests or exprs. (cond) returns nil." ;; {:added "1.0"} ;;need to implement throw for most of the stdlib. (defmacro cond (&rest clauses) (when (seq clauses) (list 'if (first clauses) (if (next clauses) (second clauses) (throw (ex-info "cond requires an even number of forms" {}))) (cons 'clclojure.base:cond (next (next clauses))))))) (defn chunk-cons [chunk rest] (error 'not-implemented)) (defn chunk-append [b x] (error 'not-implemented)) (defn empty [coll] (-empty coll)) ;; {:private true ;; :static true} (defn spread [arglist] (cond (nil? arglist) nil (nil? (next arglist)) (seq (first arglist)) :else (cons (first arglist) (spread (next arglist))))) ;; "Creates a new seq containing the items prepended to the rest, the ;; last of which will be treated as a sequence." ;; {:added "1.0" ;; :static true} (defn list* ([args] (seq args)) ([a args] (cons a args)) ([a b args] (cons a (cons b args))) ([a b c args] (cons a (cons b (cons c args)))) ([a b c d & more] (cons a (cons b (cons c (cons d (spread more))))))) (defmacro loop* (bindings &rest body) (assert (vector? bindings)) (assert (even? (count bindings))) `(with-recur ,(seq->list bindings) ,@body)) ;; "Evaluates the exprs in a lexical context in which the symbols in ;; the binding-forms are bound to their respective init-exprs or parts ;; therein. Acts as a recur target." ;; (defmacro loop ;; "Evaluates the exprs in a lexical context in which the symbols in ;; the binding-forms are bound to their respective init-exprs or parts ;; therein. Acts as a recur target." ;; {:added "1.0", :special-form true, :forms '[(loop [bindings*] exprs*)]} ;; [bindings & body] ;; (assert-args ;; (vector? bindings) "a vector for its binding" ;; (even? (count bindings)) "an even number of forms in binding vector") ;; (let [db (destructure bindings)] ;; (if (= db bindings) ;; `(loop* ~bindings ~@body) ;; (let [vs (take-nth 2 (drop 1 bindings)) ;; bs (take-nth 2 bindings) ;; gs (map (fn [b] (if (symbol? b) b (gensym))) bs) ;; bfs (reduce1 (fn [ret [b v g]] ;; (if (symbol? b) ;; (conj ret g v) ;; (conj ret g v b g))) ;; [] (map vector bs vs gs))] ;; `(let ~bfs ;; (loop* ~(vec (interleave gs gs)) ;; (let ~(vec (interleave bs gs)) ;; ~@body))))))) (defmacro loop (bindings &rest body) `(loop* ,bindings ,@body)) ;; "When lazy sequences are produced via functions that have side ;; effects, any effects other than those needed to produce the first ;; element in the seq do not occur until the seq is consumed. dorun can ;; be used to force any effects. Walks through the successive nexts of ;; the seq, does not retain the head and returns nil." ;; {:added "1.0" ;; :static true} ;;TCO version is tripping here... ;; (defn dorun ;; ([coll] ;; (when-let [s (seq coll)] ;; (recur (next s)))) ;; ([n coll] ;; (when (and (seq coll) (pos? n)) ;; (recur (dec n) (next coll))))) ;;temporary work around while I patch tail cail detection ;;so we stop getting false positives. (defn dorun ([coll] (let [s (seq coll)] (when s (recur (next s))))) ([n coll] (when (and (seq coll) (pos? n)) (recur (dec n) (next coll))))) ;; "When lazy sequences are produced via functions that have side ;; effects, any effects other than those needed to produce the first ;; element in the seq do not occur until the seq is consumed. doall can ;; be used to force any effects. Walks through the successive nexts of ;; the seq, retains the head and returns it, thus causing the entire ;; seq to reside in memory at one time." ;; {:added "1.0" ;; :static true} (defn doall ([coll] (dorun coll) coll) ([n coll] (dorun n coll) coll)) ;; "Returns the nth rest of coll, coll when n is 0." ;; {:added "1.3" ;; :static true} (defn nthrest [coll n] (loop [n n xs coll] (if-let [xs (and (pos? n) (seq xs))] (recur (dec n) (rest xs)) xs))) ;; "Returns a lazy sequence of lists of n items each, at offsets step ;; apart. If step is not supplied, defaults to n, i.e. the partitions ;; do not overlap. If a pad collection is supplied, use its elements as ;; necessary to complete last partition upto n items. In case there are ;; not enough padding elements, return a partition with less than n items." ;; {:added "1.0" ;; :static true} ;;TODO our implementation / behavior ;;of lazy seq is not identical to clojure's. ;;It's either an implementation problem or an eval problem ;;with out recursive functions. (defn partition ([n coll] (partition n n coll)) ([n step coll] (lazy-seq (when-let [s (seq coll)] (let [p (doall (take n s))] (when (= n (count p)) (cons p (partition n step (nthrest s step)))))))) ([n step pad coll] (lazy-seq (when-let [s (seq coll)] (let [p (doall (take n s))] (if (= n (count p)) (cons p (partition n step pad (nthrest s step))) (list (take n (concat p pad))))))))) ;; "Returns a lazy sequence of lists like partition, but may include ;; partitions with fewer than n items at the end. Returns a stateful ;; transducer when no collection is provided." ;; {:added "1.2" ;; :static true} ;; ([^long n] ;; (fn [rf] ;; (let [a (java.util.ArrayList. n)] ;; (fn ;; ([] (rf)) ;; ([result] ;; (let [result (if (.isEmpty a) ;; result ;; (let [v (vec (.toArray a))] ;; ;;clear first! ;; (.clear a) ;; (unreduced (rf result v))))] ;; (rf result))) ;; ([result input] ;; (.add a input) ;; (if (= n (.size a)) ;; (let [v (vec (.toArray a))] ;; (.clear a) ;; (rf result v)) ;; result)))))) ;;We need to inline or otherwise capture the ;;partition-all function symbol. Current named-fn* ;;isn't compatible with lazy seq ;; (defn partition-all ;; ([n coll] ;; (partition-all n n coll)) ;; ([n step coll] ;; (lazy-seq ;; (when-let [s (seq coll)] ;; (let [seg (doall (take n s))] ;; (cons seg (partition-all n step (nthrest s step)))))))) ;; An iteration state value. ;; A value describing the limit of iteration, if any. ;; The from-end value. ;; A step function of three arguments: the sequence, the state value, the from-end value. The function should return the new state value. ;; An end predicate of four arguments: the sequence, the state value, the limit value, the from-end value. The function should return a generalised boolean describing whether the iteration has reached the end of the sequence. ;; An element read function of two arguments: the sequence, the state value. ;; An element write function of three arguments: the new value to store, the sequence, the state value. ;; An index function of two arguments: the sequence, the state value. The function should return the current iteration index, starting from zero. ;; An iterator copy function of two arguments: the sequence, the state value. The function should return a "fresh" iteration value. (defn ->iterator [s] (multiple-value-bind (state from-end step end? read-elt write-elt index copy) (sb-sequence:make-sequence-iterator s) {:state state :from-end from-end :step step :end? end? :read-elt read-elt :write-elt write-elt :index index :copy copy})) ;;We're doing a lot of runtime checks that ;;may be suboptimal time-wise. Could cache ;;the implements? function, or move to protocol... (defn reduce ([f coll] (if (sequences:internal-reduce? coll) (sequences:reduce f coll) (sequences:reduce f (seq coll)))) ([f init coll] (if (sequences:init-reduce? coll) (sequences:reduce f init coll) (sequences:reduce f (seq coll))))) ;; "Returns a new coll consisting of to-coll with all of the items of ;; from-coll conjoined. A transducer may be supplied." ;; {:added "1.0" ;; :static true} (defn into ([] []) ([to] to) ([to from] (if nil ;(instance? clojure.lang.IEditableCollection to) (with-meta (persistent! (reduce conj! (transient to) from)) (meta to)) (reduce conj to from))) ;; ([to xform from] ;; (if nil ;(instance? clojure.lang.IEditableCollection to) ;; (with-meta (persistent! (transduce xform conj! (transient to) from)) (meta to)) ;; (transduce xform conj to from))) ) ;; "Returns a lazy sequence consisting of the result of applying f to ;; the set of first items of each coll, followed by applying f to the ;; set of second items in each coll, until any one of the colls is ;; exhausted. Any remaining items in other colls are ignored. Function ;; f should accept number-of-colls arguments. Returns a transducer when ;; no collection is provided." ;; {:added "1.0" ;; :static true} (defmacro lazy-seq (&rest body) `(sequences::lazy-seq ,@body)) (defn map ;;temporarily on hold while we fix tail recur detection. ;; ([f] ;; (fn [rf] ;; (fn ;; ([] (rf)) ;; ([result] (rf result)) ;; ([result input] ;; (rf result (f input))) ;; ([result input & inputs] ;; (rf result (apply f input inputs)))))) ([f coll] (sequences:map f (seq coll))) ([f c1 c2] (sequences:map f (seq c1) (seq c2))) ([f c1 c2 c3] (sequences:map f (seq c1) (seq c2) (seq c3))) ([f c1 c2 c3 & colls] (sequences:map f (seq c1) (seq c2) (seq c3) colls) )) ;;lame, but a little exercise in bindings... (defmacro dotimes (binding &rest body) `(common-lisp:dotimes (,(first binding) ,(second binding)) ,@body)) ;; "Returns a lazy sequence of the items in coll for which ;; (pred item) returns logical true. pred must be free of side-effects. ;; Returns a transducer when no collection is provided." ;; {:added "1.0" ;; :static true} ;;(defn filter ;; ([pred] ;; (fn [rf] ;; (fn ;; ([] (rf)) ;; ([result] (rf result)) ;; ([result input] ;; (if (pred input) ;; (rf result input) ;; result))))) ;; [pred coll] ;; (lazy-seq ;; (when-let [s (seq coll)] ;; (if (chunked-seq? s) ;; (let [c (chunk-first s) ;; size (count c) ;; b (chunk-buffer size)] ;; (dotimes [i size] ;; (let [v (nth c i)] ;; (when (pred v) ;; (chunk-append b v)))) ;; (chunk-cons (chunk b) (filter pred (chunk-rest s)))) ;; (let [f (first s) ;; r (rest s)] ;; (if (pred f) ;; (cons f (filter pred r)) ;; (filter pred r))))))) ;;lame filter for now. (defn filter [predicate coll] (lazy-seq (when-let [s (seq coll)] (let [f (first s) r (rest s)] (if (funcall predicate f) (cons f (filter predicate r)) (filter predicate r)))))) (defn concat ([] nil) ([x] x) ([x y] (sequences:concat (seq x) (seq y))) ([x y & zs] (sequences:apply #'sequences:concat (sequences:map #'seq (common-lisp:list* x y zs))))) (defn every? [pred xs] (sequences::every? pred xs)) (def identity #'common-lisp:identity) ;; "Returns a lazy seq of the first item in each coll, then the second etc." ;; {:added "1.0" ;; :static true} (defn interleave ([] ()) ([c1] (lazy-seq (seq c1))) ([c1 c2] (lazy-seq (let [s1 (seq c1) s2 (seq c2)] (when (and s1 s2) (cons (first s1) (cons (first s2) (interleave (rest s1) (rest s2)))))))) ([c1 c2 & colls] (let [ss (map seq (conj colls c2 c1))] (when (every? identity ss) (concat (map first ss) (lazy-seq (apply interleave (map rest ss)))))))) ;;need destructure... (def symbol? #'symbolp) (def keyword? #'keywordp) ;;for now, we don't have qualified keywords... ;;we "could" encode that information in the ;;keyword name somewhere (like a central db), ;;but it seems better to implement the actual ;;clojure qualified keywords... ;;wonder if we can inherit from symbol..(nope!). (defn namespace [s] (when (symbol? s) (when-let [p (symbol-package s)] (package-name p)) )) ;; (comment ;; (defmacro fn (& sigs) ;; (let* ((name (if (symbol? (first sigs)) (first sigs) nil) ;; sigs (if name (next sigs) sigs) ;; sigs (if (vector? (first sigs)) ;; (list sigs) ;; (if (seq? (first sigs)) ;; sigs ;; ;; Assume single arity syntax ;; (throw (IllegalArgumentException. ;; (if (seq sigs) ;; (str "Parameter declaration " ;; (first sigs) ;; " should be a vector") ;; (str "Parameter declaration missing")))))) ;; psig (fn* [sig] ;; ;; Ensure correct type before destructuring sig ;; (when (not (seq? sig)) ;; (throw (IllegalArgumentException. ;; (str "Invalid signature " sig ;; " should be a list")))) ;; (let [[params & body] sig ;; _ (when (not (vector? params)) ;; (throw (IllegalArgumentException. ;; (if (seq? (first sigs)) ;; (str "Parameter declaration " params ;; " should be a vector") ;; (str "Invalid signature " sig ;; " should be a list"))))) ;; conds (when (and (next body) (map? (first body))) ;; (first body)) ;; body (if conds (next body) body) ;; conds (or conds (meta params)) ;; pre (:pre conds) ;; post (:post conds) ;; body (if post ;; `((let [~'% ~(if (< 1 (count body)) ;; `(do ~@body) ;; (first body))] ;; ~@(map (fn* [c] `(assert ~c)) post) ;; ~'%)) ;; body) ;; body (if pre ;; (concat (map (fn* [c] `(assert ~c)) pre) ;; body) ;; body)] ;; (maybe-destructured params body))) ;; new-sigs (map psig sigs)] ;; (with-meta ;; (if name ;; (list* 'fn* name new-sigs) ;; (cons 'fn* new-sigs)) ;; (meta &form)))) ;; ) ;;conflicts with :common-lisp (defn rest-arg? [x] (seql x '&)) ;;need to implement "new" eventually ;;it's a low-level interop construct. (defmacro new (klass &rest args) `(make-instance (quote ~klass) ~@args)) (defn ds-pvec [bvec b val] (let [gvec (gensym "vec__") gseq (gensym "seq__") gfirst (gensym "first__") has-rest (some rest-arg? b)] (loop [ret (let [ret (conj bvec gvec val)] (if has-rest (conj ret gseq (list `seq gvec)) ret)) n 0 bs b seen-rest? false] (if (seq bs) (let [firstb (first bs)] (cond (= firstb '&) (recur (ds-pvec ret (second bs) gseq) n (nnext bs) true) (= firstb :as) (ds-pvec ret (second bs) gvec) :else (if seen-rest? (throw (ex-info "Unsupported binding form, only :as can follow & parameter" nil)) (recur (ds-pvec (if has-rest (conj ret gfirst `(first ~gseq) gseq `(next ~gseq)) ret) firstb (if has-rest gfirst (list `nth gvec n nil))) (inc n) (next bs) seen-rest?)))) ret)))) (defn ds-pmap [bvec b v] (let [gmap (gensym "map__") gmapseq (with-meta gmap {:tag 'clojure.lang.ISeq}) defaults (get b :or)] (loop [ret (-> bvec (conj gmap) (conj v) (conj gmap) (conj `(if (seq? ~gmap) (clojure.lang.PersistentHashMap/create (seq ~gmapseq)) ~gmap)) ((fn [ret] (if (get b :as) (conj ret (get b :as) gmap) ret)))) bes (let [transforms (reduce1 (fn [transforms mk] (if (keyword? mk) (let [mkns (namespace mk) mkn (name mk)] (cond (= mkn "keys") (assoc transforms mk #(keyword (or mkns (namespace %)) (name %))) (= mkn "syms") (assoc transforms mk #(list `quote (symbol (or mkns (namespace %)) (name %)))) (= mkn "strs") (assoc transforms mk str) :else transforms)) transforms)) {} (keys b))] (reduce (fn [bes entry] (reduce #(assoc %1 %2 ((val entry) %2)) (dissoc bes (key entry)) ((key entry) bes))) (dissoc b :as :or) transforms))] (if (seq bes) (let [bb (key (first bes)) bk (val (first bes)) local (if (instance? clojure.lang.Named bb) (with-meta (symbol nil (name bb)) (meta bb)) bb) bv (if (contains? defaults local) (list `get gmap bk (defaults local)) (list `get gmap bk))] (recur (if (ident? bb) (-> ret (conj local bv)) (pb ret bb bv)) (next bes))) ret)))) (comment (defn destructure [bindings] (let [bents (partition 2 bindings) pb (fn pb [bvec b v] (let [pvec (fn [bvec b val] (ds-pvec pvec b val)) pmap ] (cond (symbol? b) (-> bvec (conj b) (conj v)) (vector? b) (pvec bvec b v) (map? b) (pmap bvec b v) :else (throw (new Exception (str "Unsupported binding form: " b)))))) process-entry (fn [bvec b] (pb bvec (first b) (second b)))] (if (every? symbol? (map first bents)) bindings (reduce1 process-entry [] bents)))) )
56,765
Common Lisp
.lisp
1,383
33.946493
226
0.547741
joinr/clclojure
224
8
4
EPL-1.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
cd6f7c74a90697c281c0d956ee7e5790e08106542cfa99533785f7947b44ae81
389
[ -1 ]
390
literals.lisp
joinr_clclojure/literals.lisp
(defpackage clclojure.literals (:use :common-lisp :clclojure.eval :clclojure.pvector :clclojure.cowmap)) (in-package :clclojure.literals) ;;Data Literal Eval Semantics (EVAL-WHEN (:compile-toplevel :load-toplevel :execute) (clclojure.eval:enable-custom-eval) ;;(eval [x y z]) => (vector (eval x) (eval y) (eval z)) ;;this is somewhat inefficient since we're not exploiting ;;chunks, but good enough for proof of concept. We do ;;have chunks, fyi. (defmethod clclojure.eval::literal? ((obj pvec)) t) (defmethod custom-eval ((obj pvec) &optional env) (vector-map (lambda (x) (clclojure.eval:custom-eval-in-lexenv x env)) obj)) (defmethod let-expr ((obj pvec)) ;; `(clclojure.eval:literal ;; (clclojure.pvector:persistent-vector ,@(clclojure.pvector:vector-to-list obj))) (list 'clclojure.reader::literal (list* 'clclojure.reader::data-literal (list 'function 'persistent-vector) `((list ,@(vector-to-list obj))))) ) ;; (defmethod let-expr ((obj pvec)) ;; obj) (defmethod clclojure.eval::literal? ((obj subvector)) t) (defmethod custom-eval ((obj subvector) &optional env) (vector-map (lambda (x) (clclojure.eval:custom-eval-in-lexenv x env)) obj)) (defmethod let-expr ((obj subvector)) ;; `(clclojure.eval:literal ;; (clclojure.pvector:persistent-vector ,@(clclojure.pvector:vector-to-list obj))) (list 'clclojure.reader::literal (list* 'clclojure.reader::data-literal (list 'function 'persistent-vector) `((list ,@(vector-to-list obj))))) ) (defmethod clclojure.eval::literal? ((obj cowmap)) t) ;;(map {x y j k} => (persistent-map ;;(clclojure.eval:custom-eval-in-lexenv x) ;;(clclojure.eval:custom-eval-in-lexenv y) ;;(clclojure.eval:custom-eval-in-lexenv j) ;;(clclojure.eval:custom-eval-in-lexenv k)) (defmethod custom-eval ((obj cowmap) &optional env) (reduce (lambda (acc kv) (destructuring-bind (k v) kv (map-assoc acc (clclojure.eval:custom-eval-in-lexenv k env) (clclojure.eval:custom-eval-in-lexenv v env)))) (map-seq obj) :initial-value (empty-map))) (defmethod let-expr ((obj cowmap)) ;; `(clclojure.eval:literal ;; (clclojure.cowmap:persistent-map ;; ,@(reduce (lambda (acc kv) ;; (cons (first kv) (cons (second kv) acc))) ;; (clclojure.cowmap:map-seq obj) :initial-value '()))) (list 'clclojure.reader::literal (list* 'clclojure.reader::data-literal (list 'function 'persistent-map) `((list ,@(reduce (lambda (acc kv) (cons (first kv) (cons (second kv) acc))) (clclojure.cowmap:map-seq obj) :initial-value '())))))) )
2,912
Common Lisp
.lisp
62
39.080645
90
0.613701
joinr/clclojure
224
8
4
EPL-1.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
0dcc708ccd11ce141f4e0d76d7063a655a4e7abd1193400c48f1bc8a7d567fda
390
[ -1 ]
391
cowmap.lisp
joinr_clclojure/cowmap.lisp
;;A lame copy-on-write implementation of persistent maps ;;useful for bootstrapping. ;;Notably, none of the operations on these guys are ;;lazy. Uses copies for otherwise destructive operations. ;;Wraps a mutable hashtable. (defpackage :clclojure.cowmap (:use :common-lisp) (:export :persistent-map :empty-map? :map-count :map-assoc :map-dissoc :map-entry-at :map-contains? :map-seq :empty-map :map-get :cowmap-table :cowmap) (:shadow :assoc :find)) (in-package clclojure.cowmap) (EVAL-WHEN (:compile-toplevel :load-toplevel :execute) (defstruct cowmap (table (make-hash-table))) ;;From stack overflow. It looks like the compiler needs a hint if we're ;;defining struct/class literals and using them as constants. (defmethod make-load-form ((m cowmap) &optional env) (declare (ignore env)) (make-load-form-saving-slots m))) (defun ->cowmap () "Simple persistent vector builder. Used to derive from other pvectors to share structure where possible." (make-cowmap)) (common-utils::defconstant! +empty-cowmap+ (make-cowmap)) (defun empty-map () +empty-cowmap+) (defun empty-map? (m) (eq m +empty-cowmap+)) (defun map-count (m) (hash-table-count (cowmap-table m))) (defun insert-keys! (tbl xs) (assert (evenp (length xs))) (loop for (k v) in (common-utils::partition! 2 xs) do (setf (gethash k tbl) v)) tbl) (defun persistent-map (&rest xs) "Funcallable constructor for building vectors from arglists. Used for read-macro dispatch as well." (if (null xs) +empty-cowmap+ (progn (assert (evenp (length xs))) (let* ((cm (->cowmap)) (tbl (cowmap-table cm))) (insert-keys! tbl xs) cm)))) (defun map-contains? (m k) (multiple-value-bind (v present) (gethash k (cowmap-table m)) (declare (ignore v)) present)) (defun map-get (m k &optional default) (gethash k (cowmap-table m) default)) (defun map-entry-at (m k) (multiple-value-bind (v present) (map-get m k) (when present (list k v)))) (defun map-assoc (m k v) (let ((tbl (common-utils::copy-hash-table (cowmap-table m)))) (setf (gethash k tbl) v) (make-cowmap :table tbl))) (defun map-dissoc (m k) (if (map-contains? m k) (let ((tbl (common-utils::copy-hash-table (cowmap-table m)))) (remhash k tbl) (make-cowmap :table tbl)) m)) (defun map-seq (m) (common-utils::hash-table->entries (cowmap-table m))) (defmethod print-object ((obj cowmap) stream) (common-utils::print-map (cowmap-table obj) stream))
2,656
Common Lisp
.lisp
77
29.558442
73
0.655603
joinr/clclojure
224
8
4
EPL-1.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
a8814a7ba82bda8d3f3f15f498c7db863da358652d58e8434aa5dc921f013456
391
[ -1 ]
392
eval.lisp
joinr_clclojure/eval.lisp
(defpackage :clclojure.eval (:use :common-lisp :cl-package-locks :common-utils :clclojure.walk ) (:import-from :clclojure.reader :quoted-data-literal) (:export :custom-eval :custom-eval-in-lexenv :let-expr :let-expr? :noisy-expand :custom-eval-bindings :custom-eval? :enable-custom-eval :disable-custom-eval :literal :symbolic :simple-eval-in-lexenv :defmacro/literal-walker)) (in-package clclojure.eval) (defgeneric literal? (obj)) (defmethod literal? (obj) nil) (defgeneric let-expr (obj)) (defmethod let-expr (obj) obj) (defgeneric custom-eval (obj &optional env)) ;;We perform the same thing existing eval does for unknown ;;datums. Just return the data as-is. This is effectively ;;what sbcl does by default. (defmethod custom-eval (obj &optional env) (declare (ignore env)) obj) ;;we need to define a special xform that allows us to handle forms ;;that have been translated to their sexpr friendly forms. If we have ;;a (let-expr '[x]) then we should get (literal (persistent-vector ;;'x)). If we want to de-literal, then we need the inverse, (symbolic ;;(literal (persistent-vector 'x))) => '[x] ;;this is just identity, but we use it to codify our literals. (defun literal (obj) obj) ;;symbolic identifies data literals encoded ;;in (literal ...) forms, and helpfully unpacks them ;;into their actual literal representation. vectors ;;return to vectors, maps to maps, sets to sets, etc. (defun symbolic (obj) (if (and (listp obj) (eql (first obj) 'literal)) (let ((stored (second obj))) (eval `(,(first stored) ,@(mapcar (lambda (x) `(quote ,x)) (rest stored))))) obj)) ;;helper function to allow us to replace ;;(literal ) forms with symbolic ones. ;;fn :: subform -> context -> env -> subform (defun literal-walker (subform context env) (declare (ignore context env)) (pprint (list :walking subform)) (typecase subform (cons (cond ((listp (first subform)) (if (seql (first (first subform)) 'literal) (progn (pprint :literal-list) (cons (symbolic (first subform)) (rest subform))) subform)) ((seql (first subform) 'literal) (progn (pprint :literal) (symbolic subform))) ((literal? (first subform)) (progn (pprint :literal?) (values subform t))) (t subform))) (t (progn (pprint :blah) subform)))) (defun clj-literal-walker (subform) ;(pprint (list :walking subform)) (typecase subform (cons (cond ((listp (first subform)) (if (seql (first (first subform)) 'literal) (progn ;(pprint :literal-list) (cons (clclojure.eval::symbolic (first subform)) (rest subform))) subform)) ((seql (first subform) 'literal) (let ((litexpr (cadr subform))) (progn ;(pprint :literal) (eval (cons 'clclojure.reader::quoted-data-literal (rest litexpr)))))) ((clclojure.eval::literal? (first subform)) (progn ;(pprint :literal?) (values subform t))) (t subform))) (t subform))) (defparameter *noisy-recovery* nil) ;;helper function that walks a form and recovers ;;symbolic data literals. (defun recover-literals (form) ;(sb-walker:walk-form form nil #'literal-walker) (when *noisy-recovery* (pprint (list :recovering form))) (let ((res (postwalk-replace #'clj-literal-walker form))) (when *noisy-recovery* (pprint (list :recovered res))) res)) ;;we can alternately use macrolet... (defun normal-arg? (arg) (if (symbolp arg) (not (eq (elt (symbol-name arg) 0) #\&)) t)) ;;macro-defining-macro that does a precompile ;;step to walk the args and bind them to their ;;recovered forms. (defmacro defmacro/literal-walker (name args &body body) `(defmacro ,name ,args (let (,@(mapcar (lambda (arg) `(,arg (recover-literals ,arg))) (common-lisp:remove-if-not #'normal-arg? args))) ,@body) )) ;;another option is to use find-method... ;;(find-method #'custom-eval '() '(t) nil) (defvar +original-eval+ (symbol-function 'SB-IMPL::simple-eval-in-lexenv)) (defun custom-eval? (obj) (find-method #'custom-eval '() `(,(class-of obj)) nil)) (defun let-expr? (obj) (find-method #'let-expr '() `(,(class-of obj)) nil)) (defun macro? (x) (macro-function x)) (defparameter *noisy-custom* nil) (defparameter *noisy-depth* 0) (defun noisy-log (msg) (when *noisy-custom* (pprint (list :noisy-log msg)))) (defmacro noisy-expand (expr) (let ((*noisy-custom* t)) (pprint (custom-eval-bindings expr nil)))) (defmacro bump-depth (&rest body) `(let ((,'clclojure.eval::*noisy-depth* (1+ ,'clclojure.eval::*noisy-depth*))) ,@body)) ;;TIL '#:blah => uninterned symbol (defun symbol-key (s) (cond ((and (symbolp s) (symbol-package s) (string= (string-upcase (package-name (symbol-package s))) "CLCLOJURE.BASE") (string= (string-upcase (symbol-name s)) "LET")) :clj-let) ;((macro? s) :macro) ;;not in use. (t s))) ;;we need to make sure this is recursive, so that the body is walked, ;;as are the arg bindings. (defun custom-eval-bindings (expr lexenv) (when (> *noisy-depth* 50) (error "Possibly infinite recursion: ~S " expr)) (when *noisy-custom* (pprint `(:evaluating ,expr))) (if (listp expr) (case (symbol-key (first expr)) (:clj-let (let ((nexpr (macroexpand expr))) (noisy-log :clj-let) (bump-depth (custom-eval-bindings nexpr lexenv)))) ((let let*) (destructuring-bind (name args &rest body) expr ;;this is wrong for labels and flet (let* ((new-args (mapcar (lambda (kv) (let ((lhs (first kv)) (rhs (second kv))) (if (let-expr? rhs) `(,lhs ,(clclojure.eval:let-expr rhs)) `(,lhs ,(bump-depth (custom-eval-bindings (macroexpand rhs) lexenv) ))))) args)) (new-body (mapcar (lambda (v) (cond ((let-expr? v) (clclojure.eval:let-expr v)) ((listp v) (bump-depth (custom-eval-bindings v lexenv))) (t v))) body))) (noisy-log :let-let*-labels-flet-macrolet) `(,name ,new-args ,@new-body)))) ((labels flet macrolet) (destructuring-bind (name args &rest body) expr ;;this is wrong for labels and flet (let* ((new-args (mapcar (lambda (binding) (destructuring-bind (name args &rest body) binding `(,name ,args ,@(custom-eval-bindings body lexenv)))) args)) (new-body (mapcar (lambda (v) (cond ((let-expr? v) (clclojure.eval:let-expr v)) ((listp v) (bump-depth (custom-eval-bindings v lexenv))) (t v))) body))) (noisy-log :labels-flet-macrolet) `(,name ,new-args ,@new-body)))) (otherwise (if (listp (cdr expr)) (progn (noisy-log :list-expr) (mapcar (lambda (v) (cond ((let-expr? v) (clclojure.eval:let-expr v)) ((listp v) (bump-depth (custom-eval-bindings v lexenv))) (t v))) expr)) (destructuring-bind (l . r) expr (progn (noisy-log :cons-expr) (cons (cond ((let-expr? l) (clclojure.eval:let-expr l)) ((listp l) (bump-depth (custom-eval-bindings l lexenv))) (t l)) (cond ((let-expr? r) (clclojure.eval:let-expr r)) ((listp r) (bump-depth (custom-eval-bindings r lexenv))) (t r)) )))))) (if (let-expr? expr) (progn (noisy-log :custom-let-expr) (let-expr expr)) (progn (noisy-log :pass-through-expr) expr)))) ;;we have a minor problem with let/let* in that they don't ;;participate in the custom-eval hack for data literals. ;;Ergo, if we have a vector literal, like [x], we get ;;the legacy eval semantics that just passes the the thing through ;;unevaluated. ;;Tracing out the calls in sbcl/src/code/eval.lisp ;; (sb-impl::%simple-eval ;; '(let* ((x 2) ;; (y [x])) y) ;; (sb-impl::make-null-lexenv)) ;; yields: ;; [x] ;;So we either need to walk the code at macro expansion ;;time and unpack all the literals... ;;Or (better), hook into simple-eval ;;and allow custom eval semantics, ;;or (maybe better), hook into ;;sb-impl:%simple-eval and ;;enable custom evaluation semantics... ;;We "could" code walk this stuff ;;in our clclojure let macro too, ;;and make sure our literals expand ;;to function calls... ;;The simplest solution is just to inject #'custom-eval ;;calls into the pipeline so that %simple-eval ;;picks it up when it goes to build the expression ;;sb-impl:%simple-eval coerces the expression into ;;a lambda prior to sending it off for compilation. ;;We can leverage this to walk the bindings for ;;let, let* and inject rhs bindings that ;;have custom-eval applied if they are ;;custom-eval? ;;This should cover like 90% of our cases ;;without interfering with legacy ;;common lisp stuff. ;;This is identical to the default sbcl eval.. ;;with the exception of the hook to our custom method. (unlock-package :sb-impl) (in-package :sb-impl) (defun custom-eval-in-lexenv (original-exp lexenv) (declare (optimize (safety 1))) ;; (aver (lexenv-simple-p lexenv)) (incf *eval-calls*) (sb-c:with-compiler-error-resignalling (let ((exp (macroexpand original-exp lexenv))) (handler-bind ((eval-error (lambda (condition) (error 'interpreted-program-error :condition (encapsulated-condition condition) :form exp)))) (typecase exp (symbol (ecase (info :variable :kind exp) ((:special :global :constant :unknown) (symbol-value exp)) ;; FIXME: This special case here is a symptom of non-ANSI ;; weirdness in SBCL's ALIEN implementation, which could ;; cause problems for e.g. code walkers. It'd probably be ;; good to ANSIfy it by making alien variable accessors ;; into ordinary forms, e.g. (SB-UNIX:ENV) and (SETF ;; SB-UNIX:ENV), instead of magical symbols, e.g. plain ;; SB-UNIX:ENV. Then if the old magical-symbol syntax is to ;; be retained for compatibility, it can be implemented ;; with DEFINE-SYMBOL-MACRO, keeping the code walkers ;; happy. (:alien (sb-alien-internals:alien-value exp)))) (list (let ((name (first exp)) (n-args (1- (length exp)))) (case name ((function) (unless (= n-args 1) (error "wrong number of args to FUNCTION:~% ~S" exp)) (let ((name (second exp))) (if (and (legal-fun-name-p name) (not (consp (let ((sb-c:*lexenv* lexenv)) (sb-c:lexenv-find name funs))))) (%coerce-name-to-fun name) ;; FIXME: This is a bit wasteful: it would be nice to call ;; COMPILE-IN-LEXENV with the lambda-form directly, but ;; getting consistent source context and muffling compiler notes ;; is easier this way. (%simple-eval original-exp lexenv)))) ((quote) (unless (= n-args 1) (error "wrong number of args to QUOTE:~% ~S" exp)) (second exp)) (setq (unless (evenp n-args) (error "odd number of args to SETQ:~% ~S" exp)) (unless (zerop n-args) (do ((name (cdr exp) (cddr name))) ((null name) (do ((args (cdr exp) (cddr args))) ((null (cddr args)) ;; We duplicate the call to SET so that the ;; correct value gets returned. (set (first args) (simple-eval-in-lexenv (second args) lexenv))) (set (first args) (simple-eval-in-lexenv (second args) lexenv)))) (let ((symbol (first name))) (case (info :variable :kind symbol) (:special) (t (return (%simple-eval original-exp lexenv)))) (unless (type= (info :variable :type symbol) *universal-type*) ;; let the compiler deal with type checking (return (%simple-eval original-exp lexenv))))))) ((progn) (simple-eval-progn-body (rest exp) lexenv)) ((eval-when) ;; FIXME: DESTRUCTURING-BIND returns ARG-COUNT-ERROR ;; instead of PROGRAM-ERROR when there's something wrong ;; with the syntax here (e.g. missing SITUATIONS). This ;; could be fixed by hand-crafting clauses to catch and ;; report each possibility, but it would probably be ;; cleaner to write a new macro ;; DESTRUCTURING-BIND-PROGRAM-SYNTAX which does ;; DESTRUCTURING-BIND and promotes any mismatch to ;; PROGRAM-ERROR, then to use it here and in (probably ;; dozens of) other places where the same problem ;; arises. (destructuring-bind (eval-when situations &rest body) exp (declare (ignore eval-when)) (multiple-value-bind (ct lt e) (sb-c:parse-eval-when-situations situations) ;; CLHS 3.8 - Special Operator EVAL-WHEN: The use of ;; the situation :EXECUTE (or EVAL) controls whether ;; evaluation occurs for other EVAL-WHEN forms; that ;; is, those that are not top level forms, or those ;; in code processed by EVAL or COMPILE. If the ;; :EXECUTE situation is specified in such a form, ;; then the body forms are processed as an implicit ;; PROGN; otherwise, the EVAL-WHEN form returns NIL. (declare (ignore ct lt)) (when e (simple-eval-progn-body body lexenv))))) ((locally) (simple-eval-locally (rest exp) lexenv)) ((macrolet) (destructuring-bind (definitions &rest body) (rest exp) (let ((sb-c:*lexenv* lexenv)) (sb-c::funcall-in-macrolet-lexenv definitions (lambda (&optional funs) (simple-eval-locally body sb-c:*lexenv* :funs funs)) :eval)))) ((symbol-macrolet) (destructuring-bind (definitions &rest body) (rest exp) (let ((sb-c:*lexenv* lexenv)) (sb-c::funcall-in-symbol-macrolet-lexenv definitions (lambda (&optional vars) (simple-eval-locally body sb-c:*lexenv* :vars vars)) :eval)))) ((if) (destructuring-bind (test then &optional else) (rest exp) (eval-in-lexenv (if (eval-in-lexenv test lexenv) then else) lexenv))) ((let let*) ;;minor hack to enable custom eval semantics ;;We pre-process the expression to ensure that ;;calls to custom-eval are inserted for types with custom-eval... ;(%simple-eval exp lexenv) (%simple-eval (clclojure.eval:custom-eval-bindings exp lexenv) lexenv) ) (t (if (and (symbolp name) (eq (info :function :kind name) :function)) (collect ((args)) (dolist (arg (rest exp)) (args (eval-in-lexenv arg lexenv))) (apply (symbol-function name) (args))) (%simple-eval exp lexenv)))))) (t ;;Unlike the default SBCL eval, we inject our custom-eval here. ;;This allows types to define custom evaluation semantics, e.g. ;;for data literals, otherwise, it behaves exactly like original ;;eval and returns the type. (clclojure.eval:custom-eval exp lexenv))))))) ; something dangerous (in-package :clclojure.eval) (lock-package :sb-impl) (defun enable-custom-eval () (with-packages-unlocked (:sb-impl :sb-int) (setf (symbol-function 'SB-IMPL::simple-eval-in-lexenv) (symbol-function 'SB-IMPL::custom-eval-in-lexenv))) ; something dangerous ) (defun disable-custom-eval () (with-packages-unlocked (:sb-impl :sb-int) (setf (symbol-function 'SB-IMPL::simple-eval-in-lexenv) +original-eval+) ; something dangerous t)) (defun custom-eval-in-lexenv (original-expr lexenv) (sb-impl::custom-eval-in-lexenv original-expr lexenv))
19,410
Common Lisp
.lisp
409
32.735941
123
0.514135
joinr/clclojure
224
8
4
EPL-1.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
9edee9966815edbe06325fb970f8002ae59bc00a56f1c6003524f3d41d66fad4
392
[ -1 ]
393
symbols.lisp
joinr_clclojure/symbols.lisp
;;beginnings of custom symbol tables... ;;symbols have different behavior in ;;CL and CLJ. We need to (defpackage :clclojure.symbols (:use :common-lisp :clclojure.base) (:shadowing-import-from :clclojure.base :deftype :let)) (in-package :clclojure.symbols) (defstruct cljsymbol namespace name) (defun ->symbol (name &optional namespace) (make-cljsymbol :namespace namespace :name name)) ;;where do symbols live in cljs? ;;I think there's a local var that defines namespaces and symbols. ;;In clj jvm, there's a map... ;;good reference here: ;;http://blogish.nomistech.com/clojure/clojure-symbols-vs-lisp-symbols/ ;;this leads, naturally, to vars as well.. ;;namespaces are just mappings of symbols to vars.
727
Common Lisp
.lisp
18
38.388889
71
0.762108
joinr/clclojure
224
8
4
EPL-1.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
58496c9d420bb98184ba47ef0d539abcb1a21ee3042cee78b29ffb58cd04a875
393
[ -1 ]
394
lexical.lisp
joinr_clclojure/lexical.lisp
;;Defining lexically scoped, unified variables and ;;functions with keyword access. (defpackage :clclojure.lexical (:use :common-lisp :clclojure.keywordfunc :common-utils) (:export :unified-let*)) (in-package :clclojure.lexical) ;;if the arg can be construed as a function, ;;the lexical symbol should be unified.. ;; (defmacro unify-binding (var) ;; `(cond ((functionp ,var) ;; (setf (symbol-function (quote ,var)) ;; ,var)) ;; ((keywordp ,var) ;; (if (not (keyfn? ,var)) ;; (progn (pprint (format nil "adding keyword access for: ~a " k )) ;; (eval (key-accessor ,var))))))) ;;we need to use let and flet instead of this... ;; (defmacro unify-binding (var) ;; `(cond ((functionp ,var) ;; (setf (symbol-function (quote ,var)) ;; ,var)) ;; ((keywordp ,var) ;; (if (not (keyfn? ,var)) ;; (progn (pprint (format nil "adding keyword access for: ~a " ,var )) ;; ;;(eval (key-accessor ,var)) ;; (setf (symbol-function (quote ,var)) ;; (->keyaccess ,var)) ;; ))))) ;;a couple of notes on evaluation and symbol/function namespaces, ;;including lexical scope.... ;;we have a few cases to cover... ;;if we want to cover every possible case and get a lisp1, ;;in the lexical case, we are relegated to using a combination ;;of let and flet on all the symbols ;; (let* ((g (->keyaccess :a)) ;; (lookup (->keyaccess :b))) ;; (labels ((g (arg) (funcall (keyaccess-func g) arg)) ;; (lookup (arg) (funcall (keyaccess-func lookup) arg))) ;; ;;(mapcar f (list keyfns keyfns)) ;; (pprint (list :obj lookup :fn (g keyfns))))) ;;this is an example of how we can play with lexical binds... ;;In the extreme case, we may not know what any types are, ;;which means they're functions or objects.... ;; (defun some-fn (z) ;; (let* ((g (lambda (x) (+ x 5))) ;;an actual function object... ;; (lookup (->keyaccess :b)) ;; (z (if (keywordp z) ;; (->keyaccess z) ;; z))) ;;keyword access function object... ;; (labels (;;general implementation of fn ;; (g (&rest args) (apply g args)) ;; ;;specific implementation for kw lookup.. ;; (lookup (arg) (funcall (keyaccess-func lookup) arg)) ;; (z (&rest args) (apply z args)) ;; ) ;; (pprint (list :obj g :fn (g 2) :keyaccess lookup ;; :z z :z-lookup (z keyfns) ;; (mapcar (lambda (x) (list :type x (type-of x))) ;; (list g lookup z))))))) ;;the only things that we know... are keywords, or fn forms bindings ;;are already in pairs... ;;Scrape the bindings to let*, and if we find keywords, ;;create an alist that associates the keyword to an ;;expression that defines a labels lexical function ;;for the keyword accessor. We compute/construct ;;a keyaccessor at compile time, and though it's ;;funcallable, we lookup its associated function ;;for use (and efficiency). We then provide ;;a simple function wrapper that invokes the keyword ;;fn (bear in mind, this is setfable). (EVAL-WHEN (:compile-toplevel :load-toplevel :execute) (defun keyword-accessors (bindings) (let ((arg (gensym "lookup")) (xs (common-utils:filter (lambda (lr) (keywordp (second lr))) bindings))) (when-not (null xs) (mapcar (lambda (lr) (pprint lr) (destructuring-bind (l r) lr (let ((f (keyaccess-func (->keyaccess r)))) (list r `(,l (,arg) (funcall (->keyaccess ,r) ,arg)))))) xs)))) ;;we use a generic apply here... collect all the args into a list and ;;apply. In clojure, there's some cost to that. Dunno what the ;;overhead is in CL. Also, if we "know" anything about the function, ;;we may be able to do some analysis and compile a more efficient ;;binding form (i.e. known number of args in the lambda. or simple ;;funcall... ;;There's some question about how much we know about the parameters at ;;runtime (specifically for let bindings). For certain classes of ;;lexical environments, we may be a-okay doing significant analysis of ;;what's involved in the let (case in point: if it's a lambda or a ;;known function we have meta on, we can derive types / args). Thats ;;a future optimization... ;;Note: if we don't refer to the lexical vars (NOT fns) for the ;;keywords, we end up with a slew of style warnings, since they don't ;;appear to be used (they are used for the lexical keyaccessors ;;though). To prevent this, we define a dummy function (never ;;invoked) that builds a list composed from the symbol-values. For ;;now, it's convenient. I may revisit this to see if we can detect if ;;the symbols aren't validly used... ;;we get compiler complaints with this if we don't... (defun functionize-bindings (bindings) (let* ((kwalist (keyword-accessors bindings)) (vars (mapcar (lambda (lr) (first (second lr))) kwalist)) (dummy (gensym "dummyfn"))) (cons `(,dummy () (list :this-prevents-warnings-nothing-else ,@vars)) (mapcar (lambda (lr) (destructuring-bind (l r) lr (if (keywordp r) (second (assoc r kwalist)) `(,l (,'&rest ,'args) (apply ,l ,'args))))) bindings))))) ;;so at the lexical level, we need to analyze the bindings. ;;determine if an item is a function (or an applicable object like ;;a keyword), and create matching labels for them... ;;this acts like let*, except it allows bindings that may be functions ;;or things that can act like functions -> keywords. Everything else ;;should be covered by a funcallable object... We unify the ;;symbol-value and symbol-function namespaces in the lexical context, ;;detecting the need to generate keyword accessors. (defmacro unified-let* (bindings &rest body) `(let* (,@bindings) (labels (,@ (functionize-bindings bindings) ) ,@body))) ;;a simple test function to tie everything together. (defun test-my-scope () (unified-let* ((hello :hello) ;;we create (or lookup cached) keyaccess funcallable objects (world :world) ;;when we have literal keywords bound to symbols. (k 2) (inc (lambda (x) (+ x 1))) (add (lambda (x y) (+ x y))) (tbl (unified-let* ((tbl (make-hash-table))) (setf (gethash :hello tbl) "World") (setf (gethash :world tbl) "Hello") (setf (gethash :k tbl) k) tbl))) (list (hello tbl) (world tbl) (add (inc 39) k) ;;(:k tbl) ;;doesn't work without some extra macro magic... (funcall (->keyaccess :k) tbl) ;;it will look like this behind the scenes. ))) ;;LEXICAL> (test-my-scope) ;;("World" "Hello" 42 2) ;;works!
7,522
Common Lisp
.lisp
147
44.428571
96
0.571759
joinr/clclojure
224
8
4
EPL-1.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
1b6f7727c7454fe6c502ef4856a7ebd40b208cb443b71d7c3252000dfbf6d051
394
[ -1 ]
395
walk.lisp
joinr_clclojure/walk.lisp
;;a simple code walking package based off clojure.walk, with ;;severe limitations. (defpackage :clclojure.walk (:use :common-lisp :common-utils) (:export :walk :prewalk :postwalk :prewalk-replace :postwalk-replace) ;:loop :defmacro ) (in-package :clclojure.walk) ;; "Traverses form, an arbitrary data structure. inner and outer are ;; functions. Applies inner to each element of form, building up a ;; data structure of the same type, then applies outer to the result. ;; Recognizes all Clojure data structures. Consumes seqs as with doall." ;; {:added "1.1"} (defun walk (inner outer form) (cond ((listp form) (funcall outer (apply #'list (mapcar (lambda (x) (funcall inner x)) form)))) (t (funcall outer form)))) ;; "Like postwalk, but does pre-order traversal." ;; {:added "1.1"} (defun prewalk (f form) (walk (lambda (x) (prewalk f x)) #'identity (funcall f form))) (defun postwalk (f form) (walk (lambda (x) (postwalk f x)) f form)) ;; "Recursively transforms form by replacing keys in smap with their ;; values. Like clojure/replace but works on any data structure. Does ;; replacement at the root of the tree first." ;; {:added "1.1"} (defun prewalk-replace (f form) (prewalk (lambda (x) (let ((res (funcall f x))) (if res res x))) form)) (defun postwalk-replace (f form) (postwalk (lambda (x) (let ((res (funcall f x))) (if res res x))) form))
1,482
Common Lisp
.lisp
34
39.264706
88
0.661346
joinr/clclojure
224
8
4
EPL-1.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
0d27ef2274eb6f3ac5d60f57517bca4896f58d78bc7b991907bddb9d0f31e2ba
395
[ -1 ]
396
reader.lisp
joinr_clclojure/reader.lisp
;;A package for defining read table extensions ;;for clojure data structures. ;;Pending.................. (defpackage :clclojure.reader (:shadowing-import-from :sequences :first :second :cons :apply :map :filter :rest :reduce :flatten) (:use :common-lisp :common-utils :named-readtables :clclojure.pvector :clclojure.cowmap :sequences) (:export :*literals* :*reader-context* :quoted-children :quote-sym :literal?)) (in-package :clclojure.reader) (EVAL-WHEN (:compile-toplevel :load-toplevel :execute) ;;Problem right now is that, when we read using delimited-list, ;;we end up losing out on the reader literal for pvecs and the like... ;;When we have quoted ;;we can use a completely custom reader...perhaps that's easiet.. ;;Have to make this available to the compiler at compile time! ;;Maybe move this into a clojure-readers.lisp or something. ;;alist of literals... (defparameter *literals* '(list) ; '(list cons) ) (defparameter *reader-context* :read) ;;default quote...o ;; (comment ;; (set-macro-character #\' ;; #'(lambda (stream char) ;; (declare (ignore char)) ;; `(quote ,(read stream t nil t))))) (defun quote-sym (sym) (list 'quote sym)) ;`(quote ,sym) ;; (defmacro quoted-children (c) ;; `(,(first c) ,@(mapcar #'quote-sym (rest c)))) (defun dotted-pair? (xs) (and (listp xs) (not (listp (cdr xs))))) (defun literal? (s) (or (and (listp s) (find (first s) *literals*)) (and (symbolp s) (find s *literals*)))) (defun literal (obj) obj) (defmacro quoted-children (c) (if (symbolp c) `(quote ,c) `(,(first c) ,@ (sequences::seq->list (map (lambda (s) (cond ((literal? s) ;;we need to recursively call quoted-children.. `(quoted-children ,s)) ((dotted-pair? s) `(quote ,s)) ((listp s) `(quoted-children ,(cons (quote list) s))) (t (funcall #'quote-sym s)))) (rest c)))))) ;;Enforces quoting semantics for literal data structures.. ;;We may not need this anymore since we hacked eval. (defmacro clj-quote (expr) (cond ((literal? expr) `(quoted-children ,expr)) ((dotted-pair? expr) `(quote ,expr)) ((listp expr) `(quoted-children ,(cons (quote list) expr))) (t (quote-sym expr)))) (defun as-char (x) (cond ((characterp x) x) ((and (stringp x) (= 1 (length x))) (char x 0)) ((symbolp x) (as-char (str x))) (t (error (str (list "invalid-char!" x) )))) ) ;;Gives us clj->cl reader for chars... (set-macro-character #\\ #'(lambda (stream char) (declare (ignore char)) (let ((res (read stream t nil t))) (as-char res))) ) ;;Doesn't work currently, since we can't redefine ;;print-method for chars... (defun print-clj-char (c &optional (stream t)) "Generic char printer for clojure-style syntax." (format stream "\~c" c)) (defun print-cl-char (c &optional (stream t)) "Generic char printer for common lisp syntax." (format stream "#\~c" c)) (defun quoted-read (stream char) (declare (ignore char)) (let ((res (read stream t nil t))) (if (atom res) `(quote ,res) `(clj-quote ,res)))) ;;This should be consolidated... (set-macro-character #\' #'quoted-read) ;;need to define quasiquote extensions... ;;quasiquoting has different behavior for literal datastructures.. ;;in the case of clojure, we provide fully-qualified symbols vs. ;;standard CL-symbols. We have reader support for them, ;;that is, blah/x vs x. ;;so, clojure resolves the symbol in the current ns, at read-time. ;; (defun resolved-symbol (s) ;; (let* ((this-package (package-name *package*))) ;; (multiple-value-bind (x y) ;; (find-symbol (symbol-name s)) ;; (if x ;; ;;symbol exists ;; `(,(package-name (symbol-package x)) ,(symbol-name x)) ;; `(,this-package ,(symbol-name s)) ;; )))) ;; (defun qualify (s) ;; (apply #'common-utils::symb ;; (let ((res (resolved-symbol s))) ;; (list (first res) "::" (second res))))) ;; (defun quasi-quoted-read (stream char) ;; (declare (ignore char)) ;; (let ((res (read stream t nil t))) ;; (cond ((symbolp res) ;; (let ((resolved ))) ;; `(quote ,res)) ;; (t `(clj-quote ,res))))) ;;Additionally, for dataliterals, quasiquote serves as a template ;;for building said datastructure, as if by recursively quasiquoting ;;elements in the expression. ;;Additionally, clojure ;;we can get package-qualified symbols via: ;;`(common-lisp-user::x) ;;but they print as 'x ;;s.t. `[x y] ;;namespace-qualified symbols are kind of out of bounds at the ;;moment... (defun push-reader! (literal ldelim rdelim rdr) (progn (setf *literals* (union (list literal) *literals*)) (set-macro-character ldelim rdr) (set-syntax-from-char rdelim #\)))) (defun quoting? () (> sb-impl::*backquote-depth* 0)) ;;This now returns the actual pvector of items read from ;;the stream, versus a quoted form. Should work nicely ;;with our protocol definitions now! ;;The issue we run into with our EDN forms is this: ;;(defparameter x 2) ;;(eval [x]) ;;should yield [2] ;;we don't currently. ;;So, ;;Quasiquoting custom data literals.. ;;=================================== ;;THis is way janky... ;;I'm not afraid to say I don't know how I pulled this off. ;;The key is that the quasiquoting mechanism in backq.lisp ;;has a sb-int:comma struct to denote 3 kinds of commas: ;;0 -> ,x ;;1 -> ,.x ;;2 -> ,@x ;;We ignore the dot version for now, although it's probably simple ;;enough to get working. ;;So we just manually build the expression. ;;If it's not a comma, we quasiquote it and let the macroexpander ;;figure it out. ;; (case (sb-int:comma-kind x) ;; (0 (cons expr acc)) ;; ;;I don't think we want to eval here. ;; (2 (progn (pprint expr) ;; (common-lisp:reduce (lambda (a b) (cons b a)) expr :initial-value acc) ;; ;(nreverse (list (list 'apply '(function concat) expr))) ;; )) ;; (1 (error "comma-dot not handled!"))) (defun quoted (x) (cond ((symbolp x) (scase x ((function list cons apply sequences::seq->list) x) (t (list 'quote x)))) ((listp x) (scase (first x) ((function quote clj-quote) x) (t (mapcar #'quoted x)))) (t x))) (defmacro quoted-body (x) (list 'quote (quoted x))) (defun quasify (xs) (list 'apply '(function concat) (nreverse (common-lisp:reduce (lambda (acc x) (if (sb-int:comma-p x) (cons (let ((expr (sb-int:comma-expr x))) (case (sb-int:comma-kind x) (0 (list 'list expr)) ;;I don't think we want to eval here. (2 expr) (1 (error "comma-dot not handled!")))) acc) ;; (cons (list 'list x) acc))) xs :initial-value (list 'list))))) (defmacro quasiquote (thing) (list 'sb-impl::quasiquote thing)) (defmacro data-literal (ctor &rest body) (list 'literal (list 'apply ctor (list* 'sequences::seq->list body)))) (defmacro quoted-data-literal (ctor &rest body) (list 'literal (list 'apply ctor (list* 'sequences::seq->list (eval `(quoted-body ,body)))))) (defun backquote-charmacro (stream char) (declare (ignore char)) (let* ((expr (let ((sb-impl::*backquote-depth* (1+ sb-impl::*backquote-depth*))) (read stream t nil t))) (result (list 'quasiquote expr))) (if (and (sb-impl::comma-p expr) (sb-impl::comma-splicing-p expr)) ;; use RESULT rather than EXPR in the error so it pprints nicely (sb-impl::simple-reader-error stream "~S is not a well-formed backquote expression" result) (scase (when (listp expr) (common-lisp:first expr)) (literal expr) (data-literal expr) (t result))))) ;;Original from Stack Overflow, with some slight modifications. ;;Have to make this available to the compiler at compile time! ;;Maybe move this into a clojure-readers.lisp or something. ;;We need to modify this. It implicity acts like quote for ;;symbols, since we're using read-delimited-list. (defun |bracket-reader| (stream char) "A reader macro that allows us to define persistent vectors inline, just like Clojure." (declare (ignore char)) (if (not (quoting?)) (apply #'persistent-vector (read-delimited-list #\] stream t)) (list 'literal (list* 'data-literal (list 'function 'persistent-vector) (list (quasify (read-delimited-list #\] stream t))))) )) ;;Original from Stack Overflow, with some slight modifications. (defun |brace-reader| (stream char) "A reader macro that allows us to define persistent maps inline, just like Clojure." (declare (ignore char)) (if (not (quoting?)) (apply #'persistent-map `(,@(read-delimited-list #\} stream t))) (list 'literal (list* 'data-literal (list 'function 'persistent-map) (list (quasify (read-delimited-list #\} stream t))))) )) (set-macro-character #\{ #'|brace-reader|) (set-syntax-from-char #\} #\)) (push-reader! 'clclojure.pvector:persistent-vector #\[ #\] #'|bracket-reader|)) (set-macro-character #\` 'backquote-charmacro nil) (set-macro-character #\~ 'sb-impl::comma-charmacro nil) (comment ;;WIP, moving to more elegant solution from named-readtables.... ;; (defreadtable clojure:syntax ;; (:merge :standard) ;; (:macro-char #\[ #'|bracket-reader| t) ;; (:case :preserve)) ) ;;https://gist.github.com/chaitanyagupta/9324402 ;;https://common-lisp.net/project/named-readtables/
11,115
Common Lisp
.lisp
248
35.439516
102
0.556406
joinr/clclojure
224
8
4
EPL-1.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
adee11e9e6a04b77b8cb55b9c2db1b5ca6edb0eb2d10b52962fae313f1c496c1
396
[ -1 ]
397
pmap.lisp
joinr_clclojure/pmap.lisp
;This is an implementation of Clojure's ;persistent map for Common Lisp. (defpackage :clclojure.pmap (:use :common-lisp) (:export :persistent-map :empty-map? :pmap-count :pmap-map :pmap-reduce) (:shadow :assoc :find)) ; :pmap-chunks ; :pmap-element-type ; :pmap-assoc ; :pmap-nth)) (in-package clojure.pmap) ;Original from Stack Overflow, with some slight modifications. (defun |brace-reader| (stream char) "A reader macro that allows us to define persistent maps inline, just like Clojure." (declare (ignore char)) `(persistent-map ,@(read-delimited-list #\] stream t))) (set-macro-character #\{ #'|brace-reader|) (set-syntax-from-char #\} #\)) ;;Currently deferred... ;;For now, we'll just use a COW map implementation ;;i.e. wrap a hashtable and copy its contents... (define-condition not-implemented (error) ((text :initarg :text :reader text))) ;utility functions ;Persistent maps require a lot of array copying, and ;according to the clojure implementation, bit-twiddling. ;porting from Spiewak's excellent blog post, ;which is a port from Clojure's implementation. (defconstant +branches+ 32) ;use a 32-way trie.... ;a bytespec is like a window.. ;it's a user-defined set of continugous bits in an integer ;use (byte width position) to define the window... (defconstant +bit-width+ 5) (defconstant +mask+ (byte +bit-width+ 0)) ;denotes [00000] with "weights" [2^4 2^3 2^2 2^1 2^0] (defun >>> (i n) "Shift integer i by n bits to the right." (ash i (* -1 n))) (defun <<< (i n) "Shift integer i by n bits to the left." (ash i n)) (defun last-five-bits (n) "Helper to mask everything but the 5 least-significant bits." (mask-field +mask+ n)) (defun mask (hash shift) "Helper, used by maps. Maps a hash into a local index at given level in the trie." (last-five-bits (>>> hash shift))) (defun bit-pos (hash shift) "Helper to compute the bit-position of n from a mask. This provides a mapping to the nth bit" (<<< 1 (mask hash shift))) (defun index (n) "Given an index into a hash, which represents a sparse mapping of values from [0 31] to n children, we can find out which child the index represents by using a logical count of the 1 bits in n." (logcount (1- n))) (define-condition index-out-of-bounds (error) ((text :initarg :text :reader text))) (defun copy-vector (array n &key (element-type (array-element-type array)) (fill-pointer (and (array-has-fill-pointer-p array) (fill-pointer array))) (adjustable (adjustable-array-p array))) "Returns an undisplaced copy of ARRAY, with same fill-pointer and adjustability (if any) as the original, unless overridden by the keyword arguments. " (let* ((dimensions (incf (first (array-dimensions array)) n)) (new-array (make-array dimensions :element-type element-type :adjustable adjustable :fill-pointer fill-pointer))) (dotimes (i (array-total-size array)) (setf (row-major-aref new-array i) (row-major-aref array i))) new-array)) ;Persistent Map definition: ;A persistent hashmap is a small structure that points to a root node. ;It also contains information about the underlying trie, such as null ;keys, the count of elements, etc. (defstruct pmap (count 0) (root nil) (has-null nil) (null-value nil)) (defun ->pmap (count root has-null null-value) (make-instance pmap :count count :root root :has-null has-null :null-value null-value)) (defconstant +empty-map+ (->pmap)) (defun empty-map () +empty-map+) ;The INode interface is crucial. We dispatch based on the node types... ;We'll implement the interface as a set of generic functions. (defgeneric assoc (nd shift hash key val &optional addedLeaf)) (defgeneric without (nd shift hash key)) (defgeneric find (shift hash key)) ;(defgeneric find(shift hash key notFound)) (defgeneric nodeSeq (nd)) ; assoc(AtomicReference<Thread> edit, int shift, int hash, Object key, Object val, Box addedLeaf); ;INode without(AtomicReference<Thread> edit, int shift, int hash, Object key, Box removedLeaf); (defgeneric kvreduce (f init)) ;(defgeneric fold (combinef reducef fjtask fjfork fjjoin)) ;;note -> clojure's implementation uses an object array... ;;so that the distinction between nodes and data is blurred. ;;a node is just a thread-safe wrapper around an object array. ;;in CL, this is just an array without an initial type arg. (defun make-data (&key (branches +branches+) (element-type t) (initial-element nil)) "Standard constructor for a node in our hash trie." (if (and (null initial-element) (not (eq element-type t))) (make-array branches :element-type element-type) (make-array branches :element-type element-type :initial-element initial-element))) (defun make-node () (make-data)) (defun make-indexed-node () (make-data :branches +indexed-branches+)) ;define implementations for different node types: ;-Type identifier for empty nodes, i.e. empty maps. ;empty-node ;(defstruct empty-node ;-Type identifier for nodes with a single value. ;-This is optimized away in the clojure java implementation... ;leaf-node ;-Type identifier for nodes with 16 key/vals (full or array nodes). (defstruct array-node count (nodes (make-data))) (defun ->array-node (count nodes) (make-array-node :count count :nodes nodes)) ;-Type identifier for nodes that project a 32-bit index, the ;-bitmap, onto an array with less than 32 elements. ;bitmapindexed-node (defconstant +indexed-branches+ 16) ;indexes contained 8 keyval pairs. (defstruct indexed-node (bitmap 0) (nodes (make-data :branches +indexed-branches+)) ) (defun ->indexed-node (bitmap nodes) (make-indexed-node :bitmap bitmap :nodes nodes)) (defconstant +empty-indexed-node+ (make-indexed-node)) (defun empty-indexed-node () +empty-indexed-node+) (declaim (inline key-idx val-idx key-at-idx val-at-idx)) (defun key-idx (idx) "Return the offset key of an index" (* 2 idx)) (defun val-idx (idx) "Return the offset value of an index" (1+ (* 2 idx))) (defun equiv (x y) "Generic equality predicate." (error 'not-implemented)) (defun key-at-idx (idx nodes) "Fetches the offset key from an array packed like a propertylist, key/val/key/val/..." (aref nodes (* 2 idx))) (defun val-at-idx (idx nodes) "Fetches the offset value from an array packed like a propertylist, key/val/key/val/..." (aref nodes (1+ (* 2 idx)))) (defun pairs (xs) "Aux function that converts a list of xs into a list of pairs." (do ((acc (list)) (remaining xs (rest (rest remaining)))) ((null remaining) (nreverse acc)) (let ((x (first remaining)) (y (second remaining))) (when (and x y) (push (list x y) acc))))) (defun assoc-array (arr idx k v) (progn (setf (aref arr (key-idx idx)) k) (setf (aref arr (val-idx idx)) v))) (defun hash (o) "Generic hash function." (error 'not-implemented)) (defun remove-pair (array idx) "Auxillary function to drop pairs from an array where the pairs are packed akin to a plist, ex. key/val/key/val....returns a new, smaller array with the pair removed." (error 'not-implemented) (cond ((> idx (- (1- (array-total-size array)) 2)) (error 'index-out-of-bounds)) ((and (= (array-total-size array) 2) (= idx 0)) nil) (t (let* ((dimensions (decf (first (array-dimensions array)) 2)) (new-array (make-array dimensions :element-type (array-element-type array) :fill-pointer (and (array-has-fill-pointer-p array) (fill-pointer array)) :adjustable (adjustable-array-p array)))) (loop for i from 0 to (1- idx) do (assoc-array new-array i (key-at-idx i array) (val-at-idx i array))) (loop for i from (1+ idx) to (- (array-total-size new-array) 2) do (assoc-array new-array (1- i) (key-at-idx i array) (val-at-idx i array))) new-array)))) (defun insert-pair (array idx k v) "Auxillary function to drop pairs from an array where the pairs are packed akin to a plist, ex. key/val/key/val....returns a new, smaller array with the pair removed." (error 'not-implemented) (cond ((> idx (1- (- (array-total-size array) 2))) (error 'index-out-of-bounds)) (t (let* ((dimensions (incf (first (array-dimensions array)) 2)) (new-array (make-array dimensions :element-type (array-element-type array) :fill-pointer (and (array-has-fill-pointer-p array) (fill-pointer array)) :adjustable (adjustable-array-p array)))) (loop for i from 0 to (1- idx) do (assoc-array new-array i (key-at-idx i array) (val-at-idx i array))) (assoc-array new-array idx k v) (when (< idx (1- (/ (array-total-size array) 2))) (loop for i from idx to (1- (/ (array-total-size new-array) 2)) do (assoc-array new-array (1+ i) (key-at-idx i array) (val-at-idx i array)))) new-array)))) ;; INode createNode(int shift, Object key1, Object val1, int key2hash, Object key2, Object val2) { ;; int key1hash = hash(key1); ;; if(key1hash == key2hash) ;; return new HashCollisionNode(null, key1hash, 2, new Object[] {key1, val1, key2, val2}); ;; Box _ = new Box(null); ;; AtomicReference<Thread> edit = new AtomicReference<Thread>(); ;; return BitmapIndexedNode.EMPTY ;; .assoc(edit, shift, key1hash, key1, val1, _) ;; .assoc(edit, shift, key2hash, key2, val2, _) ; (defun create-node (shift key1 val1 key2hash key2 val2) "Generic function to create nodes....I need a better explanation. Also, the box var may not be necessary. I have to see how it's used..." (let ((key1hash (hash key1))) (if (= key1hash key2hash) ;record the hash collision with a new collision node, these will chain. (->collision-node key1hash 2 (vector key1 val1 key2 val2)) (let ((box (list))) ;else assoc both values into an empty indexed node. (assoc (assoc (empty-indexed-node) shift key1hash key1 val1 box) shift key2hash key2 val2 box))))) (defun clone-and-set (arr &rest kvps) "Aux function that clones an array and sets the element at idx = to v, where idx and v are drawn from the list kvps." (let ((acc (copy-vector arr 0))) (loop for (idx v) in (pairs kvps) do (setf (aref acc idx) v) finally (return acc)))) (declaim (inline bit-set?)) (defun bit-set? (bitmap i) "Determines if the ith bit is set in bitmap." (not (zerop (logand (>>> bitmap i) 1)))) (defun indexed-array->full-array (nodes bitmap shift hash key val addedleaf) "Projects an indexed array, indexed by a 32-bit map, 16 (unknown) bits of which indicate the presence of a key in an an underlying 32-element assoc array, onto an full array. The full array is a direct mapping of a 32-bit key, projected onto a 32 element array of nodes, by masking all but the last 5 bits. This is basically an optimization, so that we use indexed nodes while the node is sparse, when the keys are <= 16, then shift to a node with no intermediate bit mapping." (let ((newnodes (make-data)) ;create the 32 element array for the arraynode. (jdx (mask hash shift)) ;set the index for the element we're adding. (j 0)) (progn (setf (aref newnodes jdx) ;initialze the newly added node. (assoc (empty-indexed-node) (+ 5 shift) hash key val addedleaf)) (loop for i from 0 to 32 ;traverse the bitmap, cloning... do (when (bit-set? bitmap i) ;bit i is stored at j (if (null (aref nodes j)) (setf (aref newnodes i) (aref nodes (1+ j))) (assoc (empty-indexed-node) (+ 5 shift) (hash (aref nodes j)) (aref nodes j) (aref nodes (1+ j)) addedleaf)) (incf j 2))) newnodes))) (defun indexed-node->array-node (nd shift hash key val addedleaf) "Projects an indexed node, indexed by a 32-bit map, 16 (unknown) bits of which indicate the presence of a key in an an underlying 32-element assoc array, onto an array node. The array node is a direct mapping of a 32-bit key, projected onto a 32 element array of nodes, by masking all but the last 5 bits. This is basically an optimization, so that we use indexed nodes while the node is sparse, when the keys are <= 16, then shift to a node with no intermediate bit mapping." (with-slots (bitmap nodes) nd (->array-node (1+ (logcount bitmap)) (indexed-array->full-array nodes bitmap shift hash key val addedleaf)))) ;Partially implemented. ;; (defmethod assoc ((nd indexed-node) shift hash key val addedLeaf) ;; (with-slots (bitmap nodes) nd ;; (let ((b (bit-pos hash shift)) ;; (idx (index b)) ;; (exists? (not (zerop (logand bitmap b))))) ;; (if exists? ;; (let ((k (key-at-idx idx nodes)) ;; (v (val-at-idx idx nodes))) ;; (cond ((null k) ;; (let ((newnode (assoc v (+ 5 shift) hash key val addedleaf))) ;; (if (eq val-at-idx newnode) ;; nd ;no node to add to null key. ;; ;actually have val associated with null, causes changed. ;; (->indexed-node bitmap (clone-and-set nodes (val-idx idx) newnode))))) ;; ((equiv key k) ;key exists. ;; (if (eq v val) ;; nd ;no change ;; ;value changed ;; (->indexed-node bitmap (clone-and-set nodes (val-idx idx) val)))) ;; (t ;; (->indexed-node bitmap (clone-and-set nodes (key-idx idx) nil ;; (val-idx idx) (create-node (+ 5 shift) k v hash key val))))) ;; ) ;; (if (>= (logcount bitmap) +indexed-branches+) ;; ;create an array node, or full node, if the number of on-bits is excessive. ;; (indexed-node->array-node nd shift hash key val addedleaf) ;; (let ((newarray (copy-vector nodes 2))) ;; (progn ( ;; )))))) ;-Type identifier for nodes that have a direct correspondence ;-between a 5 bit integer hash and an entry in the 32 element ;-node array. ;full-node ;-Type identifier for nodes that collide. Essentially, a 32 ;-element array of nodes that have the same hash. I have an ;-idea of how this works using the 5 bit hashing scheme. ;collision-node (defstruct collision-node hash count nodes) (defun ->collision-node (hash count nodes) (make-instance collision-node :hash hash :count count :nodes nodes)) (defconstant +empty-pvec+ (make-pvec)) (defun empty-vec () +empty-pvec+) (defun empty-vec? (v) (eq v +empty-pvec+)) (defgeneric vector-count (v) (:documentation "Fetches the count of items in the persistent vector.")) (defmethod vector-count ((v pvec)) (pvec-counter v)) (defun tail-end (n &optional (b +branches+)) "Given a count of items, n, where is the tail located in an integer hash? Note, this assumes a 5 bit encoding for levels in an 32-way trie. I might generalize this later..." (if (< n b) 0 (<<< (>>> (1- n) +bit-width+) +bit-width+))) (defun tail-off (v) "Defines the integer index at which the tail starts." (tail-end (pvec-counter v) +branches+)) (defun count-tail (v) (length (pvec-tail v))) (defun find-node (rootnode shift idx) "Given a rootnode with child nodes, a bit-shift amount, and an index, traverses the rootnode's children for the node defined by idx." (if (<= shift 0) rootnode ;found our guy (find-node (aref rootnode (last-five-bits (>>> idx shift))) (- shift +bit-width+) idx))) (defun copy-path (root shift0 idx &optional (leaf-function #'identity)) "Copies the nodes from root to idx, returning a new root. If a leaf function is provided, it will be applied to the final node. If the path does not exist, intermediate structures WILL be created." (labels ((walk (rootnode shift) (if (zerop shift) (funcall leaf-function rootnode) (let ((childidx (last-five-bits (>>> idx shift))) (newnode (if (null rootnode) (make-node) (copy-vector rootnode 0)))) (progn (setf (aref newnode childidx) (walk (if (null rootnode) (make-node) (aref rootnode childidx)) (- shift +bit-width+))) newnode))))) (walk root shift0))) (defun insert-path (rootnode shift idx x) "Copies the path to the node at idx, replacing the value of the final node on the path, the address at idx, with value x." (copy-path rootnode shift idx #'(lambda (node) (progn (setf (aref node (last-five-bits idx)) x) node)))) (defgeneric get-node (v idx) (:documentation "Fetches the node (an object array) at index idx, from persistent vector v, where idx is 0-based. Currently assumes 5-bit encoding of integer keys for each level, thus 32 elements per level.")) (defmethod get-node ((v pvec) idx) (if (and (<= idx (pvec-counter v)) (>= idx 0)) (if (>= idx (tail-end (pvec-counter v) +branches+)) (pvec-tail v) (find-node (pvec-root v) (pvec-shift v) idx)) (error 'index-out-of-bounds))) (defgeneric nth-vec (v idx) (:documentation "Returns the nth element in a persistent vector.")) (defmethod nth-vec ((v pvec) idx) (aref (get-node v idx) (last-five-bits idx))) ;copy-vector should probably use displaced arrays. (defun conj-tail (v x) "Conjoins item x onto pvector v's tail node, returning a new pvector that uses the new tail, along with an incremented count." (let ((newtail (if (null (pvec-tail v)) (vector x) (let ((growntail (copy-vector (pvec-tail v) 1))) (progn (setf (aref growntail (1- (length growntail))) x) growntail))))) (make-pvec :root (pvec-root v) :tail newtail :shift (pvec-shift v) :counter (1+ (pvec-counter v))))) (defun new-path (shift node) "Given a node and an amount of initial 'shift', recursively builds a nested tree of nodes, currently 32-wide arrays, linked by the first element, with node at the logical 'bottom' of the tree, where shift = 0. This allows us to inject a node, with the required path structure, into the trie, if the path did not exist before. Typically used for inserting the tail into the pvector." (if (zerop shift) node (let ((newnode (make-node))) (progn (setf (aref newnode 0) (new-path (- shift +bit-width+) node)) newnode))))
18,846
Common Lisp
.lisp
424
39.240566
99
0.660306
joinr/clclojure
224
8
4
EPL-1.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
790c10040511193e4efd0d4df8a3199bcc94ed87f8e4e18a89f62e1ab3f84d55
397
[ -1 ]
398
protocols.lisp
joinr_clclojure/protocols.lisp
;;a simple implementation of clojure protocols, and deftype. ;;this will help with building libraries, particularly ;;the seq libraries. ;;If we can bolt on a few fundamental operations, we can take ;;advantage of the bulk of the excellent bootstrapped clojure ;;defined in the clojurescript compiler. (defpackage :clclojure.protocols (:use :common-lisp :common-utils :clclojure.reader :clclojure.pvector :clclojure.eval) (:export :defprotocol :extend-protocol :extend-type :satisfies? :protocol-exists? :list-protocols :clojure-deftype)) (in-package :clclojure.protocols) ;;aux ;;bootstrapping hack! (defun vector? (x) (typep x 'clclojure.pvector::pvec)) (defun vector-expr (x) (and (listp x) (eq (first x) 'persistent-vector))) ;;this keeps args in order....we nreverse all over the place. ;;Since we prototyped using lists, and now the vector ;;reader is working well, we're in the middle of migrating ;;to vectors. For now, we allow backwards compat with both ;;(perhaps allowing CL to define protocols in their native ;;tongue, I dunno). In the future, we'll enforce ;;vectors.... ;;TBD replace with seq (defun as-list (xs) (if (vector? xs) (vector-to-list xs) (if (vector-expr xs) (rest xs) xs))) ;;changed this since we have lists now... (defun drop-literals (xs) (filter (lambda (x) (not (or (literal? x) (stringp x)))) (as-list xs))) ;;Note-> we need to add support for variadic functions, ;;and variadic protocols members. ;;protocols are used extensively, as is deftype. There are a ;;few additional data types that we need to provide. ;Protocol specifications take on the form below: ;(protocolname ; (function-name1 (args) &optional doc) ; function-name2 (args) &optional doc)) ;; (defparameter samplespec ;; '(ISeq ;; (next (coll) ;; "Gets the next element from the sequence") ;; (more (coll) ;; "Gets the rest of the sequence."))) (defun spec-name (protocolspec) (car protocolspec)) (defun spec-functions (protocolspec) (remove-if-not #'listp (as-list protocolspec))) ;;bombing out since we can't extend SEQUENCE to ;;our own types (thanks hyperspec!) ;;We can, however, enforce that one must use persistent ;;vectors....or....we can coerce the vectors to lists, which ;;are acceptable sequences.... (defun function-names (protocolspec) (mapcar #'first (spec-functions protocolspec))) (defun function-info (protocolspec) (mapcar #'first (spec-functions protocolspec))) ;;TODO replace this with a more stringent version based ;;on protocol-function implementations rather than the spec. ;;This has arity information derived, so can provide a stronger ;;structural check. (defun make-satisfier (protocolspec) "From a list of function specs, builds a function that compares a list of function specs to ensure both specifications have the same function names. If no function specs are provided, the identity function is returned." (let ((names (function-names protocolspec))) (if (null names) (lambda (x) (declare (ignore x)) t) ;;We need to harden this to check arities for the functions. (lambda (newspec) (null (set-difference names (function-names newspec))))))) ;a sample implementation for ISeqs... (comment (defparameter sampleimp '(ISeq (next (coll) (car coll)) (more (coll) (cdr coll))))) ;;From stack overflow. It looks like the compiler needs a hint if we're ;;defining struct/class literals and using them as constants. (EVAL-WHEN (:compile-toplevel :load-toplevel :execute) ;;A protocol is a name, a set of generic functions, and a set of ;;types that implement the protocol. (defstruct protocol name functions satisfier doc (members (list))) (defmethod make-load-form ((v protocol) &optional env) (declare (ignore env)) (make-load-form-saving-slots v)) ;;Protocol function carries information about the arities ;;documentation, and other meta derived from the spec. (defstruct protocol-function name args bodies arities doc) (defmethod make-load-form ((v protocol-function) &optional env) (declare (ignore env)) (make-load-form-saving-slots v))) (defun ->protocol (name functions &optional satisfier doc) (make-protocol :name name :functions functions :satisfier satisfier :doc (or doc "Not Documented"))) ;;not used. (defun protocol-to-spec (p) (with-slots (name functions) p (list name functions))) (defun args->arities (xs) (mapcar (lambda (args) (multiple-value-bind (l variadic?) (common-utils::args-type (as-list args)) (list :args args :arity l :variadic? (when variadic? t)))) xs)) (defun function->info (name args-doc) (let* ((args (remove-if #'stringp args-doc)) (doc (first (remove-if-not #'stringp args-doc))) (arities (args->arities args))) (make-protocol-function :name name :args args :bodies (length arities) :arities arities :doc (or doc "not documented")))) ;;We won't keep a central listing of protocols. They'll be first class objects, ;;as in Clojure on the JVM. ;;So, for bookeeping, it'd be nice to hold onto function specifications. ;;Simple things like ;;{:name blah ;; :arities #{1 2 3 :variadic}} ;Debating whether to keep this around, ;I may not need it... (defparameter *protocols* (make-hash-table :test #'eq)) ;Probably deprecated soon... (defun get-protocol (name) (gethash name *protocols*)) ;;we can replace this using CLOS. We just add a generic function that ;;tells us if an object satisfies a protocol. ;;like (satisfies-protocol? (protocol obj)) ;;Since protocols are actual objects (structs in this case), we call ;;(satisfies? the-protocol-obj the-obj) ;;which delegates to ;;((get-slot 'satisfier the-protocol-obj) the-obj) ;;So we let the protocol tell us if an object satisfies its protocol. ;;When we do defprotocol then, we add an implementation of (defun add-protocol-member (pname membername) "Identifies membername as an implementor of protocol pname" (multiple-value-bind (p exists?) (get-protocol pname) (when exists? (push membername (protocol-members p))))) ;Probably deprecated soon... (defun protocol-exists? (name) (not (null (get-protocol name)))) (defun drop-protocol (name) "Eliminates any bindings to the quoted protocol name, including generic functions." (if (protocol-exists? name) (let ((p (get-protocol name))) (progn (unintern (protocol-name p)) (dolist (n (protocol-functions p)) (unintern n)) (remhash name *protocols*))))) (defun list-protocols () "Lists all known protocols." (loop for k being the hash-keys in *protocols* collect k)) ;;we should cache this.... (defgeneric satisfies? (p x)) (defmethod satisfies? ((p protocol) x) (not (null (find (type-of x) (protocol-members p))))) (defmethod satisfies? ((p protocol) x) (not (null (find (type-of x) (protocol-members p))))) (define-condition protocol-exists (error) ((text :initarg :text :reader text))) (define-condition malformed-protocol (error) ((text :initarg :text :reader text))) (define-condition missing-implementations (error) ((text :initarg :text :reader text))) (define-condition name-collision (error) ((text :initarg :text :reader text))) ;when we add protocols, we just want to ensure that the ;right generic functions are implemented. ;We let Common Lisp sort out whether the generic functions ;are actually correct. (defun add-protocol (p) (with-slots (name) p (if (null (get-protocol name)) (setf (gethash name *protocols*) p) ; (error 'protocol-exists)))) (progn (print (format nil "Overwriting existing protocol ~A" name)) (drop-protocol `(quote ,name)) (setf (gethash name *protocols*) p))))) ;;We need to add the multiple-dispatch function that's in bootstrap at the moment. ;;A multiple-body protocol implementation could be... (defparameter proto-spec '(defprotocol ITough (get-toughness [x] [x y] "gets the toughness of x, or if x is compared to y, the relative toughness"))) ;;If we want to use generic functions to mirror single-dispatch implementations of ;;protocols, we have to allow for multiple-body functions. ;;So, there's probably a protocol dispatch function.. ;;Just like our fn macro... ;;If we have multiple specs, [x] [x y], in this case, we need a generic function ;;that dispatches based on the first arg of the spec. ;;Alternately....we can just use the fn body from before... ;;This only ever matters if there are multiple function bodies. If there's only one, ;;we're golden (that's the current situation). ;;note: dealing with reader-literals and how macros parse stuff, like pvectors, ;;so we're just filtering them out of arglists. ;; (defun build-generic (functionspec) ;; (let* ((args (drop-literals (second functionspec))) ;; (name (first functionspec)) ;; (docs (if (= (length functionspec) 3) ;; (third functionspec) ;; "Not Documented"))) ;; `(progn (defgeneric ,name ,args (:documentation ,docs)) ;; ;;lets us use protocol fns as values... ;; (defparameter ,name (function ,name)) ;; (setf (symbol-function (quote ,name)) (symbol-value (quote ,name))) ;; ,name))) (defun build-generic (functionspec) (let* ((args (drop-literals (rest functionspec))) (name (first functionspec)) (doc (first (last functionspec))) (docs (if (stringp doc) doc "Not Documented"))) (case (length args) (1 (let ((args (drop-literals (first args)))) `(progn (defgeneric ,name ,args (:documentation ,docs)) ;;lets us use protocol fns as values... (defparameter ,name (function ,name)) (setf (symbol-function (quote ,name)) (symbol-value (quote ,name))) ,name))) ;;variadic (otherwise `(progn (defgeneric ,name (,'this ,'&rest ,'args) (:documentation ,docs)) ;;lets us use protocol fns as values... (defparameter ,name (function ,name)) (setf (symbol-function (quote ,name)) (symbol-value (quote ,name))) ,name))))) (defun quoted-names (xs) (mapcar (lambda (x) (list 'quote x)) (function-names xs))) (defun derive-protocol-functions (xs) (let* ((funcs (remove-if #'stringp xs))) (mapcar (lambda (spec) (function->info (first spec) (rest spec))) funcs))) (defun spec-to-protocol (protocolspec) (let ((pfs (gensym "protofuncs")) (doc (last (last protocolspec)))) `(let ((,pfs (,'list ,@(derive-protocol-functions (rest protocolspec))))) (progn ,@(mapcar #'build-generic (spec-functions protocolspec)) (->protocol (quote ,(spec-name protocolspec)) ,pfs (make-satisfier (quote ,protocolspec)) ,(if (stringp doc) doc "Not Documented")))))) ;;we'll have to update this guy later, but for now it's okay. ;;Added that a symbol gets created in the current package. ;; (defmacro defprotocol (name &rest functions) ;; (let ((p (gensym)) ;; (spec (cons name functions))) ;; `(let ((,p (eval (spec-to-protocol (quote ,spec))))) ;; (progn (add-protocol ,p) ;; (defparameter ,name ,p))))) (defmacro defprotocol (name &rest functions) (let ((p (gensym)) (spec (cons name functions))) `(let ((,p ,(spec-to-protocol spec))) (progn (add-protocol ,p) (defparameter ,name ,p))))) (comment (defprotocol IComplex (f2 [x] [x y] [x y & zs])) (defparameter test-impl '(common-lisp:cons (f2 [x] x) (f2 [x y] (cons y x)) (f2 [z y & zs] (append (cons y z) zs)))) (defparameter parsed '((CONS (F2 [X] X) (F2 [X Y] (CONS Y X)) (F2 [Z Y & ZS] (APPEND (CONS Y Z) ZS))))) ) ;;once we have implementations, grouped by type.. ;;we need to parse the functions within them. ;;We expect something of the form: ;;(type-name &rest implementations) ;;where ;;implementations conform to ;;(function-name arg-vector & body) ;;We have multiple possible implementations ;;E.g. ;;(function-name arg-vector1 & body) ;;(function-name arg-vector2 & body2) ;;Order is not guaranteed either. ;;So, we need to group-by function-name. ;;(function-name (arg-vector1 body1) ;; (arg-vector2 body2) ;; (arg-vector3 body3)) ;;May have to use seql instead of eql for symbol equality.. ;;collect-functions will coerce function definitions with multiple ;;implementations in the above normal form into a ;;variadic form that's compatible with/expected by emit* ;;and leave single implementations alone. ;;So we'd get ;; (common-lisp:CONS ;; (F2 [X] X) ;; (F2 [X Y] (CONS Y X)) ;; (F2 [Z Y & ZS] (APPEND (CONS Y Z) ZS))) ;;parsed into the method ;; (CONS ;; (F2 ([X] X) ;; ([X Y] (CONS Y X)) ;; ([Z Y & ZS] ;; (APPEND (CONS Y Z) ZS)))) ;;while single-arg implementations, or ;;functions with only one implementation, ;;are parsed as single-arity functions. (defun collect-functions (type-fns) (let ((fns (group-by #'first (rest type-fns) ;:test #'common-utils:seql ))) (cons (first type-fns) (mapcar (lambda (kv) (case (length (second kv)) (1 (first (second kv))) ;;leave it alone. (otherwise ;;generate a variadic implementation. (cons (first kv) (nreverse (mapcar #'cdr (second kv))))))) (hash-table->entries fns))))) ;;extends protocol defined by name to ;;each type in the typespecs, where typespecs ;;are of the form... ;;(typename1 (func1 (x) (body)) ;; (func2 (x) (body)) ;; typename2 (func1 (x) (body)) ;; (func2 (x) (body))) (defun parse-implementations (x) (labels ((get-spec (acc specs) (if (null specs) acc (let ((arg (first specs))) (if (symbolp arg) (get-spec (cons (list arg) acc) (rest specs)) (let ((currentspec (first acc))) (get-spec (cons (cons arg currentspec) (rest acc)) (rest specs)))))))) (mapcar (lambda (x) (collect-functions (nreverse x))) ;#'nreverse (get-spec (list) x)))) ;; (defparameter samplext ;; '(pvec ;; (next (coll) (nth coll 0)) ;; (more (coll) (subvec coll)) ;; cons ;; (next (coll) (first coll)) ;; (more (coll) (rest coll)))) (defun implement-function (typename spec) (let* ((args (cond ((vector? (second spec)) (vector-to-list (second spec))) ;this is a crappy hack. ((vector-expr (second spec)) (rest (second spec))) (t (drop-literals (second spec))))) (newargs (cons (list (first args) typename) (rest args))) (body (third spec))) `(defmethod ,(first spec) ,newargs ,body))) ;;given something like this ;; '((f [this x] (list x)) ;; (f [this x y] (list x y))) ;;emit a lambda* dispatch function like ;;(lambda* ((f (this x) (list x)) ;; (f (this x y) (list x y))) ;; '((f [this x] (list x)) ;; (f [this x y] (list x y))) ;;On the implementation side, we need to replace ;;& - which is permissible in clj, with &rest for ;;common lisp. (defun replace-ampersand (xs) (substitute '&rest '& xs)) (defun emit-dispatch (specs) `(lambda* ,@(mapcar (lambda (spec) (let* ((args (replace-ampersand (vector-to-list (first spec)))) (body (rest spec))) `(,args ,@body))) specs))) ;;multiple arity protocol function implementation. (defun implement-function* (typename specs) (let ((dispatch (gensym "dispatch")) (name (first specs)) (fns (rest specs))) `(let ((,dispatch ,(emit-dispatch fns))) (defmethod ,name ((,'obj ,typename) ,'&rest ,'args) (apply ,dispatch ,'obj ,'args))))) (defmacro/literal-walker emit-method (protoname typename imp) `(progn (add-protocol-member (quote ,protoname) (quote ,typename)) ,@(mapcar (lambda (spec) (if (listp (second spec)) (implement-function* typename spec) (implement-function typename spec))) (rest imp)))) ;;this is the one choke point where we're getting ;;[x] -> (persistent-vector x) transforms in practice. (defun emit-implementation (name satvar imp) (let* ((quoted-imp (gensym "quotedimp")) (msg (str `(,name ,imp)))) `(let ((,quoted-imp (quote ,imp))) (if (funcall ,satvar ,quoted-imp) (emit-method ,name ,(first imp) ,imp) (error 'missing-implementations ,msg))))) (defmacro/literal-walker extend-protocol (name &rest typespecs) (let* ((imps (parse-implementations typespecs)) (satisfies? (gensym)) (emits (mapcar (lambda (imp) (emit-implementation name satisfies? imp)) imps))) `(let ((,satisfies? (protocol-satisfier (get-protocol (quote ,name))))) ,@emits))) ;Extend-type is also particularly useful. ;;Pending -> implement deftype. (comment ;Testing.... (defprotocol INamed (get-name (thing) "gets the name of the thing!") (say-name (thing) "Says the name of the thing!")) (extend-protocol INamed cons (get-name (thing) (car thing)) (say-name (thing) (pprint (format nil "The name is: ~A" (get-name thing))))) (defun test () (let ((data '(:tom))) (when (satisfies? INamed data) (pprint (get-name data))) (say-name data)) (defmacro cljmacro (name argvec & body) (let ((args (if (vector? argvec argvec) (eval `(clclojure.reader/quoted-children ,argvec))))) `(,@body))) ) ;;Deftype implementation. ;;Once we have protocols, deftype is pretty easy. ;;deftype is a hook into the type definition or object system of ;;the host environment. We'll use it to generate CLOS classes via ;;defclass. I may include an option to use deftype to build structs ;;which would likely kick ass for performance. ;;A deftype form is pretty easy: ;;(deftype name-of-type (field1 field2 ... fieldn) ;; Protocol1 ;; (function1 (args) body1) ;; Protocol2 ;; (function2 (args) body2)) ;; ;;Should expand into: ;;(progn ;; (defclass name-of-type ;; ((field1 :init-arg :field1) ;; (field2 :init-arg :field2))) ;; (extend-protocol Protocol1 name-of-type ;; (function1 (args) body1)) ;; (extend-protocol Protool2 name-of-type ;; (function2 (args) body2))) ) (defun symbolize (x) (read-from-string x)) (defun emit-class-field (nm s) `(,s :initarg ,(make-keyword s) :accessor ,(symbolize (str nm "-" s)))) (defun emit-protocol-extension (proto-name type-name imps) `(extend-protocol ,proto-name ,type-name ,@imps)) ;;impl has protocol (pfn ...) (pfn ...) (defmacro extend-type (typename &rest impls) (let ((imps (parse-implementations impls)) ;(name (gensym)) ;(the-imp (gensym)) ) `(progn ,@(mapcar (lambda (the-imp) (let ((expr `(emit-protocol-extension (quote ,(first the-imp)) (quote ,typename) (quote ,(rest the-imp))))) (eval expr))) imps)) ;; (if (funcall ,satisfies? imp) ;; (progn (add-protocol-member (quote ,name) typename) ;; (dolist (spec (rest imp)) ;; (eval (implement-function ,typename spec)))) ;; (error 'missing-implementation)) )) ;;the goal here is to define "instance-local" operations ;;at the method level, where fields refer to slots on the object. ;;so, we may have a object like {:a 2 :b 3} ;;fields [a b], ;;our implementations could be ;;(blah [obj] a) ;;undefined! ;;(blee [a] a) ;;defined, shadowing, poor form, but meh. ;;we need to extend the lexcial environment to include ;;field access... ;;(blah [obj] a) => ;;(blah [obj] ;; (with-slots ((a obj)) ; a)) ;;we can be more efficient if we walk the implementations ;;to detect field usage. For NOW, we'll just ;;bind all the fields in the lexical environment ;;of body, less the field names that are shadowed ;;by protocol args. ;;TODO: walk the body and collect fields to determine ;;the final set of fields to use (tailored). (defun with-fields (fields method args &rest body) (let* ((arglist (as-list args)) (var (first arglist)) (flds (set-difference (as-list fields) arglist))) ;;naive implementation is just bind all the slots.... (if flds `(,method ,args (with-slots ,flds ,var ,@body)) `(,method ,args ,@body)))) ;;we need to mod this. If the implementations refer to a field (and ;;the field is NOT shadowed as an argument to their method impl), we ;;need a call to with-slots to pull the referenced fields out to ;;mirror clojure's behavior. (defmacro clojure-deftype (name fields &rest implementations) (let* ((flds (cond ((vector? fields) (vector-to-list fields)) ((vector-expr fields) (rest fields)) (t fields))) (impls (mapcar (lambda (impl) (if (atom impl) impl (apply #'with-fields (cons flds impl)))) implementations))) `(progn (defclass ,name () ,(mapcar (lambda (f) (emit-class-field name f) ) flds)) ;;we need to parse the implementations to provide ;;instance-level fields... (extend-type ,name ,@impls) ;;debugging (defun ,(symbolize (str "->" name)) ,flds (make-instance ,`(quote ,name) ,@(flatten (mapcar (lambda (f) `(,(make-keyword f) ,f)) flds )))) ))) ;;Deftype exists in common lisp. (comment ;;An experimental class-bassed approach; putting this on ice for now. ;;This is our interface, which is a base class all protocols will ;;derive from. ;; (defclass IProtocol () ;; (name ;; functions ;; satisfier ;; (members ;; :initform (list)))) ;;Defining a protocol is just a matter of defining a new class that inherits ;;from IProtocol. ;; (defmacro defprotocol-1 (name functions &optional satisifer) ;; `(defclass ,name (IProtocol) ;; ((name :initform ,name) ;; (functions :initform functions) ;; ( ;; ) )
23,685
Common Lisp
.lisp
554
35.893502
108
0.616449
joinr/clclojure
224
8
4
EPL-1.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
f51fb3fd6c63d7d6d83ca790095b122ac7b2c593dcb7387cb723547528c3627a
398
[ -1 ]
399
keywordfunc.lisp
joinr_clclojure/keywordfunc.lisp
;;This is a legacy implementation of keywords-as-functions. ;;We'll probably revisit this. (defpackage :clclojure.keywordfunc (:use :common-lisp ;:clclojure.base :common-utils) (:export :keyfn? :key-accessor :->keyaccess :keyaccess-func :keyaccess-key :with-keyfn)) (in-package :clclojure.keywordfunc) (defparameter keyfns (make-hash-table)) (defun keyfn? (k) (gethash k keyfns)) ;;this is the general template for implementing ;;keyword access... ;; (defun :a (m) (gethash :a m)) ;; (defun (setf :a) (new-value m) ;; (setf (gethash :a m) ;; new-value)) (defun key-accessor (k) (let ((m (gensym "map")) (v (gensym "newval"))) `(progn (defun ,k (,m) (gethash ,k ,m)) (defun (,'setf ,k) (,v ,m) (,'setf (,'gethash ,k ,m) ,v)) ;(,'setf (gethash ,k keyfns) ,k) ))) ;;for localized keyaccess, i.e. inside ;;lets and friends.... (defclass keyaccess () ((key :initarg :key :accessor keyaccess-key) (func :accessor keyaccess-func)) (:metaclass sb-mop::funcallable-standard-class)) (defmethod initialize-instance :after ((obj keyaccess) &key) (with-slots (key func) obj (setf func (lambda (ht) (gethash key ht))) (sb-mop::set-funcallable-instance-function obj func) (eval (key-accessor key)) (setf (gethash key keyfns) obj) )) ;;keyaccessors print like keywords. (defmethod print-object ((obj keyaccess) stream) (prin1 (keyaccess-key obj) stream)) (defun ->keyaccess (k) (or (gethash k keyfns) (make-instance 'keyaccess :key k))) ;;now, to get the last step of "real" keyword access, we need to ;;detect when keyword literals used, and create keyword accessors for ;;them. One dirty way of doing that, is to use a reader macro for ;;keywords, and ensure that every single keyword that's read has a ;;commensurate keyaccess obj created. ;;That's effective, maybe not efficient, since we're duplicating our ;;keywords everywhere. A more efficient, but harder to implement, ;;technique is to macroexpand and walk the code inside a unified-let*. In ;;theory, we can detect any forms used in the function position, and ;;if they're keywords, compile them into keyword accessors. (defmacro with-keyfn (expr) (let ((k (first expr)) ) (if (keywordp k) (if (not (keyfn? k)) (progn (format nil "adding keyword access for: ~a " k ) (eval (key-accessor k)) `,expr)) `,expr))) ;;dumb testing ;; (defparameter ht (make-hash-table)) ;; (with-keyfn (:a ht)) ;; (with-keyfn (:b ht)) ;; (setf (:a ht) :bilbo) ;; (setf (:b ht) :baggins) ;; (with-keyfn (:a ht)) ;; (with-keyfn (:b ht))
2,754
Common Lisp
.lisp
73
33.356164
90
0.643393
joinr/clclojure
224
8
4
EPL-1.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
82455cf12a277468300d1b93addcf6cce21cc4643ee0d770cde0d17a9d1e654b
399
[ -1 ]