repo
string
commit
string
message
string
diff
string
aereal/dotfiles
7827f4e2008a2d258754a67d2c48efb77a0d9a6f
fix(zsh): load ~/.rover/env
diff --git a/.zshenv b/.zshenv index e456014..2571207 100644 --- a/.zshenv +++ b/.zshenv @@ -1,93 +1,98 @@ # to avoid overwritten PATH via /usr/libexec/path_helper # refs. https://github.com/Homebrew/homebrew-core/pull/32074#issuecomment-421381869 unsetopt GLOBAL_RCS # environment export LC_ALL=ja_JP.UTF-8 export DEVEL_PATH=$HOME/devel export EDITOR=vim export HOMEBREW_PATH=/usr/local export HOMEBREW_NO_AUTO_UPDATE=1 export HOMEBREW_NO_ENV_HINTS=1 export HOMEBREW_NO_INSECURE_REDIRECT=1 export HOMEBREW_UPDATE_REPORT_ONLY_INSTALLED=1 if [[ -f $HOMEBREW_PATH/bin/bat ]]; then export HOMEBREW_BAT=1 fi path=( $HOME/bin(N-/) $DEVEL_PATH/bin(N-/) $HOME/.mysqlenv/bin(N-/) $HOME/.mysqlenv/shims(N-/) $HOME/.pyenv/bin(N-/) $HOME/.pyenv/shims(N-/) $HOME/.rbenv/bin(N-/) $HOME/.rbenv/shims(N-/) $HOME/.plenv/bin(N-/) $HOME/.plenv/shims(N-/) $HOME/.ndenv/bin(N-/) $HOME/.ndenv/shims(N-/) $HOME/.cargo/bin(N-/) $GOPATH/bin(N-/) $HOME/.local/share/aquaproj-aqua/bin(N-/) $HOMEBREW_PATH/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/bin(N-/) $HOMEBREW_PATH/opt/perl/bin(N-/) $HOMEBREW_PATH/lib/ruby/gems/2.7.0/bin(N-/) $HOMEBREW_PATH/opt/ruby/bin(N-/) $HOMEBREW_PATH/opt/mysql-client/bin(N-/) $HOMEBREW_PATH/opt/[email protected]/bin(N-/) $HOMEBREW_PATH/opt/coreutils/libexec/gnubin(N-/) $HOMEBREW_PATH/bin(N-/) /usr/bin(N-/) /usr/sbin(N-/) /bin(N-/) /sbin(N-/) ) typeset -U manpath manpath=( $HOMEBREW_PATH/share/man(N-/) $HOMEBREW_PATH/opt/coreutils/libexec/gnuman(N-/) /usr/share/man(N-/) ) export PAGER=less export LESS='--LONG-PROMPT --RAW-CONTROL-CHARS' if whence code 2>&1 >/dev/null; then EDITOR='code --wait' fi if whence code 2>&1 >/dev/null; then EDITOR='code --wait' fi MACVIM_APP= local -a macvim_app_candidates=( /opt/homebrew-cask/Caskroom/macvim-kaoriya/*/MacVim.app(N-/) $HOMEBREW_PATH/opt/macvim/MacVim.app(N-/) $HOME/Applications/MacVim.app(N-/) /Applications/MacVim.app(N-/) ) if (( $#macvim_app_candidates > 0 )); then MACVIM_APP="$macvim_app_candidates[1]" fi export MACVIM_APP if [[ -x /usr/libexec/java_home ]] && /usr/libexec/java_home 2>&1 >/dev/null; then export JAVA_HOME="$(/usr/libexec/java_home -v 1.8)" fi RUBY_CONFIGURE_OPTS="" openssl_dir="$HOMEBREW_PATH/opt/[email protected]" if [[ -d "$openssl_dir" ]]; then RUBY_CONFIGURE_OPTS="${RUBY_CONFIGURE_OPTS} --with-openssl-dir=${openssl_dir}" fi readline_dir="$HOMEBREW_PATH/opt/readline" if [[ -d "$readline_dir" ]]; then RUBY_CONFIGURE_OPTS="${RUBY_CONFIGURE_OPTS} --with-readline-dir=${readline_dir}" fi export RUBY_CONFIGURE_OPTS + +rover_env="$HOME/.rover/env" +if [[ -f "$rover_env" ]]; then + . $rover_env +fi
aereal/dotfiles
8db17ed7bb27d0e36a780e7236c5f96ad6815f6c
fix(zsh): fix path order
diff --git a/.zshenv b/.zshenv index 43bdef9..e456014 100644 --- a/.zshenv +++ b/.zshenv @@ -1,93 +1,93 @@ # to avoid overwritten PATH via /usr/libexec/path_helper # refs. https://github.com/Homebrew/homebrew-core/pull/32074#issuecomment-421381869 unsetopt GLOBAL_RCS # environment export LC_ALL=ja_JP.UTF-8 export DEVEL_PATH=$HOME/devel export EDITOR=vim export HOMEBREW_PATH=/usr/local export HOMEBREW_NO_AUTO_UPDATE=1 export HOMEBREW_NO_ENV_HINTS=1 export HOMEBREW_NO_INSECURE_REDIRECT=1 export HOMEBREW_UPDATE_REPORT_ONLY_INSTALLED=1 if [[ -f $HOMEBREW_PATH/bin/bat ]]; then export HOMEBREW_BAT=1 fi path=( $HOME/bin(N-/) $DEVEL_PATH/bin(N-/) $HOME/.mysqlenv/bin(N-/) $HOME/.mysqlenv/shims(N-/) $HOME/.pyenv/bin(N-/) $HOME/.pyenv/shims(N-/) $HOME/.rbenv/bin(N-/) $HOME/.rbenv/shims(N-/) $HOME/.plenv/bin(N-/) $HOME/.plenv/shims(N-/) $HOME/.ndenv/bin(N-/) $HOME/.ndenv/shims(N-/) $HOME/.cargo/bin(N-/) $GOPATH/bin(N-/) + $HOME/.local/share/aquaproj-aqua/bin(N-/) $HOMEBREW_PATH/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/bin(N-/) $HOMEBREW_PATH/opt/perl/bin(N-/) - $HOMEBREW_PATH/opt/node@14/bin(N-/) $HOMEBREW_PATH/lib/ruby/gems/2.7.0/bin(N-/) $HOMEBREW_PATH/opt/ruby/bin(N-/) - $HOMEBREW_PATH/opt/[email protected]/bin(N-/) $HOMEBREW_PATH/opt/mysql-client/bin(N-/) + $HOMEBREW_PATH/opt/[email protected]/bin(N-/) $HOMEBREW_PATH/opt/coreutils/libexec/gnubin(N-/) $HOMEBREW_PATH/bin(N-/) /usr/bin(N-/) /usr/sbin(N-/) /bin(N-/) /sbin(N-/) ) typeset -U manpath manpath=( $HOMEBREW_PATH/share/man(N-/) $HOMEBREW_PATH/opt/coreutils/libexec/gnuman(N-/) /usr/share/man(N-/) ) export PAGER=less export LESS='--LONG-PROMPT --RAW-CONTROL-CHARS' if whence code 2>&1 >/dev/null; then EDITOR='code --wait' fi if whence code 2>&1 >/dev/null; then EDITOR='code --wait' fi MACVIM_APP= local -a macvim_app_candidates=( /opt/homebrew-cask/Caskroom/macvim-kaoriya/*/MacVim.app(N-/) $HOMEBREW_PATH/opt/macvim/MacVim.app(N-/) $HOME/Applications/MacVim.app(N-/) /Applications/MacVim.app(N-/) ) if (( $#macvim_app_candidates > 0 )); then MACVIM_APP="$macvim_app_candidates[1]" fi export MACVIM_APP if [[ -x /usr/libexec/java_home ]] && /usr/libexec/java_home 2>&1 >/dev/null; then export JAVA_HOME="$(/usr/libexec/java_home -v 1.8)" fi RUBY_CONFIGURE_OPTS="" openssl_dir="$HOMEBREW_PATH/opt/[email protected]" if [[ -d "$openssl_dir" ]]; then RUBY_CONFIGURE_OPTS="${RUBY_CONFIGURE_OPTS} --with-openssl-dir=${openssl_dir}" fi readline_dir="$HOMEBREW_PATH/opt/readline" if [[ -d "$readline_dir" ]]; then RUBY_CONFIGURE_OPTS="${RUBY_CONFIGURE_OPTS} --with-readline-dir=${readline_dir}" fi export RUBY_CONFIGURE_OPTS
aereal/dotfiles
09881c796abe09eaa5a7817bf96ec98c8403384e
fix(zsh): remove GOPATH
diff --git a/.zshenv b/.zshenv index 7eafcfe..43bdef9 100644 --- a/.zshenv +++ b/.zshenv @@ -1,94 +1,93 @@ # to avoid overwritten PATH via /usr/libexec/path_helper # refs. https://github.com/Homebrew/homebrew-core/pull/32074#issuecomment-421381869 unsetopt GLOBAL_RCS # environment export LC_ALL=ja_JP.UTF-8 export DEVEL_PATH=$HOME/devel -export GOPATH=$DEVEL_PATH export EDITOR=vim export HOMEBREW_PATH=/usr/local export HOMEBREW_NO_AUTO_UPDATE=1 export HOMEBREW_NO_ENV_HINTS=1 export HOMEBREW_NO_INSECURE_REDIRECT=1 export HOMEBREW_UPDATE_REPORT_ONLY_INSTALLED=1 if [[ -f $HOMEBREW_PATH/bin/bat ]]; then export HOMEBREW_BAT=1 fi path=( $HOME/bin(N-/) $DEVEL_PATH/bin(N-/) $HOME/.mysqlenv/bin(N-/) $HOME/.mysqlenv/shims(N-/) $HOME/.pyenv/bin(N-/) $HOME/.pyenv/shims(N-/) $HOME/.rbenv/bin(N-/) $HOME/.rbenv/shims(N-/) $HOME/.plenv/bin(N-/) $HOME/.plenv/shims(N-/) $HOME/.ndenv/bin(N-/) $HOME/.ndenv/shims(N-/) $HOME/.cargo/bin(N-/) $GOPATH/bin(N-/) $HOMEBREW_PATH/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/bin(N-/) $HOMEBREW_PATH/opt/perl/bin(N-/) $HOMEBREW_PATH/opt/node@14/bin(N-/) $HOMEBREW_PATH/lib/ruby/gems/2.7.0/bin(N-/) $HOMEBREW_PATH/opt/ruby/bin(N-/) $HOMEBREW_PATH/opt/[email protected]/bin(N-/) $HOMEBREW_PATH/opt/mysql-client/bin(N-/) $HOMEBREW_PATH/opt/coreutils/libexec/gnubin(N-/) $HOMEBREW_PATH/bin(N-/) /usr/bin(N-/) /usr/sbin(N-/) /bin(N-/) /sbin(N-/) ) typeset -U manpath manpath=( $HOMEBREW_PATH/share/man(N-/) $HOMEBREW_PATH/opt/coreutils/libexec/gnuman(N-/) /usr/share/man(N-/) ) export PAGER=less export LESS='--LONG-PROMPT --RAW-CONTROL-CHARS' if whence code 2>&1 >/dev/null; then EDITOR='code --wait' fi if whence code 2>&1 >/dev/null; then EDITOR='code --wait' fi MACVIM_APP= local -a macvim_app_candidates=( /opt/homebrew-cask/Caskroom/macvim-kaoriya/*/MacVim.app(N-/) $HOMEBREW_PATH/opt/macvim/MacVim.app(N-/) $HOME/Applications/MacVim.app(N-/) /Applications/MacVim.app(N-/) ) if (( $#macvim_app_candidates > 0 )); then MACVIM_APP="$macvim_app_candidates[1]" fi export MACVIM_APP if [[ -x /usr/libexec/java_home ]] && /usr/libexec/java_home 2>&1 >/dev/null; then export JAVA_HOME="$(/usr/libexec/java_home -v 1.8)" fi RUBY_CONFIGURE_OPTS="" openssl_dir="$HOMEBREW_PATH/opt/[email protected]" if [[ -d "$openssl_dir" ]]; then RUBY_CONFIGURE_OPTS="${RUBY_CONFIGURE_OPTS} --with-openssl-dir=${openssl_dir}" fi readline_dir="$HOMEBREW_PATH/opt/readline" if [[ -d "$readline_dir" ]]; then RUBY_CONFIGURE_OPTS="${RUBY_CONFIGURE_OPTS} --with-readline-dir=${readline_dir}" fi export RUBY_CONFIGURE_OPTS
aereal/dotfiles
526618017d60cc8f45efe79fea9f35bc78239c6a
fix(git): enable autoSetupRemote
diff --git a/.gitconfig b/.gitconfig index b79334a..58ff696 100644 --- a/.gitconfig +++ b/.gitconfig @@ -1,111 +1,112 @@ [user] email = [email protected] name = aereal [gui] encoding = utf-8 [github] user = aereal [alias] abort-rebase = rebase --abort branch-name = name-rev --name-only ci = commit -v co = checkout continue-rebase = rebase --continue cp = cherry-pick df = diff ds = diff --staged fdf = diff --function-context fetch-pulls = fetch origin +refs/pull/*:refs/remotes/pull/* fix = commit --amend gr = grep interactive-rebase = rebase --interactive network = log --graph --all --decorate --oneline onelog = log --oneline squashed-merge = merge --squash st = status --branch --short --untracked-files=normal --ignore-submodules=dirty ls = ls-files delete-branch = branch -d current-branch = symbolic-ref --short HEAD curret-remote-branch = rev-parse --abbrev-ref --symbolic-full-name @{u} hard-revert-merge-commit = reset --hard ORIG_HEAD medetai = !git rev-list HEAD | rg -P '(.)\\1\\1' pr = pull-request recently-added = log --grep \"Revert\" --invert-grep --diff-filter=A --format=\"\" --name-only [color] branch = true diff = true grep = true interactive = true pager = true status = true [color "branch"] current = green reverse local = green remote = yellow [color "status"] changed = green untracked = cyan updated = yellow [i18n] commitencoding= utf-8 [core] quotepath = false whitespace = cr-at-eol pager = $PAGER precomposeunicode = true excludesfile = ~/.global.gitignore [push] default = simple + autoSetupRemote = true [branch] autosetuprebase = always [grep] lineNumber = true patternType = perl [rebase] stat = true [diff "gzip"] textconv = gzcat [log] date = iso [merge] stat = true [interactive] singlekey = true [ghq] root = /Users/aereal/devel/src [diff] algorithm = histogram [include] path = ~/.secret.gitconfig [advice] statusHints = false [pager] log = git-diff-highlight | less show = git-diff-highlight | less diff = git-diff-highlight | less grep = false [url "[email protected]:"] pushInsteadOf = https://github.com/ pushInsteadOf = git://github.com/ [pull] rebase = true [init] defaultBranch = main
aereal/dotfiles
c599f7fde591d9c243c5dab5d8d70e2e9bfea874
fix(zsh): configure Homebrew environment variables
diff --git a/.zshenv b/.zshenv index 58bd654..7eafcfe 100644 --- a/.zshenv +++ b/.zshenv @@ -1,86 +1,94 @@ # to avoid overwritten PATH via /usr/libexec/path_helper # refs. https://github.com/Homebrew/homebrew-core/pull/32074#issuecomment-421381869 unsetopt GLOBAL_RCS # environment export LC_ALL=ja_JP.UTF-8 -export HOMEBREW_PATH=/usr/local export DEVEL_PATH=$HOME/devel export GOPATH=$DEVEL_PATH export EDITOR=vim +export HOMEBREW_PATH=/usr/local +export HOMEBREW_NO_AUTO_UPDATE=1 +export HOMEBREW_NO_ENV_HINTS=1 +export HOMEBREW_NO_INSECURE_REDIRECT=1 +export HOMEBREW_UPDATE_REPORT_ONLY_INSTALLED=1 + +if [[ -f $HOMEBREW_PATH/bin/bat ]]; then + export HOMEBREW_BAT=1 +fi path=( $HOME/bin(N-/) $DEVEL_PATH/bin(N-/) $HOME/.mysqlenv/bin(N-/) $HOME/.mysqlenv/shims(N-/) $HOME/.pyenv/bin(N-/) $HOME/.pyenv/shims(N-/) $HOME/.rbenv/bin(N-/) $HOME/.rbenv/shims(N-/) $HOME/.plenv/bin(N-/) $HOME/.plenv/shims(N-/) $HOME/.ndenv/bin(N-/) $HOME/.ndenv/shims(N-/) $HOME/.cargo/bin(N-/) $GOPATH/bin(N-/) $HOMEBREW_PATH/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/bin(N-/) $HOMEBREW_PATH/opt/perl/bin(N-/) $HOMEBREW_PATH/opt/node@14/bin(N-/) $HOMEBREW_PATH/lib/ruby/gems/2.7.0/bin(N-/) $HOMEBREW_PATH/opt/ruby/bin(N-/) $HOMEBREW_PATH/opt/[email protected]/bin(N-/) $HOMEBREW_PATH/opt/mysql-client/bin(N-/) $HOMEBREW_PATH/opt/coreutils/libexec/gnubin(N-/) $HOMEBREW_PATH/bin(N-/) /usr/bin(N-/) /usr/sbin(N-/) /bin(N-/) /sbin(N-/) ) typeset -U manpath manpath=( $HOMEBREW_PATH/share/man(N-/) $HOMEBREW_PATH/opt/coreutils/libexec/gnuman(N-/) /usr/share/man(N-/) ) export PAGER=less export LESS='--LONG-PROMPT --RAW-CONTROL-CHARS' if whence code 2>&1 >/dev/null; then EDITOR='code --wait' fi if whence code 2>&1 >/dev/null; then EDITOR='code --wait' fi MACVIM_APP= local -a macvim_app_candidates=( /opt/homebrew-cask/Caskroom/macvim-kaoriya/*/MacVim.app(N-/) $HOMEBREW_PATH/opt/macvim/MacVim.app(N-/) $HOME/Applications/MacVim.app(N-/) /Applications/MacVim.app(N-/) ) if (( $#macvim_app_candidates > 0 )); then MACVIM_APP="$macvim_app_candidates[1]" fi export MACVIM_APP if [[ -x /usr/libexec/java_home ]] && /usr/libexec/java_home 2>&1 >/dev/null; then export JAVA_HOME="$(/usr/libexec/java_home -v 1.8)" fi RUBY_CONFIGURE_OPTS="" openssl_dir="$HOMEBREW_PATH/opt/[email protected]" if [[ -d "$openssl_dir" ]]; then RUBY_CONFIGURE_OPTS="${RUBY_CONFIGURE_OPTS} --with-openssl-dir=${openssl_dir}" fi readline_dir="$HOMEBREW_PATH/opt/readline" if [[ -d "$readline_dir" ]]; then RUBY_CONFIGURE_OPTS="${RUBY_CONFIGURE_OPTS} --with-readline-dir=${readline_dir}" fi export RUBY_CONFIGURE_OPTS
aereal/dotfiles
7c4c08f9f8073c56233f71e52425fe12c189535b
fix(zsh): avoid to update window name also in VSCode terminal
diff --git a/.zshrc b/.zshrc index f299351..6e15d44 100644 --- a/.zshrc +++ b/.zshrc @@ -1,365 +1,365 @@ bindkey -v # function load path {{{ typeset -Ua fpath fpath=( $HOME/.zsh.d/functions(N-/) $HOMEBREW_PATH/share/zsh-completions(N-/) $HOMEBREW_PATH/share/zsh/site-functions(N-/) $HOMEBREW_PATH/share/zsh/functions(N-/) $HOMEBREW_PATH/opt/docker-completion/share/zsh/site-functions(N-/) $HOMEBREW_PATH/opt/docker-compose-completion/share/zsh/site-functions(N-/) $fpath ) # }}} # fundamental options {{{ export REPORTTIME=1 setopt extended_glob # }}} # history {{{ HISTFILE=$HOME/.zsh_history HISTSIZE=10000000 SAVEHIST=$HISTSIZE set \ extended_history \ hist_ignore_dups \ hist_ignore_space \ inc_append_history \ share_history \ no_flow_control \ hist_save_no_dups \ hist_ignore_all_dups autoload history-search-end zle -N history-beginning-search-backward-end history-search-end zle -N history-beginning-search-forward-end history-search-end bindkey -v "^N" history-beginning-search-forward-end bindkey -v "^P" history-beginning-search-backward-end bindkey -v "^R" history-incremental-pattern-search-backward bindkey -v "^S" history-incremental-pattern-search-forward # }}} # color {{{ autoload -Uz colors; colors [[ -f "$HOME/.dircolors" ]] && source "$HOME/.dircolors" # }}} # completion {{{ zmodload -i zsh/complist autoload -U compinit && compinit -C setopt \ complete_in_word \ glob_complete \ hist_expand \ no_beep \ numeric_glob_sort # Format {{{ zstyle ':completion:*' format '%F{magenta}-- %d --%f' zstyle ':completion:*' group-name '' zstyle ':completion:*:options' description yes zstyle ':completion:*:options' auto-description '%d' zstyle ':completion:*:corrections' format ' %F{yellow}-- %d (errors: %e) --%f' zstyle ':completion:*:descriptions' format ' %F{magenta}-- %d --%f' zstyle ':completion:*:messages' format ' %F{blue}-- %d --%f' zstyle ':completion:*:warnings' format ' %F{red}-- no matches found --%f' zstyle ':completion:*:default' list-prompt '%S%M matches%s' # Show selected candidate zstyle ':completion:*:default' menu select=2 zstyle ':completion:*:default' list-colors "${(s.:.)LS_COLORS}" # Fuzzy match zstyle ':completion:*' matcher-list 'm:{a-z}={A-Z} r:|[._-]=*' zstyle ':completion:*' completer _oldlist _complete _match _ignored _approximate _prefix # sudo zstyle ':completion:sudo:*' environ PATH="$SUDO_PATH:$PATH" # Directory candidates order zstyle ':completion:*:cd:*' tag-order local-directories path-directories # Ignore current directory from directory candidates zstyle ':completion:*' ignore-parents parent pwd # Process candidates zstyle ':completion:*:*:*:*:processes' command 'ps -u $USER -o pid,user,comm -w' zstyle ':completion:*:*:kill:*:processes' list-colors '=(#b) #([0-9]#) ([0-9a-z-]#)*=01;36=0=01' zstyle ':completion:*:*:kill:*' menu yes select zstyle ':completion:*:*:kill:*' force-list always zstyle ':completion:*:*:kill:*' insert-ids single # Show man candidates with section zstyle ':completion:*:manuals' separate-sections true # }}} # key mapping {{{ bindkey -M menuselect 'h' vi-backward-char bindkey -M menuselect 'l' vi-forward-char bindkey -M menuselect 'j' vi-down-line-or-history bindkey -M menuselect 'k' vi-up-line-or-history # }}} # }}} # url-quote-magic {{{ autoload -Uz url-quote-magic zle -N self-insert url-quote-magic # }}} # expand backslash to tilde {{{ # Originally from: https://github.com/cho45/dotfiles/blob/64ea90d17aaf6c46a2cb090f2e12a6e3d7df6034/.zshrc#L245 expand-to-home-or-complete() { # {{{ if [ "$LBUFFER" = "" -o "$LBUFFER[-1]" = " " ]; then LBUFFER+="~/" else zle self-insert fi } # }}} zle -N expand-to-home-or-complete bindkey -v "\\" expand-to-home-or-complete # }}} # ghq {{{ __widget_cd_repo() { local selected_repo=$( ghq list | peco ) if [[ -n "$selected_repo" ]]; then BUFFER="pushd $(ghq root)/${selected_repo}" zle accept-line fi zle -R -c } zle -N __widget_cd_repo bindkey -v "^]^G" __widget_cd_repo # }}} # git {{{ __widget_git_recent_branches() { local selected_branch=$( \ git for-each-ref --sort=-committerdate --format="%(refname) %(committerdate:relative)" -- refs/heads \ | sed -E 's/refs\/heads\///' \ | peco --query "$LBUFFER" \ | cut -f1 \ ) if [[ -n "$selected_branch" ]]; then BUFFER="git checkout ${selected_branch}" zle accept-line fi zle -R -c } zle -N __widget_git_recent_branches bindkey -v "^]gr" __widget_git_recent_branches # }}} # tmux: split window with vim-like key mappings {{{ # vertical split {{{ tmux_vsplit() { BUFFER="tmux split-window -d -p 50 -h '$BUFFER'" # TODO: escape zle accept-line } zle -N tmux_vsplit bindkey -v "^Wv" tmux_vsplit # }}} # horizontal split {{{ tmux_split() { BUFFER="tmux split-window -d -p 50 -v '$BUFFER'" # TODO: escape zle accept-line } zle -N tmux_split bindkey -v "^Ws" tmux_split # }}} # }}} # alias {{{ alias :q=exit if whence exa >/dev/null 2>&1; then alias l='exa -aF' alias ls='exa -aF' alias ll='exa -alF' else if whence gls >/dev/null; then alias l='gls --color=auto -AF' alias ls='gls --color=auto -AF' alias ll='gls --color=auto -AFl' else alias l='ls -GAF' alias ls='ls -GAF' alias ll='ls -GAFl' fi fi whence hub >/dev/null 2>&1 && alias git=hub # }}} # abbrev {{{ setopt extended_glob typeset -A abbreviations abbreviations=( 'Ig' '| rg' 'It' '| tail' 'Ij' '| jq' 'DC' 'docker-compose' ) magic-abbrev-expand() { local MATCH LBUFFER=${LBUFFER%%(#m)[-_a-zA-Z0-9]#} LBUFFER+=${abbreviations[$MATCH]:-$MATCH} zle self-insert } no-magic-abbrev-expand() { LBUFFER+=' ' } zle -N magic-abbrev-expand zle -N no-magic-abbrev-expand bindkey -v " " magic-abbrev-expand bindkey -v "^x " no-magic-abbrev-expand # }}} # prompt {{{ setopt \ prompt_subst \ prompt_percent \ transient_rprompt autoload -U promptinit && promptinit autoload -Uz vcs_info zstyle ':vcs_info:*' max-exports 4 zstyle ':vcs_info:(git|svn):*' formats '%R' '%S' '%b' '%s' zstyle ':vcs_info:(git|svn):*' actionformats '%R' '%S' '%b|%a' '%s' zstyle ':vcs_info:*' formats '%R' '%S' '%s:%b' '%s' zstyle ':vcs_info:*' actionformats '%R' '%S' '%s:%b|%a' '%s' __configure_prompt() { local ok_yuno="%F{yellow}✘╹◡╹✘%f" local bad_yuno="%F{red}✘>﹏<✘%f" local command_line="[%D{%Y-%m-%d} %*] %(?.${ok_yuno}.${bad_yuno}) < " psvar=() STY= LANG=en_US.UTF-8 vcs_info repos=`print -nD "$vcs_info_msg_0_"` if [[ -n "$vcs_info_msg_1_" ]]; then vcs="$vcs_info_msg_3_" else vcs='' fi [[ -n "$repos" ]] && psvar[2]="$repos" [[ -n "$vcs_info_msg_1_" ]] && psvar[3]="$vcs_info_msg_1_" [[ -n "$vcs_info_msg_2_" ]] && psvar[1]="$vcs_info_msg_2_" local psdirs='[%F{yellow}%3(v|%32<..<%3v%<<|%60<..<%~%<<)%f]' local psvcs='%3(v|[%25<\<<%F{yellow}%2v%f@%F{blue}%1v%f%<<]|)' local git_is_dirty git_local_changes git_upstream_changes if git rev-parse --is-inside-work-tree &>/dev/null; then command git diff --no-ext-diff --quiet --exit-code || git_is_dirty='%F{yellow}*%f' local git_upstream_status=$(command git rev-list --left-right --count ...@{u} 2>/dev/null) git_upstream_status=(${(ps:\t:)git_upstream_status}) local left=${git_upstream_status[1]} right=${git_upstream_status[2]} (( ${left:-0} > 0 )) && git_local_changes='%F{green}⇡%f' (( ${right:-0} > 0 )) && git_upstream_changes='%F{red}⇣%f' fi export PROMPT="${command_line}" export RPROMPT="${psdirs}${git_is_dirty}${git_local_changes}${git_upstream_changes}${psvcs}" } autoload -Uz add-zsh-hooks add-zsh-hook precmd __configure_prompt # }}} # Show anyenv version {{{ notify_llenv_version() { for llenv in rbenv plenv ndenv pyenv; do llenv_root="${HOME}/.${llenv}" # XXX if whence $llenv >/dev/null && [[ "$(${llenv} version-origin)" != "$llenv_root/version" ]]; then echo "$fg[yellow]${llenv} changed version: $(${llenv} version-name)$reset_color" fi done } add-zsh-hook chpwd notify_llenv_version # }}} # Update current window name {{{ update_window_title() { # {{{ emulate -L zsh local -a cmd cmd=(${(z)2}) case $cmd[1] in *=*) # PLENV_VERSION=5.14.2 plenv exec perl -v => plenv echo -n "k$cmd[2]:t\\" return ;; ls|gls|clear|pwd) echo -n "k$ZSH_NAME\\" return ;; sudo|cd) echo -n "k$cmd[1] $cmd[2]:t\\" return ;; *) echo -n "k$cmd[1]:t\\" return ;; esac local -A jt jt=(${(kv)jobtexts}) $cmd >>(read num rest cmd=(${(z)${(e):-\$jt$num}}) echo -n "k$cmd[1]:t\\") 2>/dev/null } # }}} -if [ "$TMUX" ]; then +if [ "$TMUX" ] && [ "$TERM_PROGRAM" != "vscode" ]; then add-zsh-hook preexec update_window_title fi # }}} # direnv {{{ if whence direnv >/dev/null; then eval "$(direnv hook zsh)" fi # }}} # syntax highlight {{{ if [[ -f "$HOMEBREW_PATH/share/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh" ]]; then source $HOMEBREW_PATH/share/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh fi # }}} # substring-search {{{ if [[ -f "$HOMEBREW_PATH/opt/zsh-history-substring-search/zsh-history-substring-search.zsh" ]]; then source $HOMEBREW_PATH/opt/zsh-history-substring-search/zsh-history-substring-search.zsh bindkey -M vicmd "k" history-substring-search-up bindkey -M vicmd "j" history-substring-search-down fi # }}} if ! ssh-add -l 2>/dev/null; then echo '---> Add SSH private key' ssh-add fi if [[ -f '/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/completion.zsh.inc' ]]; then source '/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/completion.zsh.inc' fi # tmux {{{ if whence tmux >/dev/null && [ -z "$TMUX" ] && [ "$TERM_PROGRAM" != "vscode" ]; then if $(tmux has-session 2>/dev/null); then tmux attach-session -t "${HOST%%.*}" else tmux new-session -s "${HOST%%.*}" fi fi # }}} # vim:set foldmethod=marker:
aereal/dotfiles
0448db5f5760c6b1534def6aee9d6ddf03ccebf5
fix(zsh): add MySQL Server 5.6 path
diff --git a/.zshenv b/.zshenv index 6f9d2b3..58bd654 100644 --- a/.zshenv +++ b/.zshenv @@ -1,85 +1,86 @@ # to avoid overwritten PATH via /usr/libexec/path_helper # refs. https://github.com/Homebrew/homebrew-core/pull/32074#issuecomment-421381869 unsetopt GLOBAL_RCS # environment export LC_ALL=ja_JP.UTF-8 export HOMEBREW_PATH=/usr/local export DEVEL_PATH=$HOME/devel export GOPATH=$DEVEL_PATH export EDITOR=vim path=( $HOME/bin(N-/) $DEVEL_PATH/bin(N-/) $HOME/.mysqlenv/bin(N-/) $HOME/.mysqlenv/shims(N-/) $HOME/.pyenv/bin(N-/) $HOME/.pyenv/shims(N-/) $HOME/.rbenv/bin(N-/) $HOME/.rbenv/shims(N-/) $HOME/.plenv/bin(N-/) $HOME/.plenv/shims(N-/) $HOME/.ndenv/bin(N-/) $HOME/.ndenv/shims(N-/) $HOME/.cargo/bin(N-/) $GOPATH/bin(N-/) $HOMEBREW_PATH/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/bin(N-/) $HOMEBREW_PATH/opt/perl/bin(N-/) $HOMEBREW_PATH/opt/node@14/bin(N-/) $HOMEBREW_PATH/lib/ruby/gems/2.7.0/bin(N-/) $HOMEBREW_PATH/opt/ruby/bin(N-/) + $HOMEBREW_PATH/opt/[email protected]/bin(N-/) $HOMEBREW_PATH/opt/mysql-client/bin(N-/) $HOMEBREW_PATH/opt/coreutils/libexec/gnubin(N-/) $HOMEBREW_PATH/bin(N-/) /usr/bin(N-/) /usr/sbin(N-/) /bin(N-/) /sbin(N-/) ) typeset -U manpath manpath=( $HOMEBREW_PATH/share/man(N-/) $HOMEBREW_PATH/opt/coreutils/libexec/gnuman(N-/) /usr/share/man(N-/) ) export PAGER=less export LESS='--LONG-PROMPT --RAW-CONTROL-CHARS' if whence code 2>&1 >/dev/null; then EDITOR='code --wait' fi if whence code 2>&1 >/dev/null; then EDITOR='code --wait' fi MACVIM_APP= local -a macvim_app_candidates=( /opt/homebrew-cask/Caskroom/macvim-kaoriya/*/MacVim.app(N-/) $HOMEBREW_PATH/opt/macvim/MacVim.app(N-/) $HOME/Applications/MacVim.app(N-/) /Applications/MacVim.app(N-/) ) if (( $#macvim_app_candidates > 0 )); then MACVIM_APP="$macvim_app_candidates[1]" fi export MACVIM_APP if [[ -x /usr/libexec/java_home ]] && /usr/libexec/java_home 2>&1 >/dev/null; then export JAVA_HOME="$(/usr/libexec/java_home -v 1.8)" fi RUBY_CONFIGURE_OPTS="" openssl_dir="$HOMEBREW_PATH/opt/[email protected]" if [[ -d "$openssl_dir" ]]; then RUBY_CONFIGURE_OPTS="${RUBY_CONFIGURE_OPTS} --with-openssl-dir=${openssl_dir}" fi readline_dir="$HOMEBREW_PATH/opt/readline" if [[ -d "$readline_dir" ]]; then RUBY_CONFIGURE_OPTS="${RUBY_CONFIGURE_OPTS} --with-readline-dir=${readline_dir}" fi export RUBY_CONFIGURE_OPTS
aereal/dotfiles
d032578cf04be791c19ee4f140c8882309c33c4c
fix(zsh): update Node LTS version to 14
diff --git a/.zshenv b/.zshenv index bb77a54..6f9d2b3 100644 --- a/.zshenv +++ b/.zshenv @@ -1,85 +1,85 @@ # to avoid overwritten PATH via /usr/libexec/path_helper # refs. https://github.com/Homebrew/homebrew-core/pull/32074#issuecomment-421381869 unsetopt GLOBAL_RCS # environment export LC_ALL=ja_JP.UTF-8 export HOMEBREW_PATH=/usr/local export DEVEL_PATH=$HOME/devel export GOPATH=$DEVEL_PATH export EDITOR=vim path=( $HOME/bin(N-/) $DEVEL_PATH/bin(N-/) $HOME/.mysqlenv/bin(N-/) $HOME/.mysqlenv/shims(N-/) $HOME/.pyenv/bin(N-/) $HOME/.pyenv/shims(N-/) $HOME/.rbenv/bin(N-/) $HOME/.rbenv/shims(N-/) $HOME/.plenv/bin(N-/) $HOME/.plenv/shims(N-/) $HOME/.ndenv/bin(N-/) $HOME/.ndenv/shims(N-/) $HOME/.cargo/bin(N-/) $GOPATH/bin(N-/) $HOMEBREW_PATH/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/bin(N-/) $HOMEBREW_PATH/opt/perl/bin(N-/) - $HOMEBREW_PATH/opt/node@12/bin(N-/) + $HOMEBREW_PATH/opt/node@14/bin(N-/) $HOMEBREW_PATH/lib/ruby/gems/2.7.0/bin(N-/) $HOMEBREW_PATH/opt/ruby/bin(N-/) $HOMEBREW_PATH/opt/mysql-client/bin(N-/) $HOMEBREW_PATH/opt/coreutils/libexec/gnubin(N-/) $HOMEBREW_PATH/bin(N-/) /usr/bin(N-/) /usr/sbin(N-/) /bin(N-/) /sbin(N-/) ) typeset -U manpath manpath=( $HOMEBREW_PATH/share/man(N-/) $HOMEBREW_PATH/opt/coreutils/libexec/gnuman(N-/) /usr/share/man(N-/) ) export PAGER=less export LESS='--LONG-PROMPT --RAW-CONTROL-CHARS' if whence code 2>&1 >/dev/null; then EDITOR='code --wait' fi if whence code 2>&1 >/dev/null; then EDITOR='code --wait' fi MACVIM_APP= local -a macvim_app_candidates=( /opt/homebrew-cask/Caskroom/macvim-kaoriya/*/MacVim.app(N-/) $HOMEBREW_PATH/opt/macvim/MacVim.app(N-/) $HOME/Applications/MacVim.app(N-/) /Applications/MacVim.app(N-/) ) if (( $#macvim_app_candidates > 0 )); then MACVIM_APP="$macvim_app_candidates[1]" fi export MACVIM_APP if [[ -x /usr/libexec/java_home ]] && /usr/libexec/java_home 2>&1 >/dev/null; then export JAVA_HOME="$(/usr/libexec/java_home -v 1.8)" fi RUBY_CONFIGURE_OPTS="" openssl_dir="$HOMEBREW_PATH/opt/[email protected]" if [[ -d "$openssl_dir" ]]; then RUBY_CONFIGURE_OPTS="${RUBY_CONFIGURE_OPTS} --with-openssl-dir=${openssl_dir}" fi readline_dir="$HOMEBREW_PATH/opt/readline" if [[ -d "$readline_dir" ]]; then RUBY_CONFIGURE_OPTS="${RUBY_CONFIGURE_OPTS} --with-readline-dir=${readline_dir}" fi export RUBY_CONFIGURE_OPTS
aereal/dotfiles
90907644503836526fd4ba24d6f7ac7b0e81cafb
fix(git): use main branch as default
diff --git a/.gitconfig b/.gitconfig index 34a29b3..b79334a 100644 --- a/.gitconfig +++ b/.gitconfig @@ -1,109 +1,111 @@ [user] email = [email protected] name = aereal [gui] encoding = utf-8 [github] user = aereal [alias] abort-rebase = rebase --abort branch-name = name-rev --name-only ci = commit -v co = checkout continue-rebase = rebase --continue cp = cherry-pick df = diff ds = diff --staged fdf = diff --function-context fetch-pulls = fetch origin +refs/pull/*:refs/remotes/pull/* fix = commit --amend gr = grep interactive-rebase = rebase --interactive network = log --graph --all --decorate --oneline onelog = log --oneline squashed-merge = merge --squash st = status --branch --short --untracked-files=normal --ignore-submodules=dirty ls = ls-files delete-branch = branch -d current-branch = symbolic-ref --short HEAD curret-remote-branch = rev-parse --abbrev-ref --symbolic-full-name @{u} hard-revert-merge-commit = reset --hard ORIG_HEAD medetai = !git rev-list HEAD | rg -P '(.)\\1\\1' pr = pull-request recently-added = log --grep \"Revert\" --invert-grep --diff-filter=A --format=\"\" --name-only [color] branch = true diff = true grep = true interactive = true pager = true status = true [color "branch"] current = green reverse local = green remote = yellow [color "status"] changed = green untracked = cyan updated = yellow [i18n] commitencoding= utf-8 [core] quotepath = false whitespace = cr-at-eol pager = $PAGER precomposeunicode = true excludesfile = ~/.global.gitignore [push] default = simple [branch] autosetuprebase = always [grep] lineNumber = true patternType = perl [rebase] stat = true [diff "gzip"] textconv = gzcat [log] date = iso [merge] stat = true [interactive] singlekey = true [ghq] root = /Users/aereal/devel/src [diff] algorithm = histogram [include] path = ~/.secret.gitconfig [advice] statusHints = false [pager] log = git-diff-highlight | less show = git-diff-highlight | less diff = git-diff-highlight | less grep = false [url "[email protected]:"] pushInsteadOf = https://github.com/ pushInsteadOf = git://github.com/ [pull] rebase = true +[init] + defaultBranch = main
aereal/dotfiles
a4d5f0038e64ed50f1f9139bafac2086fb0fb6de
fix(zsh): add gcloud path
diff --git a/.zshenv b/.zshenv index 2521501..bb77a54 100644 --- a/.zshenv +++ b/.zshenv @@ -1,84 +1,85 @@ # to avoid overwritten PATH via /usr/libexec/path_helper # refs. https://github.com/Homebrew/homebrew-core/pull/32074#issuecomment-421381869 unsetopt GLOBAL_RCS # environment export LC_ALL=ja_JP.UTF-8 export HOMEBREW_PATH=/usr/local export DEVEL_PATH=$HOME/devel export GOPATH=$DEVEL_PATH export EDITOR=vim path=( $HOME/bin(N-/) $DEVEL_PATH/bin(N-/) $HOME/.mysqlenv/bin(N-/) $HOME/.mysqlenv/shims(N-/) $HOME/.pyenv/bin(N-/) $HOME/.pyenv/shims(N-/) $HOME/.rbenv/bin(N-/) $HOME/.rbenv/shims(N-/) $HOME/.plenv/bin(N-/) $HOME/.plenv/shims(N-/) $HOME/.ndenv/bin(N-/) $HOME/.ndenv/shims(N-/) $HOME/.cargo/bin(N-/) $GOPATH/bin(N-/) + $HOMEBREW_PATH/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/bin(N-/) $HOMEBREW_PATH/opt/perl/bin(N-/) $HOMEBREW_PATH/opt/node@12/bin(N-/) $HOMEBREW_PATH/lib/ruby/gems/2.7.0/bin(N-/) $HOMEBREW_PATH/opt/ruby/bin(N-/) $HOMEBREW_PATH/opt/mysql-client/bin(N-/) $HOMEBREW_PATH/opt/coreutils/libexec/gnubin(N-/) $HOMEBREW_PATH/bin(N-/) /usr/bin(N-/) /usr/sbin(N-/) /bin(N-/) /sbin(N-/) ) typeset -U manpath manpath=( $HOMEBREW_PATH/share/man(N-/) $HOMEBREW_PATH/opt/coreutils/libexec/gnuman(N-/) /usr/share/man(N-/) ) export PAGER=less export LESS='--LONG-PROMPT --RAW-CONTROL-CHARS' if whence code 2>&1 >/dev/null; then EDITOR='code --wait' fi if whence code 2>&1 >/dev/null; then EDITOR='code --wait' fi MACVIM_APP= local -a macvim_app_candidates=( /opt/homebrew-cask/Caskroom/macvim-kaoriya/*/MacVim.app(N-/) $HOMEBREW_PATH/opt/macvim/MacVim.app(N-/) $HOME/Applications/MacVim.app(N-/) /Applications/MacVim.app(N-/) ) if (( $#macvim_app_candidates > 0 )); then MACVIM_APP="$macvim_app_candidates[1]" fi export MACVIM_APP if [[ -x /usr/libexec/java_home ]] && /usr/libexec/java_home 2>&1 >/dev/null; then export JAVA_HOME="$(/usr/libexec/java_home -v 1.8)" fi RUBY_CONFIGURE_OPTS="" openssl_dir="$HOMEBREW_PATH/opt/[email protected]" if [[ -d "$openssl_dir" ]]; then RUBY_CONFIGURE_OPTS="${RUBY_CONFIGURE_OPTS} --with-openssl-dir=${openssl_dir}" fi readline_dir="$HOMEBREW_PATH/opt/readline" if [[ -d "$readline_dir" ]]; then RUBY_CONFIGURE_OPTS="${RUBY_CONFIGURE_OPTS} --with-readline-dir=${readline_dir}" fi export RUBY_CONFIGURE_OPTS
aereal/dotfiles
7a505c7077134f0884006841e735730578481a22
feat(zsh): add cargo path
diff --git a/.zshenv b/.zshenv index 406b098..2521501 100644 --- a/.zshenv +++ b/.zshenv @@ -1,83 +1,84 @@ # to avoid overwritten PATH via /usr/libexec/path_helper # refs. https://github.com/Homebrew/homebrew-core/pull/32074#issuecomment-421381869 unsetopt GLOBAL_RCS # environment export LC_ALL=ja_JP.UTF-8 export HOMEBREW_PATH=/usr/local export DEVEL_PATH=$HOME/devel export GOPATH=$DEVEL_PATH export EDITOR=vim path=( $HOME/bin(N-/) $DEVEL_PATH/bin(N-/) $HOME/.mysqlenv/bin(N-/) $HOME/.mysqlenv/shims(N-/) $HOME/.pyenv/bin(N-/) $HOME/.pyenv/shims(N-/) $HOME/.rbenv/bin(N-/) $HOME/.rbenv/shims(N-/) $HOME/.plenv/bin(N-/) $HOME/.plenv/shims(N-/) $HOME/.ndenv/bin(N-/) $HOME/.ndenv/shims(N-/) + $HOME/.cargo/bin(N-/) $GOPATH/bin(N-/) $HOMEBREW_PATH/opt/perl/bin(N-/) $HOMEBREW_PATH/opt/node@12/bin(N-/) $HOMEBREW_PATH/lib/ruby/gems/2.7.0/bin(N-/) $HOMEBREW_PATH/opt/ruby/bin(N-/) $HOMEBREW_PATH/opt/mysql-client/bin(N-/) $HOMEBREW_PATH/opt/coreutils/libexec/gnubin(N-/) $HOMEBREW_PATH/bin(N-/) /usr/bin(N-/) /usr/sbin(N-/) /bin(N-/) /sbin(N-/) ) typeset -U manpath manpath=( $HOMEBREW_PATH/share/man(N-/) $HOMEBREW_PATH/opt/coreutils/libexec/gnuman(N-/) /usr/share/man(N-/) ) export PAGER=less export LESS='--LONG-PROMPT --RAW-CONTROL-CHARS' if whence code 2>&1 >/dev/null; then EDITOR='code --wait' fi if whence code 2>&1 >/dev/null; then EDITOR='code --wait' fi MACVIM_APP= local -a macvim_app_candidates=( /opt/homebrew-cask/Caskroom/macvim-kaoriya/*/MacVim.app(N-/) $HOMEBREW_PATH/opt/macvim/MacVim.app(N-/) $HOME/Applications/MacVim.app(N-/) /Applications/MacVim.app(N-/) ) if (( $#macvim_app_candidates > 0 )); then MACVIM_APP="$macvim_app_candidates[1]" fi export MACVIM_APP if [[ -x /usr/libexec/java_home ]] && /usr/libexec/java_home 2>&1 >/dev/null; then export JAVA_HOME="$(/usr/libexec/java_home -v 1.8)" fi RUBY_CONFIGURE_OPTS="" openssl_dir="$HOMEBREW_PATH/opt/[email protected]" if [[ -d "$openssl_dir" ]]; then RUBY_CONFIGURE_OPTS="${RUBY_CONFIGURE_OPTS} --with-openssl-dir=${openssl_dir}" fi readline_dir="$HOMEBREW_PATH/opt/readline" if [[ -d "$readline_dir" ]]; then RUBY_CONFIGURE_OPTS="${RUBY_CONFIGURE_OPTS} --with-readline-dir=${readline_dir}" fi export RUBY_CONFIGURE_OPTS
aereal/dotfiles
579bcf1d13a17dbcb1efe8f69fa6c70efc9ac6dc
fix(zsh): use VS Code as default editor
diff --git a/.zshenv b/.zshenv index e67dbc6..406b098 100644 --- a/.zshenv +++ b/.zshenv @@ -1,79 +1,83 @@ # to avoid overwritten PATH via /usr/libexec/path_helper # refs. https://github.com/Homebrew/homebrew-core/pull/32074#issuecomment-421381869 unsetopt GLOBAL_RCS # environment export LC_ALL=ja_JP.UTF-8 export HOMEBREW_PATH=/usr/local export DEVEL_PATH=$HOME/devel export GOPATH=$DEVEL_PATH export EDITOR=vim path=( $HOME/bin(N-/) $DEVEL_PATH/bin(N-/) $HOME/.mysqlenv/bin(N-/) $HOME/.mysqlenv/shims(N-/) $HOME/.pyenv/bin(N-/) $HOME/.pyenv/shims(N-/) $HOME/.rbenv/bin(N-/) $HOME/.rbenv/shims(N-/) $HOME/.plenv/bin(N-/) $HOME/.plenv/shims(N-/) $HOME/.ndenv/bin(N-/) $HOME/.ndenv/shims(N-/) $GOPATH/bin(N-/) $HOMEBREW_PATH/opt/perl/bin(N-/) $HOMEBREW_PATH/opt/node@12/bin(N-/) $HOMEBREW_PATH/lib/ruby/gems/2.7.0/bin(N-/) $HOMEBREW_PATH/opt/ruby/bin(N-/) $HOMEBREW_PATH/opt/mysql-client/bin(N-/) $HOMEBREW_PATH/opt/coreutils/libexec/gnubin(N-/) $HOMEBREW_PATH/bin(N-/) /usr/bin(N-/) /usr/sbin(N-/) /bin(N-/) /sbin(N-/) ) typeset -U manpath manpath=( $HOMEBREW_PATH/share/man(N-/) $HOMEBREW_PATH/opt/coreutils/libexec/gnuman(N-/) /usr/share/man(N-/) ) export PAGER=less export LESS='--LONG-PROMPT --RAW-CONTROL-CHARS' if whence code 2>&1 >/dev/null; then EDITOR='code --wait' fi +if whence code 2>&1 >/dev/null; then + EDITOR='code --wait' +fi + MACVIM_APP= local -a macvim_app_candidates=( /opt/homebrew-cask/Caskroom/macvim-kaoriya/*/MacVim.app(N-/) $HOMEBREW_PATH/opt/macvim/MacVim.app(N-/) $HOME/Applications/MacVim.app(N-/) /Applications/MacVim.app(N-/) ) if (( $#macvim_app_candidates > 0 )); then MACVIM_APP="$macvim_app_candidates[1]" fi export MACVIM_APP if [[ -x /usr/libexec/java_home ]] && /usr/libexec/java_home 2>&1 >/dev/null; then export JAVA_HOME="$(/usr/libexec/java_home -v 1.8)" fi RUBY_CONFIGURE_OPTS="" openssl_dir="$HOMEBREW_PATH/opt/[email protected]" if [[ -d "$openssl_dir" ]]; then RUBY_CONFIGURE_OPTS="${RUBY_CONFIGURE_OPTS} --with-openssl-dir=${openssl_dir}" fi readline_dir="$HOMEBREW_PATH/opt/readline" if [[ -d "$readline_dir" ]]; then RUBY_CONFIGURE_OPTS="${RUBY_CONFIGURE_OPTS} --with-readline-dir=${readline_dir}" fi export RUBY_CONFIGURE_OPTS
aereal/dotfiles
12957c92fc8cce6170d45ce461c989d34d481fbb
fix(zsh): update Ruby gems path
diff --git a/.zshenv b/.zshenv index 5b3fb55..e67dbc6 100644 --- a/.zshenv +++ b/.zshenv @@ -1,79 +1,79 @@ # to avoid overwritten PATH via /usr/libexec/path_helper # refs. https://github.com/Homebrew/homebrew-core/pull/32074#issuecomment-421381869 unsetopt GLOBAL_RCS # environment export LC_ALL=ja_JP.UTF-8 export HOMEBREW_PATH=/usr/local export DEVEL_PATH=$HOME/devel export GOPATH=$DEVEL_PATH export EDITOR=vim path=( $HOME/bin(N-/) $DEVEL_PATH/bin(N-/) $HOME/.mysqlenv/bin(N-/) $HOME/.mysqlenv/shims(N-/) $HOME/.pyenv/bin(N-/) $HOME/.pyenv/shims(N-/) $HOME/.rbenv/bin(N-/) $HOME/.rbenv/shims(N-/) $HOME/.plenv/bin(N-/) $HOME/.plenv/shims(N-/) $HOME/.ndenv/bin(N-/) $HOME/.ndenv/shims(N-/) $GOPATH/bin(N-/) $HOMEBREW_PATH/opt/perl/bin(N-/) $HOMEBREW_PATH/opt/node@12/bin(N-/) - $HOMEBREW_PATH/lib/ruby/gems/2.6.0/bin(N-/) + $HOMEBREW_PATH/lib/ruby/gems/2.7.0/bin(N-/) $HOMEBREW_PATH/opt/ruby/bin(N-/) $HOMEBREW_PATH/opt/mysql-client/bin(N-/) $HOMEBREW_PATH/opt/coreutils/libexec/gnubin(N-/) $HOMEBREW_PATH/bin(N-/) /usr/bin(N-/) /usr/sbin(N-/) /bin(N-/) /sbin(N-/) ) typeset -U manpath manpath=( $HOMEBREW_PATH/share/man(N-/) $HOMEBREW_PATH/opt/coreutils/libexec/gnuman(N-/) /usr/share/man(N-/) ) export PAGER=less export LESS='--LONG-PROMPT --RAW-CONTROL-CHARS' if whence code 2>&1 >/dev/null; then EDITOR='code --wait' fi MACVIM_APP= local -a macvim_app_candidates=( /opt/homebrew-cask/Caskroom/macvim-kaoriya/*/MacVim.app(N-/) $HOMEBREW_PATH/opt/macvim/MacVim.app(N-/) $HOME/Applications/MacVim.app(N-/) /Applications/MacVim.app(N-/) ) if (( $#macvim_app_candidates > 0 )); then MACVIM_APP="$macvim_app_candidates[1]" fi export MACVIM_APP if [[ -x /usr/libexec/java_home ]] && /usr/libexec/java_home 2>&1 >/dev/null; then export JAVA_HOME="$(/usr/libexec/java_home -v 1.8)" fi RUBY_CONFIGURE_OPTS="" openssl_dir="$HOMEBREW_PATH/opt/[email protected]" if [[ -d "$openssl_dir" ]]; then RUBY_CONFIGURE_OPTS="${RUBY_CONFIGURE_OPTS} --with-openssl-dir=${openssl_dir}" fi readline_dir="$HOMEBREW_PATH/opt/readline" if [[ -d "$readline_dir" ]]; then RUBY_CONFIGURE_OPTS="${RUBY_CONFIGURE_OPTS} --with-readline-dir=${readline_dir}" fi export RUBY_CONFIGURE_OPTS
aereal/dotfiles
43ec46333fde398b0f02b9bd4771e69a5b68159d
feat: add space hotkey
diff --git a/.hammerspoon/init.lua b/.hammerspoon/init.lua index fa38af7..6a1b05e 100644 --- a/.hammerspoon/init.lua +++ b/.hammerspoon/init.lua @@ -1,44 +1,48 @@ hs.window.animationDuration = 0 viKey = hs.hotkey.modal.new('ctrl-cmd', 'delete', 'hammerspoon') function viKey:entered() hs.alert'Enter' end function viKey:exited() hs.alert'Exit' end viKey:bind('', 'escape', function() viKey:exit() end) units = { enter = { x = 0.0, y = 0.0, w = 1.0, h = 1.0 }, + spc = { x = 0.125, y = 0.125, w = 0.75, h = 0.75 }, h = { x = 0.0, y = 0.0, w = 0.5, h = 1.0 }, l = { x = 0.5, y = 0.0, w = 0.5, h = 1.0 }, j = { x = 0.0, y = 0.5, w = 1.0, h = 0.5 }, k = { x = 0.0, y = 0.0, w = 1.0, h = 0.5 }, i = { x = 0.0, y = 0.0, w = 0.5, h = 0.5 }, o = { x = 0.5, y = 0.0, w = 0.5, h = 0.5 }, n = { x = 0.0, y = 0.5, w = 0.5, h = 0.5 }, m = { x = 0.5, y = 0.5, w = 0.5, h = 0.5 }, } viKey:bind('', 'return', function() hs.window.focusedWindow():move(units.enter) end) +viKey:bind('', 'space', function() + hs.window.focusedWindow():move(units.spc) +end) viKey:bind('', 'h', function() hs.window.focusedWindow():move(units.h) end) viKey:bind('', 'l', function() hs.window.focusedWindow():move(units.l) end) viKey:bind('', 'j', function() hs.window.focusedWindow():move(units.j) end) viKey:bind('', 'k', function() hs.window.focusedWindow():move(units.k) end) viKey:bind('', 'i', function() hs.window.focusedWindow():move(units.i) end) viKey:bind('', 'o', function() hs.window.focusedWindow():move(units.o) end) viKey:bind('', 'n', function() hs.window.focusedWindow():move(units.n) end) viKey:bind('', 'm', function() hs.window.focusedWindow():move(units.m) end)
aereal/dotfiles
8ca962dd0dfca4edddca4dca9843450684f413dc
feat: add .hammerspoon/init.lua
diff --git a/.hammerspoon/init.lua b/.hammerspoon/init.lua new file mode 100644 index 0000000..fa38af7 --- /dev/null +++ b/.hammerspoon/init.lua @@ -0,0 +1,44 @@ +hs.window.animationDuration = 0 + +viKey = hs.hotkey.modal.new('ctrl-cmd', 'delete', 'hammerspoon') +function viKey:entered() hs.alert'Enter' end +function viKey:exited() hs.alert'Exit' end +viKey:bind('', 'escape', function() viKey:exit() end) +units = { + enter = { x = 0.0, y = 0.0, w = 1.0, h = 1.0 }, + h = { x = 0.0, y = 0.0, w = 0.5, h = 1.0 }, + l = { x = 0.5, y = 0.0, w = 0.5, h = 1.0 }, + j = { x = 0.0, y = 0.5, w = 1.0, h = 0.5 }, + k = { x = 0.0, y = 0.0, w = 1.0, h = 0.5 }, + i = { x = 0.0, y = 0.0, w = 0.5, h = 0.5 }, + o = { x = 0.5, y = 0.0, w = 0.5, h = 0.5 }, + n = { x = 0.0, y = 0.5, w = 0.5, h = 0.5 }, + m = { x = 0.5, y = 0.5, w = 0.5, h = 0.5 }, +} +viKey:bind('', 'return', function() + hs.window.focusedWindow():move(units.enter) +end) +viKey:bind('', 'h', function() + hs.window.focusedWindow():move(units.h) +end) +viKey:bind('', 'l', function() + hs.window.focusedWindow():move(units.l) +end) +viKey:bind('', 'j', function() + hs.window.focusedWindow():move(units.j) +end) +viKey:bind('', 'k', function() + hs.window.focusedWindow():move(units.k) +end) +viKey:bind('', 'i', function() + hs.window.focusedWindow():move(units.i) +end) +viKey:bind('', 'o', function() + hs.window.focusedWindow():move(units.o) +end) +viKey:bind('', 'n', function() + hs.window.focusedWindow():move(units.n) +end) +viKey:bind('', 'm', function() + hs.window.focusedWindow():move(units.m) +end)
aereal/dotfiles
94b435cbd2148352e0f2dcbb2c87fb66fed5d9c3
zsh: prefers VSCode as primary editor
diff --git a/.zshenv b/.zshenv index 7fceac2..5b3fb55 100644 --- a/.zshenv +++ b/.zshenv @@ -1,79 +1,79 @@ # to avoid overwritten PATH via /usr/libexec/path_helper # refs. https://github.com/Homebrew/homebrew-core/pull/32074#issuecomment-421381869 unsetopt GLOBAL_RCS # environment export LC_ALL=ja_JP.UTF-8 export HOMEBREW_PATH=/usr/local export DEVEL_PATH=$HOME/devel export GOPATH=$DEVEL_PATH export EDITOR=vim path=( $HOME/bin(N-/) $DEVEL_PATH/bin(N-/) $HOME/.mysqlenv/bin(N-/) $HOME/.mysqlenv/shims(N-/) $HOME/.pyenv/bin(N-/) $HOME/.pyenv/shims(N-/) $HOME/.rbenv/bin(N-/) $HOME/.rbenv/shims(N-/) $HOME/.plenv/bin(N-/) $HOME/.plenv/shims(N-/) $HOME/.ndenv/bin(N-/) $HOME/.ndenv/shims(N-/) $GOPATH/bin(N-/) $HOMEBREW_PATH/opt/perl/bin(N-/) $HOMEBREW_PATH/opt/node@12/bin(N-/) $HOMEBREW_PATH/lib/ruby/gems/2.6.0/bin(N-/) $HOMEBREW_PATH/opt/ruby/bin(N-/) $HOMEBREW_PATH/opt/mysql-client/bin(N-/) $HOMEBREW_PATH/opt/coreutils/libexec/gnubin(N-/) $HOMEBREW_PATH/bin(N-/) /usr/bin(N-/) /usr/sbin(N-/) /bin(N-/) /sbin(N-/) ) typeset -U manpath manpath=( $HOMEBREW_PATH/share/man(N-/) $HOMEBREW_PATH/opt/coreutils/libexec/gnuman(N-/) /usr/share/man(N-/) ) export PAGER=less export LESS='--LONG-PROMPT --RAW-CONTROL-CHARS' -if whence nvim 2>&1 >/dev/null; then - EDITOR=nvim +if whence code 2>&1 >/dev/null; then + EDITOR='code --wait' fi MACVIM_APP= local -a macvim_app_candidates=( /opt/homebrew-cask/Caskroom/macvim-kaoriya/*/MacVim.app(N-/) $HOMEBREW_PATH/opt/macvim/MacVim.app(N-/) $HOME/Applications/MacVim.app(N-/) /Applications/MacVim.app(N-/) ) if (( $#macvim_app_candidates > 0 )); then MACVIM_APP="$macvim_app_candidates[1]" fi export MACVIM_APP if [[ -x /usr/libexec/java_home ]] && /usr/libexec/java_home 2>&1 >/dev/null; then export JAVA_HOME="$(/usr/libexec/java_home -v 1.8)" fi RUBY_CONFIGURE_OPTS="" openssl_dir="$HOMEBREW_PATH/opt/[email protected]" if [[ -d "$openssl_dir" ]]; then RUBY_CONFIGURE_OPTS="${RUBY_CONFIGURE_OPTS} --with-openssl-dir=${openssl_dir}" fi readline_dir="$HOMEBREW_PATH/opt/readline" if [[ -d "$readline_dir" ]]; then RUBY_CONFIGURE_OPTS="${RUBY_CONFIGURE_OPTS} --with-readline-dir=${readline_dir}" fi export RUBY_CONFIGURE_OPTS
aereal/dotfiles
2813ab3b27aa8871a4f932644c2be4f8846b4d8b
git: rebase true
diff --git a/.gitconfig b/.gitconfig index b70be81..34a29b3 100644 --- a/.gitconfig +++ b/.gitconfig @@ -1,107 +1,109 @@ [user] email = [email protected] name = aereal [gui] encoding = utf-8 [github] user = aereal [alias] abort-rebase = rebase --abort branch-name = name-rev --name-only ci = commit -v co = checkout continue-rebase = rebase --continue cp = cherry-pick df = diff ds = diff --staged fdf = diff --function-context fetch-pulls = fetch origin +refs/pull/*:refs/remotes/pull/* fix = commit --amend gr = grep interactive-rebase = rebase --interactive network = log --graph --all --decorate --oneline onelog = log --oneline squashed-merge = merge --squash st = status --branch --short --untracked-files=normal --ignore-submodules=dirty ls = ls-files delete-branch = branch -d current-branch = symbolic-ref --short HEAD curret-remote-branch = rev-parse --abbrev-ref --symbolic-full-name @{u} hard-revert-merge-commit = reset --hard ORIG_HEAD medetai = !git rev-list HEAD | rg -P '(.)\\1\\1' pr = pull-request recently-added = log --grep \"Revert\" --invert-grep --diff-filter=A --format=\"\" --name-only [color] branch = true diff = true grep = true interactive = true pager = true status = true [color "branch"] current = green reverse local = green remote = yellow [color "status"] changed = green untracked = cyan updated = yellow [i18n] commitencoding= utf-8 [core] quotepath = false whitespace = cr-at-eol pager = $PAGER precomposeunicode = true excludesfile = ~/.global.gitignore [push] default = simple [branch] autosetuprebase = always [grep] lineNumber = true patternType = perl [rebase] stat = true [diff "gzip"] textconv = gzcat [log] date = iso [merge] stat = true [interactive] singlekey = true [ghq] root = /Users/aereal/devel/src [diff] algorithm = histogram [include] path = ~/.secret.gitconfig [advice] statusHints = false [pager] log = git-diff-highlight | less show = git-diff-highlight | less diff = git-diff-highlight | less grep = false [url "[email protected]:"] pushInsteadOf = https://github.com/ pushInsteadOf = git://github.com/ +[pull] + rebase = true
aereal/dotfiles
f32ac60bfe5bd439ab3e3d804600e653c865bfa9
zsh: add RUBY_CONFIGURE_OPTS
diff --git a/.zshenv b/.zshenv index 35750a8..7fceac2 100644 --- a/.zshenv +++ b/.zshenv @@ -1,67 +1,79 @@ # to avoid overwritten PATH via /usr/libexec/path_helper # refs. https://github.com/Homebrew/homebrew-core/pull/32074#issuecomment-421381869 unsetopt GLOBAL_RCS # environment export LC_ALL=ja_JP.UTF-8 export HOMEBREW_PATH=/usr/local export DEVEL_PATH=$HOME/devel export GOPATH=$DEVEL_PATH export EDITOR=vim path=( $HOME/bin(N-/) $DEVEL_PATH/bin(N-/) $HOME/.mysqlenv/bin(N-/) $HOME/.mysqlenv/shims(N-/) $HOME/.pyenv/bin(N-/) $HOME/.pyenv/shims(N-/) $HOME/.rbenv/bin(N-/) $HOME/.rbenv/shims(N-/) $HOME/.plenv/bin(N-/) $HOME/.plenv/shims(N-/) $HOME/.ndenv/bin(N-/) $HOME/.ndenv/shims(N-/) $GOPATH/bin(N-/) $HOMEBREW_PATH/opt/perl/bin(N-/) $HOMEBREW_PATH/opt/node@12/bin(N-/) $HOMEBREW_PATH/lib/ruby/gems/2.6.0/bin(N-/) $HOMEBREW_PATH/opt/ruby/bin(N-/) $HOMEBREW_PATH/opt/mysql-client/bin(N-/) $HOMEBREW_PATH/opt/coreutils/libexec/gnubin(N-/) $HOMEBREW_PATH/bin(N-/) /usr/bin(N-/) /usr/sbin(N-/) /bin(N-/) /sbin(N-/) ) typeset -U manpath manpath=( $HOMEBREW_PATH/share/man(N-/) $HOMEBREW_PATH/opt/coreutils/libexec/gnuman(N-/) /usr/share/man(N-/) ) export PAGER=less export LESS='--LONG-PROMPT --RAW-CONTROL-CHARS' if whence nvim 2>&1 >/dev/null; then EDITOR=nvim fi MACVIM_APP= local -a macvim_app_candidates=( /opt/homebrew-cask/Caskroom/macvim-kaoriya/*/MacVim.app(N-/) $HOMEBREW_PATH/opt/macvim/MacVim.app(N-/) $HOME/Applications/MacVim.app(N-/) /Applications/MacVim.app(N-/) ) if (( $#macvim_app_candidates > 0 )); then MACVIM_APP="$macvim_app_candidates[1]" fi export MACVIM_APP if [[ -x /usr/libexec/java_home ]] && /usr/libexec/java_home 2>&1 >/dev/null; then export JAVA_HOME="$(/usr/libexec/java_home -v 1.8)" fi + +RUBY_CONFIGURE_OPTS="" +openssl_dir="$HOMEBREW_PATH/opt/[email protected]" +if [[ -d "$openssl_dir" ]]; then + RUBY_CONFIGURE_OPTS="${RUBY_CONFIGURE_OPTS} --with-openssl-dir=${openssl_dir}" +fi + +readline_dir="$HOMEBREW_PATH/opt/readline" +if [[ -d "$readline_dir" ]]; then + RUBY_CONFIGURE_OPTS="${RUBY_CONFIGURE_OPTS} --with-readline-dir=${readline_dir}" +fi +export RUBY_CONFIGURE_OPTS
aereal/dotfiles
5456b0503e9726262b78e9518d1aecae98fd2a07
use node LTS
diff --git a/.zshenv b/.zshenv index 0fb355a..35750a8 100644 --- a/.zshenv +++ b/.zshenv @@ -1,67 +1,67 @@ # to avoid overwritten PATH via /usr/libexec/path_helper # refs. https://github.com/Homebrew/homebrew-core/pull/32074#issuecomment-421381869 unsetopt GLOBAL_RCS # environment export LC_ALL=ja_JP.UTF-8 export HOMEBREW_PATH=/usr/local export DEVEL_PATH=$HOME/devel export GOPATH=$DEVEL_PATH export EDITOR=vim path=( $HOME/bin(N-/) $DEVEL_PATH/bin(N-/) $HOME/.mysqlenv/bin(N-/) $HOME/.mysqlenv/shims(N-/) $HOME/.pyenv/bin(N-/) $HOME/.pyenv/shims(N-/) $HOME/.rbenv/bin(N-/) $HOME/.rbenv/shims(N-/) $HOME/.plenv/bin(N-/) $HOME/.plenv/shims(N-/) $HOME/.ndenv/bin(N-/) $HOME/.ndenv/shims(N-/) $GOPATH/bin(N-/) $HOMEBREW_PATH/opt/perl/bin(N-/) - $HOMEBREW_PATH/opt/node@10/bin(N-/) + $HOMEBREW_PATH/opt/node@12/bin(N-/) $HOMEBREW_PATH/lib/ruby/gems/2.6.0/bin(N-/) $HOMEBREW_PATH/opt/ruby/bin(N-/) $HOMEBREW_PATH/opt/mysql-client/bin(N-/) $HOMEBREW_PATH/opt/coreutils/libexec/gnubin(N-/) $HOMEBREW_PATH/bin(N-/) /usr/bin(N-/) /usr/sbin(N-/) /bin(N-/) /sbin(N-/) ) typeset -U manpath manpath=( $HOMEBREW_PATH/share/man(N-/) $HOMEBREW_PATH/opt/coreutils/libexec/gnuman(N-/) /usr/share/man(N-/) ) export PAGER=less export LESS='--LONG-PROMPT --RAW-CONTROL-CHARS' if whence nvim 2>&1 >/dev/null; then EDITOR=nvim fi MACVIM_APP= local -a macvim_app_candidates=( /opt/homebrew-cask/Caskroom/macvim-kaoriya/*/MacVim.app(N-/) $HOMEBREW_PATH/opt/macvim/MacVim.app(N-/) $HOME/Applications/MacVim.app(N-/) /Applications/MacVim.app(N-/) ) if (( $#macvim_app_candidates > 0 )); then MACVIM_APP="$macvim_app_candidates[1]" fi export MACVIM_APP if [[ -x /usr/libexec/java_home ]] && /usr/libexec/java_home 2>&1 >/dev/null; then export JAVA_HOME="$(/usr/libexec/java_home -v 1.8)" fi
aereal/dotfiles
8de9afe0427b597edcce90151a11c90411cd9184
vim: fix source name
diff --git a/.vim/rc/plugins/denite.added.vim b/.vim/rc/plugins/denite.added.vim index 7216b72..a491961 100644 --- a/.vim/rc/plugins/denite.added.vim +++ b/.vim/rc/plugins/denite.added.vim @@ -1,14 +1,14 @@ nnoremap <SID>[denite] <Nop> nmap gj <SID>[denite] nmap <SID>[denite]p <SID>(project-files) nmap <SID>[denite]f <SID>(files) nmap <SID>[denite]F <SID>(files-from-buffer) nmap <SID>[denite][ <SID>(outline) nmap <SID>[denite]b <SID>(buffers) -nnoremap <silent> <SID>(project-files) :<C-u>Denite file_rec -buffer-name=files -source-names=hide<CR> +nnoremap <silent> <SID>(project-files) :<C-u>Denite file/rec -buffer-name=files -source-names=hide<CR> nnoremap <silent> <SID>(files) :<C-u>DeniteProjectDir file file:new -buffer-name=files -source-names=hide<CR> nnoremap <silent> <SID>(files-from-buffer) :<C-u>DeniteBufferDir file file:new -buffer-name=files -source-names=hide<CR> nnoremap <silent> <SID>(buffers) :<C-u>Denite buffer<CR> nnoremap <silent> <SID>(outline) :<C-u>Denite outline<CR>
aereal/dotfiles
6f15a2c082ff14e7ba0ba79906fd5881342335f1
zsh: add timestamp
diff --git a/.zshrc b/.zshrc index 321a3e8..f299351 100644 --- a/.zshrc +++ b/.zshrc @@ -1,365 +1,365 @@ bindkey -v # function load path {{{ typeset -Ua fpath fpath=( $HOME/.zsh.d/functions(N-/) $HOMEBREW_PATH/share/zsh-completions(N-/) $HOMEBREW_PATH/share/zsh/site-functions(N-/) $HOMEBREW_PATH/share/zsh/functions(N-/) $HOMEBREW_PATH/opt/docker-completion/share/zsh/site-functions(N-/) $HOMEBREW_PATH/opt/docker-compose-completion/share/zsh/site-functions(N-/) $fpath ) # }}} # fundamental options {{{ export REPORTTIME=1 setopt extended_glob # }}} # history {{{ HISTFILE=$HOME/.zsh_history HISTSIZE=10000000 SAVEHIST=$HISTSIZE set \ extended_history \ hist_ignore_dups \ hist_ignore_space \ inc_append_history \ share_history \ no_flow_control \ hist_save_no_dups \ hist_ignore_all_dups autoload history-search-end zle -N history-beginning-search-backward-end history-search-end zle -N history-beginning-search-forward-end history-search-end bindkey -v "^N" history-beginning-search-forward-end bindkey -v "^P" history-beginning-search-backward-end bindkey -v "^R" history-incremental-pattern-search-backward bindkey -v "^S" history-incremental-pattern-search-forward # }}} # color {{{ autoload -Uz colors; colors [[ -f "$HOME/.dircolors" ]] && source "$HOME/.dircolors" # }}} # completion {{{ zmodload -i zsh/complist autoload -U compinit && compinit -C setopt \ complete_in_word \ glob_complete \ hist_expand \ no_beep \ numeric_glob_sort # Format {{{ zstyle ':completion:*' format '%F{magenta}-- %d --%f' zstyle ':completion:*' group-name '' zstyle ':completion:*:options' description yes zstyle ':completion:*:options' auto-description '%d' zstyle ':completion:*:corrections' format ' %F{yellow}-- %d (errors: %e) --%f' zstyle ':completion:*:descriptions' format ' %F{magenta}-- %d --%f' zstyle ':completion:*:messages' format ' %F{blue}-- %d --%f' zstyle ':completion:*:warnings' format ' %F{red}-- no matches found --%f' zstyle ':completion:*:default' list-prompt '%S%M matches%s' # Show selected candidate zstyle ':completion:*:default' menu select=2 zstyle ':completion:*:default' list-colors "${(s.:.)LS_COLORS}" # Fuzzy match zstyle ':completion:*' matcher-list 'm:{a-z}={A-Z} r:|[._-]=*' zstyle ':completion:*' completer _oldlist _complete _match _ignored _approximate _prefix # sudo zstyle ':completion:sudo:*' environ PATH="$SUDO_PATH:$PATH" # Directory candidates order zstyle ':completion:*:cd:*' tag-order local-directories path-directories # Ignore current directory from directory candidates zstyle ':completion:*' ignore-parents parent pwd # Process candidates zstyle ':completion:*:*:*:*:processes' command 'ps -u $USER -o pid,user,comm -w' zstyle ':completion:*:*:kill:*:processes' list-colors '=(#b) #([0-9]#) ([0-9a-z-]#)*=01;36=0=01' zstyle ':completion:*:*:kill:*' menu yes select zstyle ':completion:*:*:kill:*' force-list always zstyle ':completion:*:*:kill:*' insert-ids single # Show man candidates with section zstyle ':completion:*:manuals' separate-sections true # }}} # key mapping {{{ bindkey -M menuselect 'h' vi-backward-char bindkey -M menuselect 'l' vi-forward-char bindkey -M menuselect 'j' vi-down-line-or-history bindkey -M menuselect 'k' vi-up-line-or-history # }}} # }}} # url-quote-magic {{{ autoload -Uz url-quote-magic zle -N self-insert url-quote-magic # }}} # expand backslash to tilde {{{ # Originally from: https://github.com/cho45/dotfiles/blob/64ea90d17aaf6c46a2cb090f2e12a6e3d7df6034/.zshrc#L245 expand-to-home-or-complete() { # {{{ if [ "$LBUFFER" = "" -o "$LBUFFER[-1]" = " " ]; then LBUFFER+="~/" else zle self-insert fi } # }}} zle -N expand-to-home-or-complete bindkey -v "\\" expand-to-home-or-complete # }}} # ghq {{{ __widget_cd_repo() { local selected_repo=$( ghq list | peco ) if [[ -n "$selected_repo" ]]; then BUFFER="pushd $(ghq root)/${selected_repo}" zle accept-line fi zle -R -c } zle -N __widget_cd_repo bindkey -v "^]^G" __widget_cd_repo # }}} # git {{{ __widget_git_recent_branches() { local selected_branch=$( \ git for-each-ref --sort=-committerdate --format="%(refname) %(committerdate:relative)" -- refs/heads \ | sed -E 's/refs\/heads\///' \ | peco --query "$LBUFFER" \ | cut -f1 \ ) if [[ -n "$selected_branch" ]]; then BUFFER="git checkout ${selected_branch}" zle accept-line fi zle -R -c } zle -N __widget_git_recent_branches bindkey -v "^]gr" __widget_git_recent_branches # }}} # tmux: split window with vim-like key mappings {{{ # vertical split {{{ tmux_vsplit() { BUFFER="tmux split-window -d -p 50 -h '$BUFFER'" # TODO: escape zle accept-line } zle -N tmux_vsplit bindkey -v "^Wv" tmux_vsplit # }}} # horizontal split {{{ tmux_split() { BUFFER="tmux split-window -d -p 50 -v '$BUFFER'" # TODO: escape zle accept-line } zle -N tmux_split bindkey -v "^Ws" tmux_split # }}} # }}} # alias {{{ alias :q=exit if whence exa >/dev/null 2>&1; then alias l='exa -aF' alias ls='exa -aF' alias ll='exa -alF' else if whence gls >/dev/null; then alias l='gls --color=auto -AF' alias ls='gls --color=auto -AF' alias ll='gls --color=auto -AFl' else alias l='ls -GAF' alias ls='ls -GAF' alias ll='ls -GAFl' fi fi whence hub >/dev/null 2>&1 && alias git=hub # }}} # abbrev {{{ setopt extended_glob typeset -A abbreviations abbreviations=( 'Ig' '| rg' 'It' '| tail' 'Ij' '| jq' 'DC' 'docker-compose' ) magic-abbrev-expand() { local MATCH LBUFFER=${LBUFFER%%(#m)[-_a-zA-Z0-9]#} LBUFFER+=${abbreviations[$MATCH]:-$MATCH} zle self-insert } no-magic-abbrev-expand() { LBUFFER+=' ' } zle -N magic-abbrev-expand zle -N no-magic-abbrev-expand bindkey -v " " magic-abbrev-expand bindkey -v "^x " no-magic-abbrev-expand # }}} # prompt {{{ setopt \ prompt_subst \ prompt_percent \ transient_rprompt autoload -U promptinit && promptinit autoload -Uz vcs_info zstyle ':vcs_info:*' max-exports 4 zstyle ':vcs_info:(git|svn):*' formats '%R' '%S' '%b' '%s' zstyle ':vcs_info:(git|svn):*' actionformats '%R' '%S' '%b|%a' '%s' zstyle ':vcs_info:*' formats '%R' '%S' '%s:%b' '%s' zstyle ':vcs_info:*' actionformats '%R' '%S' '%s:%b|%a' '%s' __configure_prompt() { local ok_yuno="%F{yellow}✘╹◡╹✘%f" local bad_yuno="%F{red}✘>﹏<✘%f" - local command_line="%(?.${ok_yuno}.${bad_yuno}) < " + local command_line="[%D{%Y-%m-%d} %*] %(?.${ok_yuno}.${bad_yuno}) < " psvar=() STY= LANG=en_US.UTF-8 vcs_info repos=`print -nD "$vcs_info_msg_0_"` if [[ -n "$vcs_info_msg_1_" ]]; then vcs="$vcs_info_msg_3_" else vcs='' fi [[ -n "$repos" ]] && psvar[2]="$repos" [[ -n "$vcs_info_msg_1_" ]] && psvar[3]="$vcs_info_msg_1_" [[ -n "$vcs_info_msg_2_" ]] && psvar[1]="$vcs_info_msg_2_" local psdirs='[%F{yellow}%3(v|%32<..<%3v%<<|%60<..<%~%<<)%f]' local psvcs='%3(v|[%25<\<<%F{yellow}%2v%f@%F{blue}%1v%f%<<]|)' local git_is_dirty git_local_changes git_upstream_changes if git rev-parse --is-inside-work-tree &>/dev/null; then command git diff --no-ext-diff --quiet --exit-code || git_is_dirty='%F{yellow}*%f' local git_upstream_status=$(command git rev-list --left-right --count ...@{u} 2>/dev/null) git_upstream_status=(${(ps:\t:)git_upstream_status}) local left=${git_upstream_status[1]} right=${git_upstream_status[2]} (( ${left:-0} > 0 )) && git_local_changes='%F{green}⇡%f' (( ${right:-0} > 0 )) && git_upstream_changes='%F{red}⇣%f' fi export PROMPT="${command_line}" export RPROMPT="${psdirs}${git_is_dirty}${git_local_changes}${git_upstream_changes}${psvcs}" } autoload -Uz add-zsh-hooks add-zsh-hook precmd __configure_prompt # }}} # Show anyenv version {{{ notify_llenv_version() { for llenv in rbenv plenv ndenv pyenv; do llenv_root="${HOME}/.${llenv}" # XXX if whence $llenv >/dev/null && [[ "$(${llenv} version-origin)" != "$llenv_root/version" ]]; then echo "$fg[yellow]${llenv} changed version: $(${llenv} version-name)$reset_color" fi done } add-zsh-hook chpwd notify_llenv_version # }}} # Update current window name {{{ update_window_title() { # {{{ emulate -L zsh local -a cmd cmd=(${(z)2}) case $cmd[1] in *=*) # PLENV_VERSION=5.14.2 plenv exec perl -v => plenv echo -n "k$cmd[2]:t\\" return ;; ls|gls|clear|pwd) echo -n "k$ZSH_NAME\\" return ;; sudo|cd) echo -n "k$cmd[1] $cmd[2]:t\\" return ;; *) echo -n "k$cmd[1]:t\\" return ;; esac local -A jt jt=(${(kv)jobtexts}) $cmd >>(read num rest cmd=(${(z)${(e):-\$jt$num}}) echo -n "k$cmd[1]:t\\") 2>/dev/null } # }}} if [ "$TMUX" ]; then add-zsh-hook preexec update_window_title fi # }}} # direnv {{{ if whence direnv >/dev/null; then eval "$(direnv hook zsh)" fi # }}} # syntax highlight {{{ if [[ -f "$HOMEBREW_PATH/share/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh" ]]; then source $HOMEBREW_PATH/share/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh fi # }}} # substring-search {{{ if [[ -f "$HOMEBREW_PATH/opt/zsh-history-substring-search/zsh-history-substring-search.zsh" ]]; then source $HOMEBREW_PATH/opt/zsh-history-substring-search/zsh-history-substring-search.zsh bindkey -M vicmd "k" history-substring-search-up bindkey -M vicmd "j" history-substring-search-down fi # }}} if ! ssh-add -l 2>/dev/null; then echo '---> Add SSH private key' ssh-add fi if [[ -f '/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/completion.zsh.inc' ]]; then source '/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/completion.zsh.inc' fi # tmux {{{ if whence tmux >/dev/null && [ -z "$TMUX" ] && [ "$TERM_PROGRAM" != "vscode" ]; then if $(tmux has-session 2>/dev/null); then tmux attach-session -t "${HOST%%.*}" else tmux new-session -s "${HOST%%.*}" fi fi # }}} # vim:set foldmethod=marker:
aereal/dotfiles
f8d658c57300b2d01371186c114dc2b837f11ab0
zsh: check term program
diff --git a/.zshrc b/.zshrc index ffe4f1e..321a3e8 100644 --- a/.zshrc +++ b/.zshrc @@ -1,365 +1,365 @@ bindkey -v # function load path {{{ typeset -Ua fpath fpath=( $HOME/.zsh.d/functions(N-/) $HOMEBREW_PATH/share/zsh-completions(N-/) $HOMEBREW_PATH/share/zsh/site-functions(N-/) $HOMEBREW_PATH/share/zsh/functions(N-/) $HOMEBREW_PATH/opt/docker-completion/share/zsh/site-functions(N-/) $HOMEBREW_PATH/opt/docker-compose-completion/share/zsh/site-functions(N-/) $fpath ) # }}} # fundamental options {{{ export REPORTTIME=1 setopt extended_glob # }}} # history {{{ HISTFILE=$HOME/.zsh_history HISTSIZE=10000000 SAVEHIST=$HISTSIZE set \ extended_history \ hist_ignore_dups \ hist_ignore_space \ inc_append_history \ share_history \ no_flow_control \ hist_save_no_dups \ hist_ignore_all_dups autoload history-search-end zle -N history-beginning-search-backward-end history-search-end zle -N history-beginning-search-forward-end history-search-end bindkey -v "^N" history-beginning-search-forward-end bindkey -v "^P" history-beginning-search-backward-end bindkey -v "^R" history-incremental-pattern-search-backward bindkey -v "^S" history-incremental-pattern-search-forward # }}} # color {{{ autoload -Uz colors; colors [[ -f "$HOME/.dircolors" ]] && source "$HOME/.dircolors" # }}} # completion {{{ zmodload -i zsh/complist autoload -U compinit && compinit -C setopt \ complete_in_word \ glob_complete \ hist_expand \ no_beep \ numeric_glob_sort # Format {{{ zstyle ':completion:*' format '%F{magenta}-- %d --%f' zstyle ':completion:*' group-name '' zstyle ':completion:*:options' description yes zstyle ':completion:*:options' auto-description '%d' zstyle ':completion:*:corrections' format ' %F{yellow}-- %d (errors: %e) --%f' zstyle ':completion:*:descriptions' format ' %F{magenta}-- %d --%f' zstyle ':completion:*:messages' format ' %F{blue}-- %d --%f' zstyle ':completion:*:warnings' format ' %F{red}-- no matches found --%f' zstyle ':completion:*:default' list-prompt '%S%M matches%s' # Show selected candidate zstyle ':completion:*:default' menu select=2 zstyle ':completion:*:default' list-colors "${(s.:.)LS_COLORS}" # Fuzzy match zstyle ':completion:*' matcher-list 'm:{a-z}={A-Z} r:|[._-]=*' zstyle ':completion:*' completer _oldlist _complete _match _ignored _approximate _prefix # sudo zstyle ':completion:sudo:*' environ PATH="$SUDO_PATH:$PATH" # Directory candidates order zstyle ':completion:*:cd:*' tag-order local-directories path-directories # Ignore current directory from directory candidates zstyle ':completion:*' ignore-parents parent pwd # Process candidates zstyle ':completion:*:*:*:*:processes' command 'ps -u $USER -o pid,user,comm -w' zstyle ':completion:*:*:kill:*:processes' list-colors '=(#b) #([0-9]#) ([0-9a-z-]#)*=01;36=0=01' zstyle ':completion:*:*:kill:*' menu yes select zstyle ':completion:*:*:kill:*' force-list always zstyle ':completion:*:*:kill:*' insert-ids single # Show man candidates with section zstyle ':completion:*:manuals' separate-sections true # }}} # key mapping {{{ bindkey -M menuselect 'h' vi-backward-char bindkey -M menuselect 'l' vi-forward-char bindkey -M menuselect 'j' vi-down-line-or-history bindkey -M menuselect 'k' vi-up-line-or-history # }}} # }}} # url-quote-magic {{{ autoload -Uz url-quote-magic zle -N self-insert url-quote-magic # }}} # expand backslash to tilde {{{ # Originally from: https://github.com/cho45/dotfiles/blob/64ea90d17aaf6c46a2cb090f2e12a6e3d7df6034/.zshrc#L245 expand-to-home-or-complete() { # {{{ if [ "$LBUFFER" = "" -o "$LBUFFER[-1]" = " " ]; then LBUFFER+="~/" else zle self-insert fi } # }}} zle -N expand-to-home-or-complete bindkey -v "\\" expand-to-home-or-complete # }}} # ghq {{{ __widget_cd_repo() { local selected_repo=$( ghq list | peco ) if [[ -n "$selected_repo" ]]; then BUFFER="pushd $(ghq root)/${selected_repo}" zle accept-line fi zle -R -c } zle -N __widget_cd_repo bindkey -v "^]^G" __widget_cd_repo # }}} # git {{{ __widget_git_recent_branches() { local selected_branch=$( \ git for-each-ref --sort=-committerdate --format="%(refname) %(committerdate:relative)" -- refs/heads \ | sed -E 's/refs\/heads\///' \ | peco --query "$LBUFFER" \ | cut -f1 \ ) if [[ -n "$selected_branch" ]]; then BUFFER="git checkout ${selected_branch}" zle accept-line fi zle -R -c } zle -N __widget_git_recent_branches bindkey -v "^]gr" __widget_git_recent_branches # }}} # tmux: split window with vim-like key mappings {{{ # vertical split {{{ tmux_vsplit() { BUFFER="tmux split-window -d -p 50 -h '$BUFFER'" # TODO: escape zle accept-line } zle -N tmux_vsplit bindkey -v "^Wv" tmux_vsplit # }}} # horizontal split {{{ tmux_split() { BUFFER="tmux split-window -d -p 50 -v '$BUFFER'" # TODO: escape zle accept-line } zle -N tmux_split bindkey -v "^Ws" tmux_split # }}} # }}} # alias {{{ alias :q=exit if whence exa >/dev/null 2>&1; then alias l='exa -aF' alias ls='exa -aF' alias ll='exa -alF' else if whence gls >/dev/null; then alias l='gls --color=auto -AF' alias ls='gls --color=auto -AF' alias ll='gls --color=auto -AFl' else alias l='ls -GAF' alias ls='ls -GAF' alias ll='ls -GAFl' fi fi whence hub >/dev/null 2>&1 && alias git=hub # }}} # abbrev {{{ setopt extended_glob typeset -A abbreviations abbreviations=( 'Ig' '| rg' 'It' '| tail' 'Ij' '| jq' 'DC' 'docker-compose' ) magic-abbrev-expand() { local MATCH LBUFFER=${LBUFFER%%(#m)[-_a-zA-Z0-9]#} LBUFFER+=${abbreviations[$MATCH]:-$MATCH} zle self-insert } no-magic-abbrev-expand() { LBUFFER+=' ' } zle -N magic-abbrev-expand zle -N no-magic-abbrev-expand bindkey -v " " magic-abbrev-expand bindkey -v "^x " no-magic-abbrev-expand # }}} # prompt {{{ setopt \ prompt_subst \ prompt_percent \ transient_rprompt autoload -U promptinit && promptinit autoload -Uz vcs_info zstyle ':vcs_info:*' max-exports 4 zstyle ':vcs_info:(git|svn):*' formats '%R' '%S' '%b' '%s' zstyle ':vcs_info:(git|svn):*' actionformats '%R' '%S' '%b|%a' '%s' zstyle ':vcs_info:*' formats '%R' '%S' '%s:%b' '%s' zstyle ':vcs_info:*' actionformats '%R' '%S' '%s:%b|%a' '%s' __configure_prompt() { local ok_yuno="%F{yellow}✘╹◡╹✘%f" local bad_yuno="%F{red}✘>﹏<✘%f" local command_line="%(?.${ok_yuno}.${bad_yuno}) < " psvar=() STY= LANG=en_US.UTF-8 vcs_info repos=`print -nD "$vcs_info_msg_0_"` if [[ -n "$vcs_info_msg_1_" ]]; then vcs="$vcs_info_msg_3_" else vcs='' fi [[ -n "$repos" ]] && psvar[2]="$repos" [[ -n "$vcs_info_msg_1_" ]] && psvar[3]="$vcs_info_msg_1_" [[ -n "$vcs_info_msg_2_" ]] && psvar[1]="$vcs_info_msg_2_" local psdirs='[%F{yellow}%3(v|%32<..<%3v%<<|%60<..<%~%<<)%f]' local psvcs='%3(v|[%25<\<<%F{yellow}%2v%f@%F{blue}%1v%f%<<]|)' local git_is_dirty git_local_changes git_upstream_changes if git rev-parse --is-inside-work-tree &>/dev/null; then command git diff --no-ext-diff --quiet --exit-code || git_is_dirty='%F{yellow}*%f' local git_upstream_status=$(command git rev-list --left-right --count ...@{u} 2>/dev/null) git_upstream_status=(${(ps:\t:)git_upstream_status}) local left=${git_upstream_status[1]} right=${git_upstream_status[2]} (( ${left:-0} > 0 )) && git_local_changes='%F{green}⇡%f' (( ${right:-0} > 0 )) && git_upstream_changes='%F{red}⇣%f' fi export PROMPT="${command_line}" export RPROMPT="${psdirs}${git_is_dirty}${git_local_changes}${git_upstream_changes}${psvcs}" } autoload -Uz add-zsh-hooks add-zsh-hook precmd __configure_prompt # }}} # Show anyenv version {{{ notify_llenv_version() { for llenv in rbenv plenv ndenv pyenv; do llenv_root="${HOME}/.${llenv}" # XXX if whence $llenv >/dev/null && [[ "$(${llenv} version-origin)" != "$llenv_root/version" ]]; then echo "$fg[yellow]${llenv} changed version: $(${llenv} version-name)$reset_color" fi done } add-zsh-hook chpwd notify_llenv_version # }}} # Update current window name {{{ update_window_title() { # {{{ emulate -L zsh local -a cmd cmd=(${(z)2}) case $cmd[1] in *=*) # PLENV_VERSION=5.14.2 plenv exec perl -v => plenv echo -n "k$cmd[2]:t\\" return ;; ls|gls|clear|pwd) echo -n "k$ZSH_NAME\\" return ;; sudo|cd) echo -n "k$cmd[1] $cmd[2]:t\\" return ;; *) echo -n "k$cmd[1]:t\\" return ;; esac local -A jt jt=(${(kv)jobtexts}) $cmd >>(read num rest cmd=(${(z)${(e):-\$jt$num}}) echo -n "k$cmd[1]:t\\") 2>/dev/null } # }}} if [ "$TMUX" ]; then add-zsh-hook preexec update_window_title fi # }}} # direnv {{{ if whence direnv >/dev/null; then eval "$(direnv hook zsh)" fi # }}} # syntax highlight {{{ if [[ -f "$HOMEBREW_PATH/share/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh" ]]; then source $HOMEBREW_PATH/share/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh fi # }}} # substring-search {{{ if [[ -f "$HOMEBREW_PATH/opt/zsh-history-substring-search/zsh-history-substring-search.zsh" ]]; then source $HOMEBREW_PATH/opt/zsh-history-substring-search/zsh-history-substring-search.zsh bindkey -M vicmd "k" history-substring-search-up bindkey -M vicmd "j" history-substring-search-down fi # }}} if ! ssh-add -l 2>/dev/null; then echo '---> Add SSH private key' ssh-add fi if [[ -f '/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/completion.zsh.inc' ]]; then source '/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/completion.zsh.inc' fi # tmux {{{ -if whence tmux >/dev/null && [ -z "$TMUX" ]; then +if whence tmux >/dev/null && [ -z "$TMUX" ] && [ "$TERM_PROGRAM" != "vscode" ]; then if $(tmux has-session 2>/dev/null); then tmux attach-session -t "${HOST%%.*}" else tmux new-session -s "${HOST%%.*}" fi fi # }}} # vim:set foldmethod=marker:
aereal/dotfiles
dec73ff6d6e8dcf7184ade0a8b43111cb5e17924
zsh: unsetopt GLOBAL_RCS
diff --git a/.zshenv b/.zshenv index e419185..0fb355a 100644 --- a/.zshenv +++ b/.zshenv @@ -1,63 +1,67 @@ +# to avoid overwritten PATH via /usr/libexec/path_helper +# refs. https://github.com/Homebrew/homebrew-core/pull/32074#issuecomment-421381869 +unsetopt GLOBAL_RCS + # environment export LC_ALL=ja_JP.UTF-8 export HOMEBREW_PATH=/usr/local export DEVEL_PATH=$HOME/devel export GOPATH=$DEVEL_PATH export EDITOR=vim path=( $HOME/bin(N-/) $DEVEL_PATH/bin(N-/) $HOME/.mysqlenv/bin(N-/) $HOME/.mysqlenv/shims(N-/) $HOME/.pyenv/bin(N-/) $HOME/.pyenv/shims(N-/) $HOME/.rbenv/bin(N-/) $HOME/.rbenv/shims(N-/) $HOME/.plenv/bin(N-/) $HOME/.plenv/shims(N-/) $HOME/.ndenv/bin(N-/) $HOME/.ndenv/shims(N-/) $GOPATH/bin(N-/) $HOMEBREW_PATH/opt/perl/bin(N-/) $HOMEBREW_PATH/opt/node@10/bin(N-/) $HOMEBREW_PATH/lib/ruby/gems/2.6.0/bin(N-/) $HOMEBREW_PATH/opt/ruby/bin(N-/) $HOMEBREW_PATH/opt/mysql-client/bin(N-/) $HOMEBREW_PATH/opt/coreutils/libexec/gnubin(N-/) $HOMEBREW_PATH/bin(N-/) /usr/bin(N-/) /usr/sbin(N-/) /bin(N-/) /sbin(N-/) ) typeset -U manpath manpath=( $HOMEBREW_PATH/share/man(N-/) $HOMEBREW_PATH/opt/coreutils/libexec/gnuman(N-/) /usr/share/man(N-/) ) export PAGER=less export LESS='--LONG-PROMPT --RAW-CONTROL-CHARS' if whence nvim 2>&1 >/dev/null; then EDITOR=nvim fi MACVIM_APP= local -a macvim_app_candidates=( /opt/homebrew-cask/Caskroom/macvim-kaoriya/*/MacVim.app(N-/) $HOMEBREW_PATH/opt/macvim/MacVim.app(N-/) $HOME/Applications/MacVim.app(N-/) /Applications/MacVim.app(N-/) ) if (( $#macvim_app_candidates > 0 )); then MACVIM_APP="$macvim_app_candidates[1]" fi export MACVIM_APP if [[ -x /usr/libexec/java_home ]] && /usr/libexec/java_home 2>&1 >/dev/null; then export JAVA_HOME="$(/usr/libexec/java_home -v 1.8)" fi
aereal/dotfiles
cb1e29a5bf42e43107d02289c28685d96432d1e2
zsh: add perl path
diff --git a/.zshenv b/.zshenv index 49a3c57..e419185 100644 --- a/.zshenv +++ b/.zshenv @@ -1,62 +1,63 @@ # environment export LC_ALL=ja_JP.UTF-8 export HOMEBREW_PATH=/usr/local export DEVEL_PATH=$HOME/devel export GOPATH=$DEVEL_PATH export EDITOR=vim path=( $HOME/bin(N-/) $DEVEL_PATH/bin(N-/) $HOME/.mysqlenv/bin(N-/) $HOME/.mysqlenv/shims(N-/) $HOME/.pyenv/bin(N-/) $HOME/.pyenv/shims(N-/) $HOME/.rbenv/bin(N-/) $HOME/.rbenv/shims(N-/) $HOME/.plenv/bin(N-/) $HOME/.plenv/shims(N-/) $HOME/.ndenv/bin(N-/) $HOME/.ndenv/shims(N-/) $GOPATH/bin(N-/) + $HOMEBREW_PATH/opt/perl/bin(N-/) $HOMEBREW_PATH/opt/node@10/bin(N-/) $HOMEBREW_PATH/lib/ruby/gems/2.6.0/bin(N-/) $HOMEBREW_PATH/opt/ruby/bin(N-/) $HOMEBREW_PATH/opt/mysql-client/bin(N-/) $HOMEBREW_PATH/opt/coreutils/libexec/gnubin(N-/) $HOMEBREW_PATH/bin(N-/) /usr/bin(N-/) /usr/sbin(N-/) /bin(N-/) /sbin(N-/) ) typeset -U manpath manpath=( $HOMEBREW_PATH/share/man(N-/) $HOMEBREW_PATH/opt/coreutils/libexec/gnuman(N-/) /usr/share/man(N-/) ) export PAGER=less export LESS='--LONG-PROMPT --RAW-CONTROL-CHARS' if whence nvim 2>&1 >/dev/null; then EDITOR=nvim fi MACVIM_APP= local -a macvim_app_candidates=( /opt/homebrew-cask/Caskroom/macvim-kaoriya/*/MacVim.app(N-/) $HOMEBREW_PATH/opt/macvim/MacVim.app(N-/) $HOME/Applications/MacVim.app(N-/) /Applications/MacVim.app(N-/) ) if (( $#macvim_app_candidates > 0 )); then MACVIM_APP="$macvim_app_candidates[1]" fi export MACVIM_APP if [[ -x /usr/libexec/java_home ]] && /usr/libexec/java_home 2>&1 >/dev/null; then export JAVA_HOME="$(/usr/libexec/java_home -v 1.8)" fi
aereal/dotfiles
a918e02351b2bab0d20b1dbdc22c47b58dbf6800
zsh: JAVA_HOME
diff --git a/.zshenv b/.zshenv index bce8bac..49a3c57 100644 --- a/.zshenv +++ b/.zshenv @@ -1,58 +1,62 @@ # environment export LC_ALL=ja_JP.UTF-8 export HOMEBREW_PATH=/usr/local export DEVEL_PATH=$HOME/devel export GOPATH=$DEVEL_PATH export EDITOR=vim path=( $HOME/bin(N-/) $DEVEL_PATH/bin(N-/) $HOME/.mysqlenv/bin(N-/) $HOME/.mysqlenv/shims(N-/) $HOME/.pyenv/bin(N-/) $HOME/.pyenv/shims(N-/) $HOME/.rbenv/bin(N-/) $HOME/.rbenv/shims(N-/) $HOME/.plenv/bin(N-/) $HOME/.plenv/shims(N-/) $HOME/.ndenv/bin(N-/) $HOME/.ndenv/shims(N-/) $GOPATH/bin(N-/) $HOMEBREW_PATH/opt/node@10/bin(N-/) $HOMEBREW_PATH/lib/ruby/gems/2.6.0/bin(N-/) $HOMEBREW_PATH/opt/ruby/bin(N-/) $HOMEBREW_PATH/opt/mysql-client/bin(N-/) $HOMEBREW_PATH/opt/coreutils/libexec/gnubin(N-/) $HOMEBREW_PATH/bin(N-/) /usr/bin(N-/) /usr/sbin(N-/) /bin(N-/) /sbin(N-/) ) typeset -U manpath manpath=( $HOMEBREW_PATH/share/man(N-/) $HOMEBREW_PATH/opt/coreutils/libexec/gnuman(N-/) /usr/share/man(N-/) ) export PAGER=less export LESS='--LONG-PROMPT --RAW-CONTROL-CHARS' if whence nvim 2>&1 >/dev/null; then EDITOR=nvim fi MACVIM_APP= local -a macvim_app_candidates=( /opt/homebrew-cask/Caskroom/macvim-kaoriya/*/MacVim.app(N-/) $HOMEBREW_PATH/opt/macvim/MacVim.app(N-/) $HOME/Applications/MacVim.app(N-/) /Applications/MacVim.app(N-/) ) if (( $#macvim_app_candidates > 0 )); then MACVIM_APP="$macvim_app_candidates[1]" fi export MACVIM_APP + +if [[ -x /usr/libexec/java_home ]] && /usr/libexec/java_home 2>&1 >/dev/null; then + export JAVA_HOME="$(/usr/libexec/java_home -v 1.8)" +fi
aereal/dotfiles
3e81097cd69b4cce83b38fb90258f59b9d4a67c4
add google-cloud-sdk completion
diff --git a/.zshrc b/.zshrc index 6b4552d..ffe4f1e 100644 --- a/.zshrc +++ b/.zshrc @@ -1,360 +1,365 @@ bindkey -v # function load path {{{ typeset -Ua fpath fpath=( $HOME/.zsh.d/functions(N-/) $HOMEBREW_PATH/share/zsh-completions(N-/) $HOMEBREW_PATH/share/zsh/site-functions(N-/) $HOMEBREW_PATH/share/zsh/functions(N-/) $HOMEBREW_PATH/opt/docker-completion/share/zsh/site-functions(N-/) $HOMEBREW_PATH/opt/docker-compose-completion/share/zsh/site-functions(N-/) $fpath ) # }}} # fundamental options {{{ export REPORTTIME=1 setopt extended_glob # }}} # history {{{ HISTFILE=$HOME/.zsh_history HISTSIZE=10000000 SAVEHIST=$HISTSIZE set \ extended_history \ hist_ignore_dups \ hist_ignore_space \ inc_append_history \ share_history \ no_flow_control \ hist_save_no_dups \ hist_ignore_all_dups autoload history-search-end zle -N history-beginning-search-backward-end history-search-end zle -N history-beginning-search-forward-end history-search-end bindkey -v "^N" history-beginning-search-forward-end bindkey -v "^P" history-beginning-search-backward-end bindkey -v "^R" history-incremental-pattern-search-backward bindkey -v "^S" history-incremental-pattern-search-forward # }}} # color {{{ autoload -Uz colors; colors [[ -f "$HOME/.dircolors" ]] && source "$HOME/.dircolors" # }}} # completion {{{ zmodload -i zsh/complist autoload -U compinit && compinit -C setopt \ complete_in_word \ glob_complete \ hist_expand \ no_beep \ numeric_glob_sort # Format {{{ zstyle ':completion:*' format '%F{magenta}-- %d --%f' zstyle ':completion:*' group-name '' zstyle ':completion:*:options' description yes zstyle ':completion:*:options' auto-description '%d' zstyle ':completion:*:corrections' format ' %F{yellow}-- %d (errors: %e) --%f' zstyle ':completion:*:descriptions' format ' %F{magenta}-- %d --%f' zstyle ':completion:*:messages' format ' %F{blue}-- %d --%f' zstyle ':completion:*:warnings' format ' %F{red}-- no matches found --%f' zstyle ':completion:*:default' list-prompt '%S%M matches%s' # Show selected candidate zstyle ':completion:*:default' menu select=2 zstyle ':completion:*:default' list-colors "${(s.:.)LS_COLORS}" # Fuzzy match zstyle ':completion:*' matcher-list 'm:{a-z}={A-Z} r:|[._-]=*' zstyle ':completion:*' completer _oldlist _complete _match _ignored _approximate _prefix # sudo zstyle ':completion:sudo:*' environ PATH="$SUDO_PATH:$PATH" # Directory candidates order zstyle ':completion:*:cd:*' tag-order local-directories path-directories # Ignore current directory from directory candidates zstyle ':completion:*' ignore-parents parent pwd # Process candidates zstyle ':completion:*:*:*:*:processes' command 'ps -u $USER -o pid,user,comm -w' zstyle ':completion:*:*:kill:*:processes' list-colors '=(#b) #([0-9]#) ([0-9a-z-]#)*=01;36=0=01' zstyle ':completion:*:*:kill:*' menu yes select zstyle ':completion:*:*:kill:*' force-list always zstyle ':completion:*:*:kill:*' insert-ids single # Show man candidates with section zstyle ':completion:*:manuals' separate-sections true # }}} # key mapping {{{ bindkey -M menuselect 'h' vi-backward-char bindkey -M menuselect 'l' vi-forward-char bindkey -M menuselect 'j' vi-down-line-or-history bindkey -M menuselect 'k' vi-up-line-or-history # }}} # }}} # url-quote-magic {{{ autoload -Uz url-quote-magic zle -N self-insert url-quote-magic # }}} # expand backslash to tilde {{{ # Originally from: https://github.com/cho45/dotfiles/blob/64ea90d17aaf6c46a2cb090f2e12a6e3d7df6034/.zshrc#L245 expand-to-home-or-complete() { # {{{ if [ "$LBUFFER" = "" -o "$LBUFFER[-1]" = " " ]; then LBUFFER+="~/" else zle self-insert fi } # }}} zle -N expand-to-home-or-complete bindkey -v "\\" expand-to-home-or-complete # }}} # ghq {{{ __widget_cd_repo() { local selected_repo=$( ghq list | peco ) if [[ -n "$selected_repo" ]]; then BUFFER="pushd $(ghq root)/${selected_repo}" zle accept-line fi zle -R -c } zle -N __widget_cd_repo bindkey -v "^]^G" __widget_cd_repo # }}} # git {{{ __widget_git_recent_branches() { local selected_branch=$( \ git for-each-ref --sort=-committerdate --format="%(refname) %(committerdate:relative)" -- refs/heads \ | sed -E 's/refs\/heads\///' \ | peco --query "$LBUFFER" \ | cut -f1 \ ) if [[ -n "$selected_branch" ]]; then BUFFER="git checkout ${selected_branch}" zle accept-line fi zle -R -c } zle -N __widget_git_recent_branches bindkey -v "^]gr" __widget_git_recent_branches # }}} # tmux: split window with vim-like key mappings {{{ # vertical split {{{ tmux_vsplit() { BUFFER="tmux split-window -d -p 50 -h '$BUFFER'" # TODO: escape zle accept-line } zle -N tmux_vsplit bindkey -v "^Wv" tmux_vsplit # }}} # horizontal split {{{ tmux_split() { BUFFER="tmux split-window -d -p 50 -v '$BUFFER'" # TODO: escape zle accept-line } zle -N tmux_split bindkey -v "^Ws" tmux_split # }}} # }}} # alias {{{ alias :q=exit if whence exa >/dev/null 2>&1; then alias l='exa -aF' alias ls='exa -aF' alias ll='exa -alF' else if whence gls >/dev/null; then alias l='gls --color=auto -AF' alias ls='gls --color=auto -AF' alias ll='gls --color=auto -AFl' else alias l='ls -GAF' alias ls='ls -GAF' alias ll='ls -GAFl' fi fi whence hub >/dev/null 2>&1 && alias git=hub # }}} # abbrev {{{ setopt extended_glob typeset -A abbreviations abbreviations=( 'Ig' '| rg' 'It' '| tail' 'Ij' '| jq' 'DC' 'docker-compose' ) magic-abbrev-expand() { local MATCH LBUFFER=${LBUFFER%%(#m)[-_a-zA-Z0-9]#} LBUFFER+=${abbreviations[$MATCH]:-$MATCH} zle self-insert } no-magic-abbrev-expand() { LBUFFER+=' ' } zle -N magic-abbrev-expand zle -N no-magic-abbrev-expand bindkey -v " " magic-abbrev-expand bindkey -v "^x " no-magic-abbrev-expand # }}} # prompt {{{ setopt \ prompt_subst \ prompt_percent \ transient_rprompt autoload -U promptinit && promptinit autoload -Uz vcs_info zstyle ':vcs_info:*' max-exports 4 zstyle ':vcs_info:(git|svn):*' formats '%R' '%S' '%b' '%s' zstyle ':vcs_info:(git|svn):*' actionformats '%R' '%S' '%b|%a' '%s' zstyle ':vcs_info:*' formats '%R' '%S' '%s:%b' '%s' zstyle ':vcs_info:*' actionformats '%R' '%S' '%s:%b|%a' '%s' __configure_prompt() { local ok_yuno="%F{yellow}✘╹◡╹✘%f" local bad_yuno="%F{red}✘>﹏<✘%f" local command_line="%(?.${ok_yuno}.${bad_yuno}) < " psvar=() STY= LANG=en_US.UTF-8 vcs_info repos=`print -nD "$vcs_info_msg_0_"` if [[ -n "$vcs_info_msg_1_" ]]; then vcs="$vcs_info_msg_3_" else vcs='' fi [[ -n "$repos" ]] && psvar[2]="$repos" [[ -n "$vcs_info_msg_1_" ]] && psvar[3]="$vcs_info_msg_1_" [[ -n "$vcs_info_msg_2_" ]] && psvar[1]="$vcs_info_msg_2_" local psdirs='[%F{yellow}%3(v|%32<..<%3v%<<|%60<..<%~%<<)%f]' local psvcs='%3(v|[%25<\<<%F{yellow}%2v%f@%F{blue}%1v%f%<<]|)' local git_is_dirty git_local_changes git_upstream_changes if git rev-parse --is-inside-work-tree &>/dev/null; then command git diff --no-ext-diff --quiet --exit-code || git_is_dirty='%F{yellow}*%f' local git_upstream_status=$(command git rev-list --left-right --count ...@{u} 2>/dev/null) git_upstream_status=(${(ps:\t:)git_upstream_status}) local left=${git_upstream_status[1]} right=${git_upstream_status[2]} (( ${left:-0} > 0 )) && git_local_changes='%F{green}⇡%f' (( ${right:-0} > 0 )) && git_upstream_changes='%F{red}⇣%f' fi export PROMPT="${command_line}" export RPROMPT="${psdirs}${git_is_dirty}${git_local_changes}${git_upstream_changes}${psvcs}" } autoload -Uz add-zsh-hooks add-zsh-hook precmd __configure_prompt # }}} # Show anyenv version {{{ notify_llenv_version() { for llenv in rbenv plenv ndenv pyenv; do llenv_root="${HOME}/.${llenv}" # XXX if whence $llenv >/dev/null && [[ "$(${llenv} version-origin)" != "$llenv_root/version" ]]; then echo "$fg[yellow]${llenv} changed version: $(${llenv} version-name)$reset_color" fi done } add-zsh-hook chpwd notify_llenv_version # }}} # Update current window name {{{ update_window_title() { # {{{ emulate -L zsh local -a cmd cmd=(${(z)2}) case $cmd[1] in *=*) # PLENV_VERSION=5.14.2 plenv exec perl -v => plenv echo -n "k$cmd[2]:t\\" return ;; ls|gls|clear|pwd) echo -n "k$ZSH_NAME\\" return ;; sudo|cd) echo -n "k$cmd[1] $cmd[2]:t\\" return ;; *) echo -n "k$cmd[1]:t\\" return ;; esac local -A jt jt=(${(kv)jobtexts}) $cmd >>(read num rest cmd=(${(z)${(e):-\$jt$num}}) echo -n "k$cmd[1]:t\\") 2>/dev/null } # }}} if [ "$TMUX" ]; then add-zsh-hook preexec update_window_title fi # }}} # direnv {{{ if whence direnv >/dev/null; then eval "$(direnv hook zsh)" fi # }}} # syntax highlight {{{ if [[ -f "$HOMEBREW_PATH/share/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh" ]]; then source $HOMEBREW_PATH/share/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh fi # }}} # substring-search {{{ if [[ -f "$HOMEBREW_PATH/opt/zsh-history-substring-search/zsh-history-substring-search.zsh" ]]; then source $HOMEBREW_PATH/opt/zsh-history-substring-search/zsh-history-substring-search.zsh bindkey -M vicmd "k" history-substring-search-up bindkey -M vicmd "j" history-substring-search-down fi # }}} if ! ssh-add -l 2>/dev/null; then echo '---> Add SSH private key' ssh-add fi + +if [[ -f '/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/completion.zsh.inc' ]]; then + source '/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/completion.zsh.inc' +fi + # tmux {{{ if whence tmux >/dev/null && [ -z "$TMUX" ]; then if $(tmux has-session 2>/dev/null); then tmux attach-session -t "${HOST%%.*}" else tmux new-session -s "${HOST%%.*}" fi fi # }}} # vim:set foldmethod=marker:
aereal/dotfiles
4370f71d566fc0249794f7647ad8cfeca6d5094b
zsh: prefer node 10
diff --git a/.zshenv b/.zshenv index 9f7b995..bce8bac 100644 --- a/.zshenv +++ b/.zshenv @@ -1,57 +1,58 @@ # environment export LC_ALL=ja_JP.UTF-8 export HOMEBREW_PATH=/usr/local export DEVEL_PATH=$HOME/devel export GOPATH=$DEVEL_PATH export EDITOR=vim path=( $HOME/bin(N-/) $DEVEL_PATH/bin(N-/) $HOME/.mysqlenv/bin(N-/) $HOME/.mysqlenv/shims(N-/) $HOME/.pyenv/bin(N-/) $HOME/.pyenv/shims(N-/) $HOME/.rbenv/bin(N-/) $HOME/.rbenv/shims(N-/) $HOME/.plenv/bin(N-/) $HOME/.plenv/shims(N-/) $HOME/.ndenv/bin(N-/) $HOME/.ndenv/shims(N-/) $GOPATH/bin(N-/) + $HOMEBREW_PATH/opt/node@10/bin(N-/) $HOMEBREW_PATH/lib/ruby/gems/2.6.0/bin(N-/) $HOMEBREW_PATH/opt/ruby/bin(N-/) $HOMEBREW_PATH/opt/mysql-client/bin(N-/) $HOMEBREW_PATH/opt/coreutils/libexec/gnubin(N-/) $HOMEBREW_PATH/bin(N-/) /usr/bin(N-/) /usr/sbin(N-/) /bin(N-/) /sbin(N-/) ) typeset -U manpath manpath=( $HOMEBREW_PATH/share/man(N-/) $HOMEBREW_PATH/opt/coreutils/libexec/gnuman(N-/) /usr/share/man(N-/) ) export PAGER=less export LESS='--LONG-PROMPT --RAW-CONTROL-CHARS' if whence nvim 2>&1 >/dev/null; then EDITOR=nvim fi MACVIM_APP= local -a macvim_app_candidates=( /opt/homebrew-cask/Caskroom/macvim-kaoriya/*/MacVim.app(N-/) $HOMEBREW_PATH/opt/macvim/MacVim.app(N-/) $HOME/Applications/MacVim.app(N-/) /Applications/MacVim.app(N-/) ) if (( $#macvim_app_candidates > 0 )); then MACVIM_APP="$macvim_app_candidates[1]" fi export MACVIM_APP
aereal/dotfiles
9d96ac0dca5b6aafd162ee337f38dd8465b6a3d0
zsh: specify LC_ALL
diff --git a/.zshenv b/.zshenv index ae24b00..9f7b995 100644 --- a/.zshenv +++ b/.zshenv @@ -1,56 +1,57 @@ # environment +export LC_ALL=ja_JP.UTF-8 export HOMEBREW_PATH=/usr/local export DEVEL_PATH=$HOME/devel export GOPATH=$DEVEL_PATH export EDITOR=vim path=( $HOME/bin(N-/) $DEVEL_PATH/bin(N-/) $HOME/.mysqlenv/bin(N-/) $HOME/.mysqlenv/shims(N-/) $HOME/.pyenv/bin(N-/) $HOME/.pyenv/shims(N-/) $HOME/.rbenv/bin(N-/) $HOME/.rbenv/shims(N-/) $HOME/.plenv/bin(N-/) $HOME/.plenv/shims(N-/) $HOME/.ndenv/bin(N-/) $HOME/.ndenv/shims(N-/) $GOPATH/bin(N-/) $HOMEBREW_PATH/lib/ruby/gems/2.6.0/bin(N-/) $HOMEBREW_PATH/opt/ruby/bin(N-/) $HOMEBREW_PATH/opt/mysql-client/bin(N-/) $HOMEBREW_PATH/opt/coreutils/libexec/gnubin(N-/) $HOMEBREW_PATH/bin(N-/) /usr/bin(N-/) /usr/sbin(N-/) /bin(N-/) /sbin(N-/) ) typeset -U manpath manpath=( $HOMEBREW_PATH/share/man(N-/) $HOMEBREW_PATH/opt/coreutils/libexec/gnuman(N-/) /usr/share/man(N-/) ) export PAGER=less export LESS='--LONG-PROMPT --RAW-CONTROL-CHARS' if whence nvim 2>&1 >/dev/null; then EDITOR=nvim fi MACVIM_APP= local -a macvim_app_candidates=( /opt/homebrew-cask/Caskroom/macvim-kaoriya/*/MacVim.app(N-/) $HOMEBREW_PATH/opt/macvim/MacVim.app(N-/) $HOME/Applications/MacVim.app(N-/) /Applications/MacVim.app(N-/) ) if (( $#macvim_app_candidates > 0 )); then MACVIM_APP="$macvim_app_candidates[1]" fi export MACVIM_APP
aereal/dotfiles
2188437d645b44a4cf7a051c4c45e8d8afda2cb7
bundler: install gems globally by default
diff --git a/.bundle/config b/.bundle/config index 5fd52a0..179ac28 100644 --- a/.bundle/config +++ b/.bundle/config @@ -1,5 +1,3 @@ --- -BUNDLE_PATH: vendor/bundle -BUNDLE_DISABLE_SHARED_GEMS: '1' BUNDLE_BIN: ".bundle/bin" BUNDLE_JOBS: '4'
aereal/dotfiles
43ad69a1a57fead43761b671369b0bf943e8e5ea
gemrc: remove deprecated options
diff --git a/.gemrc b/.gemrc index e643382..676582b 100644 --- a/.gemrc +++ b/.gemrc @@ -1,6 +1,6 @@ --- :backtrace: true :benchmark: false :verbose: true -gem: --no-rdoc --no-ri +gem: -N search: -r
aereal/dotfiles
4be1a1bae8e50e77203d9ef52f5e39e6bd403340
zsh: Ruby path
diff --git a/.zshenv b/.zshenv index b993f8c..ae24b00 100644 --- a/.zshenv +++ b/.zshenv @@ -1,54 +1,56 @@ # environment export HOMEBREW_PATH=/usr/local export DEVEL_PATH=$HOME/devel export GOPATH=$DEVEL_PATH export EDITOR=vim path=( $HOME/bin(N-/) $DEVEL_PATH/bin(N-/) $HOME/.mysqlenv/bin(N-/) $HOME/.mysqlenv/shims(N-/) $HOME/.pyenv/bin(N-/) $HOME/.pyenv/shims(N-/) $HOME/.rbenv/bin(N-/) $HOME/.rbenv/shims(N-/) $HOME/.plenv/bin(N-/) $HOME/.plenv/shims(N-/) $HOME/.ndenv/bin(N-/) $HOME/.ndenv/shims(N-/) $GOPATH/bin(N-/) + $HOMEBREW_PATH/lib/ruby/gems/2.6.0/bin(N-/) + $HOMEBREW_PATH/opt/ruby/bin(N-/) $HOMEBREW_PATH/opt/mysql-client/bin(N-/) $HOMEBREW_PATH/opt/coreutils/libexec/gnubin(N-/) $HOMEBREW_PATH/bin(N-/) /usr/bin(N-/) /usr/sbin(N-/) /bin(N-/) /sbin(N-/) ) typeset -U manpath manpath=( $HOMEBREW_PATH/share/man(N-/) $HOMEBREW_PATH/opt/coreutils/libexec/gnuman(N-/) /usr/share/man(N-/) ) export PAGER=less export LESS='--LONG-PROMPT --RAW-CONTROL-CHARS' if whence nvim 2>&1 >/dev/null; then EDITOR=nvim fi MACVIM_APP= local -a macvim_app_candidates=( /opt/homebrew-cask/Caskroom/macvim-kaoriya/*/MacVim.app(N-/) $HOMEBREW_PATH/opt/macvim/MacVim.app(N-/) $HOME/Applications/MacVim.app(N-/) /Applications/MacVim.app(N-/) ) if (( $#macvim_app_candidates > 0 )); then MACVIM_APP="$macvim_app_candidates[1]" fi export MACVIM_APP
aereal/dotfiles
2f109faf788a089c3c38d8fef6d0c165b2f3fef5
mysql-client
diff --git a/.zshenv b/.zshenv index 1550939..b993f8c 100644 --- a/.zshenv +++ b/.zshenv @@ -1,53 +1,54 @@ # environment export HOMEBREW_PATH=/usr/local export DEVEL_PATH=$HOME/devel export GOPATH=$DEVEL_PATH export EDITOR=vim path=( $HOME/bin(N-/) $DEVEL_PATH/bin(N-/) $HOME/.mysqlenv/bin(N-/) $HOME/.mysqlenv/shims(N-/) $HOME/.pyenv/bin(N-/) $HOME/.pyenv/shims(N-/) $HOME/.rbenv/bin(N-/) $HOME/.rbenv/shims(N-/) $HOME/.plenv/bin(N-/) $HOME/.plenv/shims(N-/) $HOME/.ndenv/bin(N-/) $HOME/.ndenv/shims(N-/) $GOPATH/bin(N-/) + $HOMEBREW_PATH/opt/mysql-client/bin(N-/) $HOMEBREW_PATH/opt/coreutils/libexec/gnubin(N-/) $HOMEBREW_PATH/bin(N-/) /usr/bin(N-/) /usr/sbin(N-/) /bin(N-/) /sbin(N-/) ) typeset -U manpath manpath=( $HOMEBREW_PATH/share/man(N-/) $HOMEBREW_PATH/opt/coreutils/libexec/gnuman(N-/) /usr/share/man(N-/) ) export PAGER=less export LESS='--LONG-PROMPT --RAW-CONTROL-CHARS' if whence nvim 2>&1 >/dev/null; then EDITOR=nvim fi MACVIM_APP= local -a macvim_app_candidates=( /opt/homebrew-cask/Caskroom/macvim-kaoriya/*/MacVim.app(N-/) $HOMEBREW_PATH/opt/macvim/MacVim.app(N-/) $HOME/Applications/MacVim.app(N-/) /Applications/MacVim.app(N-/) ) if (( $#macvim_app_candidates > 0 )); then MACVIM_APP="$macvim_app_candidates[1]" fi export MACVIM_APP
aereal/dotfiles
e5c469f9b7e9848c16205712ffb8280bffae1550
zsh: just change working directory instead of running child shell process
diff --git a/.zshrc b/.zshrc index ade4208..6b4552d 100644 --- a/.zshrc +++ b/.zshrc @@ -1,360 +1,360 @@ bindkey -v # function load path {{{ typeset -Ua fpath fpath=( $HOME/.zsh.d/functions(N-/) $HOMEBREW_PATH/share/zsh-completions(N-/) $HOMEBREW_PATH/share/zsh/site-functions(N-/) $HOMEBREW_PATH/share/zsh/functions(N-/) $HOMEBREW_PATH/opt/docker-completion/share/zsh/site-functions(N-/) $HOMEBREW_PATH/opt/docker-compose-completion/share/zsh/site-functions(N-/) $fpath ) # }}} # fundamental options {{{ export REPORTTIME=1 setopt extended_glob # }}} # history {{{ HISTFILE=$HOME/.zsh_history HISTSIZE=10000000 SAVEHIST=$HISTSIZE set \ extended_history \ hist_ignore_dups \ hist_ignore_space \ inc_append_history \ share_history \ no_flow_control \ hist_save_no_dups \ hist_ignore_all_dups autoload history-search-end zle -N history-beginning-search-backward-end history-search-end zle -N history-beginning-search-forward-end history-search-end bindkey -v "^N" history-beginning-search-forward-end bindkey -v "^P" history-beginning-search-backward-end bindkey -v "^R" history-incremental-pattern-search-backward bindkey -v "^S" history-incremental-pattern-search-forward # }}} # color {{{ autoload -Uz colors; colors [[ -f "$HOME/.dircolors" ]] && source "$HOME/.dircolors" # }}} # completion {{{ zmodload -i zsh/complist autoload -U compinit && compinit -C setopt \ complete_in_word \ glob_complete \ hist_expand \ no_beep \ numeric_glob_sort # Format {{{ zstyle ':completion:*' format '%F{magenta}-- %d --%f' zstyle ':completion:*' group-name '' zstyle ':completion:*:options' description yes zstyle ':completion:*:options' auto-description '%d' zstyle ':completion:*:corrections' format ' %F{yellow}-- %d (errors: %e) --%f' zstyle ':completion:*:descriptions' format ' %F{magenta}-- %d --%f' zstyle ':completion:*:messages' format ' %F{blue}-- %d --%f' zstyle ':completion:*:warnings' format ' %F{red}-- no matches found --%f' zstyle ':completion:*:default' list-prompt '%S%M matches%s' # Show selected candidate zstyle ':completion:*:default' menu select=2 zstyle ':completion:*:default' list-colors "${(s.:.)LS_COLORS}" # Fuzzy match zstyle ':completion:*' matcher-list 'm:{a-z}={A-Z} r:|[._-]=*' zstyle ':completion:*' completer _oldlist _complete _match _ignored _approximate _prefix # sudo zstyle ':completion:sudo:*' environ PATH="$SUDO_PATH:$PATH" # Directory candidates order zstyle ':completion:*:cd:*' tag-order local-directories path-directories # Ignore current directory from directory candidates zstyle ':completion:*' ignore-parents parent pwd # Process candidates zstyle ':completion:*:*:*:*:processes' command 'ps -u $USER -o pid,user,comm -w' zstyle ':completion:*:*:kill:*:processes' list-colors '=(#b) #([0-9]#) ([0-9a-z-]#)*=01;36=0=01' zstyle ':completion:*:*:kill:*' menu yes select zstyle ':completion:*:*:kill:*' force-list always zstyle ':completion:*:*:kill:*' insert-ids single # Show man candidates with section zstyle ':completion:*:manuals' separate-sections true # }}} # key mapping {{{ bindkey -M menuselect 'h' vi-backward-char bindkey -M menuselect 'l' vi-forward-char bindkey -M menuselect 'j' vi-down-line-or-history bindkey -M menuselect 'k' vi-up-line-or-history # }}} # }}} # url-quote-magic {{{ autoload -Uz url-quote-magic zle -N self-insert url-quote-magic # }}} # expand backslash to tilde {{{ # Originally from: https://github.com/cho45/dotfiles/blob/64ea90d17aaf6c46a2cb090f2e12a6e3d7df6034/.zshrc#L245 expand-to-home-or-complete() { # {{{ if [ "$LBUFFER" = "" -o "$LBUFFER[-1]" = " " ]; then LBUFFER+="~/" else zle self-insert fi } # }}} zle -N expand-to-home-or-complete bindkey -v "\\" expand-to-home-or-complete # }}} # ghq {{{ __widget_cd_repo() { local selected_repo=$( ghq list | peco ) if [[ -n "$selected_repo" ]]; then - BUFFER="ghq look ${selected_repo}" + BUFFER="pushd $(ghq root)/${selected_repo}" zle accept-line fi zle -R -c } zle -N __widget_cd_repo bindkey -v "^]^G" __widget_cd_repo # }}} # git {{{ __widget_git_recent_branches() { local selected_branch=$( \ git for-each-ref --sort=-committerdate --format="%(refname) %(committerdate:relative)" -- refs/heads \ | sed -E 's/refs\/heads\///' \ | peco --query "$LBUFFER" \ | cut -f1 \ ) if [[ -n "$selected_branch" ]]; then BUFFER="git checkout ${selected_branch}" zle accept-line fi zle -R -c } zle -N __widget_git_recent_branches bindkey -v "^]gr" __widget_git_recent_branches # }}} # tmux: split window with vim-like key mappings {{{ # vertical split {{{ tmux_vsplit() { BUFFER="tmux split-window -d -p 50 -h '$BUFFER'" # TODO: escape zle accept-line } zle -N tmux_vsplit bindkey -v "^Wv" tmux_vsplit # }}} # horizontal split {{{ tmux_split() { BUFFER="tmux split-window -d -p 50 -v '$BUFFER'" # TODO: escape zle accept-line } zle -N tmux_split bindkey -v "^Ws" tmux_split # }}} # }}} # alias {{{ alias :q=exit if whence exa >/dev/null 2>&1; then alias l='exa -aF' alias ls='exa -aF' alias ll='exa -alF' else if whence gls >/dev/null; then alias l='gls --color=auto -AF' alias ls='gls --color=auto -AF' alias ll='gls --color=auto -AFl' else alias l='ls -GAF' alias ls='ls -GAF' alias ll='ls -GAFl' fi fi whence hub >/dev/null 2>&1 && alias git=hub # }}} # abbrev {{{ setopt extended_glob typeset -A abbreviations abbreviations=( 'Ig' '| rg' 'It' '| tail' 'Ij' '| jq' 'DC' 'docker-compose' ) magic-abbrev-expand() { local MATCH LBUFFER=${LBUFFER%%(#m)[-_a-zA-Z0-9]#} LBUFFER+=${abbreviations[$MATCH]:-$MATCH} zle self-insert } no-magic-abbrev-expand() { LBUFFER+=' ' } zle -N magic-abbrev-expand zle -N no-magic-abbrev-expand bindkey -v " " magic-abbrev-expand bindkey -v "^x " no-magic-abbrev-expand # }}} # prompt {{{ setopt \ prompt_subst \ prompt_percent \ transient_rprompt autoload -U promptinit && promptinit autoload -Uz vcs_info zstyle ':vcs_info:*' max-exports 4 zstyle ':vcs_info:(git|svn):*' formats '%R' '%S' '%b' '%s' zstyle ':vcs_info:(git|svn):*' actionformats '%R' '%S' '%b|%a' '%s' zstyle ':vcs_info:*' formats '%R' '%S' '%s:%b' '%s' zstyle ':vcs_info:*' actionformats '%R' '%S' '%s:%b|%a' '%s' __configure_prompt() { local ok_yuno="%F{yellow}✘╹◡╹✘%f" local bad_yuno="%F{red}✘>﹏<✘%f" local command_line="%(?.${ok_yuno}.${bad_yuno}) < " psvar=() STY= LANG=en_US.UTF-8 vcs_info repos=`print -nD "$vcs_info_msg_0_"` if [[ -n "$vcs_info_msg_1_" ]]; then vcs="$vcs_info_msg_3_" else vcs='' fi [[ -n "$repos" ]] && psvar[2]="$repos" [[ -n "$vcs_info_msg_1_" ]] && psvar[3]="$vcs_info_msg_1_" [[ -n "$vcs_info_msg_2_" ]] && psvar[1]="$vcs_info_msg_2_" local psdirs='[%F{yellow}%3(v|%32<..<%3v%<<|%60<..<%~%<<)%f]' local psvcs='%3(v|[%25<\<<%F{yellow}%2v%f@%F{blue}%1v%f%<<]|)' local git_is_dirty git_local_changes git_upstream_changes if git rev-parse --is-inside-work-tree &>/dev/null; then command git diff --no-ext-diff --quiet --exit-code || git_is_dirty='%F{yellow}*%f' local git_upstream_status=$(command git rev-list --left-right --count ...@{u} 2>/dev/null) git_upstream_status=(${(ps:\t:)git_upstream_status}) local left=${git_upstream_status[1]} right=${git_upstream_status[2]} (( ${left:-0} > 0 )) && git_local_changes='%F{green}⇡%f' (( ${right:-0} > 0 )) && git_upstream_changes='%F{red}⇣%f' fi export PROMPT="${command_line}" export RPROMPT="${psdirs}${git_is_dirty}${git_local_changes}${git_upstream_changes}${psvcs}" } autoload -Uz add-zsh-hooks add-zsh-hook precmd __configure_prompt # }}} # Show anyenv version {{{ notify_llenv_version() { for llenv in rbenv plenv ndenv pyenv; do llenv_root="${HOME}/.${llenv}" # XXX if whence $llenv >/dev/null && [[ "$(${llenv} version-origin)" != "$llenv_root/version" ]]; then echo "$fg[yellow]${llenv} changed version: $(${llenv} version-name)$reset_color" fi done } add-zsh-hook chpwd notify_llenv_version # }}} # Update current window name {{{ update_window_title() { # {{{ emulate -L zsh local -a cmd cmd=(${(z)2}) case $cmd[1] in *=*) # PLENV_VERSION=5.14.2 plenv exec perl -v => plenv echo -n "k$cmd[2]:t\\" return ;; ls|gls|clear|pwd) echo -n "k$ZSH_NAME\\" return ;; sudo|cd) echo -n "k$cmd[1] $cmd[2]:t\\" return ;; *) echo -n "k$cmd[1]:t\\" return ;; esac local -A jt jt=(${(kv)jobtexts}) $cmd >>(read num rest cmd=(${(z)${(e):-\$jt$num}}) echo -n "k$cmd[1]:t\\") 2>/dev/null } # }}} if [ "$TMUX" ]; then add-zsh-hook preexec update_window_title fi # }}} # direnv {{{ if whence direnv >/dev/null; then eval "$(direnv hook zsh)" fi # }}} # syntax highlight {{{ if [[ -f "$HOMEBREW_PATH/share/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh" ]]; then source $HOMEBREW_PATH/share/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh fi # }}} # substring-search {{{ if [[ -f "$HOMEBREW_PATH/opt/zsh-history-substring-search/zsh-history-substring-search.zsh" ]]; then source $HOMEBREW_PATH/opt/zsh-history-substring-search/zsh-history-substring-search.zsh bindkey -M vicmd "k" history-substring-search-up bindkey -M vicmd "j" history-substring-search-down fi # }}} if ! ssh-add -l 2>/dev/null; then echo '---> Add SSH private key' ssh-add fi # tmux {{{ if whence tmux >/dev/null && [ -z "$TMUX" ]; then if $(tmux has-session 2>/dev/null); then tmux attach-session -t "${HOST%%.*}" else tmux new-session -s "${HOST%%.*}" fi fi # }}} # vim:set foldmethod=marker:
aereal/dotfiles
67e0a7a10d10653a633d26dc6158e6c012e95053
git-medetai: requires PCRE2
diff --git a/.gitconfig b/.gitconfig index 3cc6497..b70be81 100644 --- a/.gitconfig +++ b/.gitconfig @@ -1,107 +1,107 @@ [user] email = [email protected] name = aereal [gui] encoding = utf-8 [github] user = aereal [alias] abort-rebase = rebase --abort branch-name = name-rev --name-only ci = commit -v co = checkout continue-rebase = rebase --continue cp = cherry-pick df = diff ds = diff --staged fdf = diff --function-context fetch-pulls = fetch origin +refs/pull/*:refs/remotes/pull/* fix = commit --amend gr = grep interactive-rebase = rebase --interactive network = log --graph --all --decorate --oneline onelog = log --oneline squashed-merge = merge --squash st = status --branch --short --untracked-files=normal --ignore-submodules=dirty ls = ls-files delete-branch = branch -d current-branch = symbolic-ref --short HEAD curret-remote-branch = rev-parse --abbrev-ref --symbolic-full-name @{u} hard-revert-merge-commit = reset --hard ORIG_HEAD - medetai = !git rev-list HEAD | grep -E '(.)\\1\\1\\1\\1\\1' + medetai = !git rev-list HEAD | rg -P '(.)\\1\\1' pr = pull-request recently-added = log --grep \"Revert\" --invert-grep --diff-filter=A --format=\"\" --name-only [color] branch = true diff = true grep = true interactive = true pager = true status = true [color "branch"] current = green reverse local = green remote = yellow [color "status"] changed = green untracked = cyan updated = yellow [i18n] commitencoding= utf-8 [core] quotepath = false whitespace = cr-at-eol pager = $PAGER precomposeunicode = true excludesfile = ~/.global.gitignore [push] default = simple [branch] autosetuprebase = always [grep] lineNumber = true patternType = perl [rebase] stat = true [diff "gzip"] textconv = gzcat [log] date = iso [merge] stat = true [interactive] singlekey = true [ghq] root = /Users/aereal/devel/src [diff] algorithm = histogram [include] path = ~/.secret.gitconfig [advice] statusHints = false [pager] log = git-diff-highlight | less show = git-diff-highlight | less diff = git-diff-highlight | less grep = false [url "[email protected]:"] pushInsteadOf = https://github.com/ pushInsteadOf = git://github.com/
aereal/dotfiles
1ca6f5bd9a3d3b648b8943588ad9e3aa83b6197d
brew.bash: + bat
diff --git a/brew.bash b/brew.bash index 2ccbf90..58f8302 100644 --- a/brew.bash +++ b/brew.bash @@ -1,68 +1,69 @@ #!/bin/bash set -e brew_install() { brew install $@ || : } brew update export HOMEBREW_NO_AUTO_UPDATE=1 # essentials brew_install awscli +brew_install bat brew_install colordiff brew_install coreutils brew_install curl brew_install direnv brew_install docker-completion brew_install docker-compose-completion brew_install envchain brew_install exa brew_install --HEAD motemen/furoshiki2/furoshiki2 brew_install git --with-curl brew_install gnu-tar brew_install go brew_install hub brew_install jq brew_install mackerelio/mackerel-agent/mackerel-agent brew_install mackerelio/mackerel-agent/mkr brew_install neovim brew_install peco brew_install proctools brew_install pstree brew_install reattach-to-user-namespace brew_install ripgrep brew_install slackcat brew_install sshuttle brew_install telnet brew_install tig brew_install tmux brew_install tree brew_install zsh --without-etcdir brew_install zsh-completions brew_install zsh-history-substring-search brew_install zsh-syntax-highlighting # extra brew_install graphviz brew_install mysql-client brew_install openssl brew_install itchyny/rexdep/rexdep # casks brew cask install alfred brew cask install docker brew cask install dropbox brew cask install homebrew/cask-versions/google-chrome-dev brew cask install gyazo brew cask install iterm2 brew cask install karabiner-elements brew cask install mattr-slate brew cask install slack brew cask install visual-studio-code # JDK-related brew cask install homebrew/cask-versions/java8 brew_install sbt
aereal/dotfiles
096552d6f2be8361b6a7b7638b102c769fb18d6e
brew.bash: ensure install
diff --git a/brew.bash b/brew.bash index dc65348..2ccbf90 100644 --- a/brew.bash +++ b/brew.bash @@ -1,64 +1,68 @@ #!/bin/bash set -e +brew_install() { + brew install $@ || : +} + brew update export HOMEBREW_NO_AUTO_UPDATE=1 # essentials -brew install awscli -brew install colordiff -brew install coreutils -brew install curl -brew install direnv -brew install docker-completion -brew install docker-compose-completion -brew install envchain -brew install exa -brew install --HEAD motemen/furoshiki2/furoshiki2 -brew install git --with-curl -brew install gnu-tar -brew install go -brew install hub -brew install jq -brew install mackerelio/mackerel-agent/mackerel-agent -brew install mackerelio/mackerel-agent/mkr -brew install neovim -brew install peco -brew install proctools -brew install pstree -brew install reattach-to-user-namespace -brew install ripgrep -brew install slackcat -brew install sshuttle -brew install telnet -brew install tig -brew install tmux -brew install tree -brew install zsh --without-etcdir -brew install zsh-completions -brew install zsh-history-substring-search -brew install zsh-syntax-highlighting +brew_install awscli +brew_install colordiff +brew_install coreutils +brew_install curl +brew_install direnv +brew_install docker-completion +brew_install docker-compose-completion +brew_install envchain +brew_install exa +brew_install --HEAD motemen/furoshiki2/furoshiki2 +brew_install git --with-curl +brew_install gnu-tar +brew_install go +brew_install hub +brew_install jq +brew_install mackerelio/mackerel-agent/mackerel-agent +brew_install mackerelio/mackerel-agent/mkr +brew_install neovim +brew_install peco +brew_install proctools +brew_install pstree +brew_install reattach-to-user-namespace +brew_install ripgrep +brew_install slackcat +brew_install sshuttle +brew_install telnet +brew_install tig +brew_install tmux +brew_install tree +brew_install zsh --without-etcdir +brew_install zsh-completions +brew_install zsh-history-substring-search +brew_install zsh-syntax-highlighting # extra -brew install graphviz -brew install mysql-client -brew install openssl -brew install itchyny/rexdep/rexdep +brew_install graphviz +brew_install mysql-client +brew_install openssl +brew_install itchyny/rexdep/rexdep # casks brew cask install alfred brew cask install docker brew cask install dropbox brew cask install homebrew/cask-versions/google-chrome-dev brew cask install gyazo brew cask install iterm2 brew cask install karabiner-elements brew cask install mattr-slate brew cask install slack brew cask install visual-studio-code # JDK-related brew cask install homebrew/cask-versions/java8 -brew install sbt +brew_install sbt
aereal/dotfiles
68671a9b73cb4e88054d8bf8b85a0e64bec71457
brew.bash: HOMEBREW_NO_AUTO_UPDATE
diff --git a/brew.bash b/brew.bash index b63668a..dc65348 100644 --- a/brew.bash +++ b/brew.bash @@ -1,62 +1,64 @@ #!/bin/bash set -e brew update +export HOMEBREW_NO_AUTO_UPDATE=1 + # essentials brew install awscli brew install colordiff brew install coreutils brew install curl brew install direnv brew install docker-completion brew install docker-compose-completion brew install envchain brew install exa brew install --HEAD motemen/furoshiki2/furoshiki2 brew install git --with-curl brew install gnu-tar brew install go brew install hub brew install jq brew install mackerelio/mackerel-agent/mackerel-agent brew install mackerelio/mackerel-agent/mkr brew install neovim brew install peco brew install proctools brew install pstree brew install reattach-to-user-namespace brew install ripgrep brew install slackcat brew install sshuttle brew install telnet brew install tig brew install tmux brew install tree brew install zsh --without-etcdir brew install zsh-completions brew install zsh-history-substring-search brew install zsh-syntax-highlighting # extra brew install graphviz brew install mysql-client brew install openssl brew install itchyny/rexdep/rexdep # casks brew cask install alfred brew cask install docker brew cask install dropbox brew cask install homebrew/cask-versions/google-chrome-dev brew cask install gyazo brew cask install iterm2 brew cask install karabiner-elements brew cask install mattr-slate brew cask install slack brew cask install visual-studio-code # JDK-related brew cask install homebrew/cask-versions/java8 brew install sbt
aereal/dotfiles
cb814f622d508ddb8a081a2651583bedbd739cca
git-run: credit
diff --git a/bin/git-run b/bin/git-run index e6c65ef..ccf4d08 100755 --- a/bin/git-run +++ b/bin/git-run @@ -1,8 +1,10 @@ #!/bin/bash +# originally written at https://fujimura.hatenablog.com/entry/2018/03/30/181715 + set -e git-check-dirty eval $@ git add -A git commit --edit --verbose --message "$(echo $@)"
aereal/dotfiles
fa9c0f679f85778b109af92c9b5d7eb7529147f7
git-check-dirty: fix inversion of the condition
diff --git a/bin/git-check-dirty b/bin/git-check-dirty index c6ca746..09575d8 100755 --- a/bin/git-check-dirty +++ b/bin/git-check-dirty @@ -1,9 +1,9 @@ #!/bin/bash # refs. https://unix.stackexchange.com/questions/155046/determine-if-git-working-directory-is-clean-from-a-script if [[ -z "$(git status --short --untracked-files=normal --porcelain)" ]]; then - exit 1 + exit 0 fi -exit 0 +exit 1
aereal/dotfiles
063adc3dd773267661f3ca2b9fd3e4d3fafff27b
git-run
diff --git a/bin/git-run b/bin/git-run new file mode 100755 index 0000000..e6c65ef --- /dev/null +++ b/bin/git-run @@ -0,0 +1,8 @@ +#!/bin/bash + +set -e + +git-check-dirty +eval $@ +git add -A +git commit --edit --verbose --message "$(echo $@)"
aereal/dotfiles
909568f11cdb44b48eff7473427e68bd9a24011d
git-check-dirty
diff --git a/bin/git-check-dirty b/bin/git-check-dirty new file mode 100755 index 0000000..c6ca746 --- /dev/null +++ b/bin/git-check-dirty @@ -0,0 +1,9 @@ +#!/bin/bash + +# refs. https://unix.stackexchange.com/questions/155046/determine-if-git-working-directory-is-clean-from-a-script + +if [[ -z "$(git status --short --untracked-files=normal --porcelain)" ]]; then + exit 1 +fi + +exit 0
aereal/dotfiles
5333ba582b98eaa08e1ac394449bd8abcc584a5c
brew.bash: + mattr-slate
diff --git a/brew.bash b/brew.bash index efcf3de..b63668a 100644 --- a/brew.bash +++ b/brew.bash @@ -1,61 +1,62 @@ #!/bin/bash set -e brew update # essentials brew install awscli brew install colordiff brew install coreutils brew install curl brew install direnv brew install docker-completion brew install docker-compose-completion brew install envchain brew install exa brew install --HEAD motemen/furoshiki2/furoshiki2 brew install git --with-curl brew install gnu-tar brew install go brew install hub brew install jq brew install mackerelio/mackerel-agent/mackerel-agent brew install mackerelio/mackerel-agent/mkr brew install neovim brew install peco brew install proctools brew install pstree brew install reattach-to-user-namespace brew install ripgrep brew install slackcat brew install sshuttle brew install telnet brew install tig brew install tmux brew install tree brew install zsh --without-etcdir brew install zsh-completions brew install zsh-history-substring-search brew install zsh-syntax-highlighting # extra brew install graphviz brew install mysql-client brew install openssl brew install itchyny/rexdep/rexdep # casks brew cask install alfred brew cask install docker brew cask install dropbox brew cask install homebrew/cask-versions/google-chrome-dev brew cask install gyazo brew cask install iterm2 brew cask install karabiner-elements +brew cask install mattr-slate brew cask install slack brew cask install visual-studio-code # JDK-related brew cask install homebrew/cask-versions/java8 brew install sbt
aereal/dotfiles
ac78a57d3d797d62179fa3c8f55a4e33227b9ef7
brew.bash: Specify tap
diff --git a/brew.bash b/brew.bash index b59a960..efcf3de 100644 --- a/brew.bash +++ b/brew.bash @@ -1,61 +1,61 @@ #!/bin/bash set -e brew update # essentials brew install awscli brew install colordiff brew install coreutils brew install curl brew install direnv brew install docker-completion brew install docker-compose-completion brew install envchain brew install exa brew install --HEAD motemen/furoshiki2/furoshiki2 brew install git --with-curl brew install gnu-tar brew install go brew install hub brew install jq brew install mackerelio/mackerel-agent/mackerel-agent brew install mackerelio/mackerel-agent/mkr brew install neovim brew install peco brew install proctools brew install pstree brew install reattach-to-user-namespace brew install ripgrep brew install slackcat brew install sshuttle brew install telnet brew install tig brew install tmux brew install tree brew install zsh --without-etcdir brew install zsh-completions brew install zsh-history-substring-search brew install zsh-syntax-highlighting # extra brew install graphviz brew install mysql-client brew install openssl brew install itchyny/rexdep/rexdep # casks brew cask install alfred brew cask install docker brew cask install dropbox -brew cask install google-chrome-dev +brew cask install homebrew/cask-versions/google-chrome-dev brew cask install gyazo brew cask install iterm2 brew cask install karabiner-elements brew cask install slack brew cask install visual-studio-code # JDK-related brew cask install homebrew/cask-versions/java8 brew install sbt
aereal/dotfiles
dc7581354a7429b7e3d4aae7905050d3fdef7fe2
brew.cash: manage JDK-related apps dependencies
diff --git a/brew.bash b/brew.bash index a96bea8..b59a960 100644 --- a/brew.bash +++ b/brew.bash @@ -1,58 +1,61 @@ #!/bin/bash set -e brew update # essentials brew install awscli brew install colordiff brew install coreutils brew install curl brew install direnv brew install docker-completion brew install docker-compose-completion brew install envchain brew install exa brew install --HEAD motemen/furoshiki2/furoshiki2 brew install git --with-curl brew install gnu-tar brew install go brew install hub brew install jq brew install mackerelio/mackerel-agent/mackerel-agent brew install mackerelio/mackerel-agent/mkr brew install neovim brew install peco brew install proctools brew install pstree brew install reattach-to-user-namespace brew install ripgrep brew install slackcat brew install sshuttle brew install telnet brew install tig brew install tmux brew install tree brew install zsh --without-etcdir brew install zsh-completions brew install zsh-history-substring-search brew install zsh-syntax-highlighting # extra brew install graphviz brew install mysql-client brew install openssl brew install itchyny/rexdep/rexdep -brew install sbt # casks brew cask install alfred brew cask install docker brew cask install dropbox brew cask install google-chrome-dev brew cask install gyazo brew cask install iterm2 brew cask install karabiner-elements brew cask install slack brew cask install visual-studio-code + +# JDK-related +brew cask install homebrew/cask-versions/java8 +brew install sbt
aereal/dotfiles
85bb4c08dc1247e7c7fe71dd805d3bcd167dbd1a
brew.bash: Fix typo
diff --git a/brew.bash b/brew.bash index 3c987a9..a96bea8 100644 --- a/brew.bash +++ b/brew.bash @@ -1,58 +1,58 @@ #!/bin/bash set -e brew update # essentials brew install awscli brew install colordiff brew install coreutils brew install curl brew install direnv brew install docker-completion brew install docker-compose-completion brew install envchain brew install exa brew install --HEAD motemen/furoshiki2/furoshiki2 brew install git --with-curl brew install gnu-tar brew install go brew install hub brew install jq brew install mackerelio/mackerel-agent/mackerel-agent brew install mackerelio/mackerel-agent/mkr brew install neovim brew install peco brew install proctools brew install pstree brew install reattach-to-user-namespace brew install ripgrep brew install slackcat -brew install sshutltle +brew install sshuttle brew install telnet brew install tig brew install tmux brew install tree brew install zsh --without-etcdir brew install zsh-completions brew install zsh-history-substring-search brew install zsh-syntax-highlighting # extra brew install graphviz brew install mysql-client brew install openssl brew install itchyny/rexdep/rexdep brew install sbt # casks brew cask install alfred brew cask install docker brew cask install dropbox brew cask install google-chrome-dev brew cask install gyazo brew cask install iterm2 brew cask install karabiner-elements brew cask install slack brew cask install visual-studio-code
aereal/dotfiles
dcf2a8838208625774237e404635b404850940c4
brew.bash: tar -> gnu-tar
diff --git a/brew.bash b/brew.bash index 77f6eca..3c987a9 100644 --- a/brew.bash +++ b/brew.bash @@ -1,58 +1,58 @@ #!/bin/bash set -e brew update # essentials brew install awscli brew install colordiff brew install coreutils brew install curl brew install direnv brew install docker-completion brew install docker-compose-completion brew install envchain brew install exa brew install --HEAD motemen/furoshiki2/furoshiki2 brew install git --with-curl -brew install tar +brew install gnu-tar brew install go brew install hub brew install jq brew install mackerelio/mackerel-agent/mackerel-agent brew install mackerelio/mackerel-agent/mkr brew install neovim brew install peco brew install proctools brew install pstree brew install reattach-to-user-namespace brew install ripgrep brew install slackcat brew install sshutltle brew install telnet brew install tig brew install tmux brew install tree brew install zsh --without-etcdir brew install zsh-completions brew install zsh-history-substring-search brew install zsh-syntax-highlighting # extra brew install graphviz brew install mysql-client brew install openssl brew install itchyny/rexdep/rexdep brew install sbt # casks brew cask install alfred brew cask install docker brew cask install dropbox brew cask install google-chrome-dev brew cask install gyazo brew cask install iterm2 brew cask install karabiner-elements brew cask install slack brew cask install visual-studio-code
aereal/dotfiles
e6ffd8f8a9d88ea8f261bc478cc99304ab175f51
brew.bash: --HEAD
diff --git a/.bundle/config b/.bundle/config new file mode 100644 index 0000000..5fd52a0 --- /dev/null +++ b/.bundle/config @@ -0,0 +1,5 @@ +--- +BUNDLE_PATH: vendor/bundle +BUNDLE_DISABLE_SHARED_GEMS: '1' +BUNDLE_BIN: ".bundle/bin" +BUNDLE_JOBS: '4' diff --git a/.caprc b/.caprc new file mode 100644 index 0000000..b049169 --- /dev/null +++ b/.caprc @@ -0,0 +1,6 @@ +# vim:set ft=ruby: + +begin + require 'capistrano_colors' +rescue LoadError +end diff --git a/.colordiffrc b/.colordiffrc new file mode 100644 index 0000000..1a45dd9 --- /dev/null +++ b/.colordiffrc @@ -0,0 +1,29 @@ +# Example colordiffrc file for dark backgrounds +# +# Set banner=no to suppress authorship info at top of +# colordiff output +banner=no +# By default, when colordiff output is being redirected +# to a file, it detects this and does not colour-highlight +# To make the patch file *include* colours, change the option +# below to 'yes' +color_patches=no +# Sometimes it can be useful to specify which diff command to +# use: that can be specified here +diff_cmd=diff +# +# available colours are: white, yellow, green, blue, +# cyan, red, magenta, black, +# darkwhite, darkyellow, darkgreen, +# darkblue, darkcyan, darkred, +# darkmagenta, darkblack +# +# Can also specify 'none', 'normal' or 'off' which are all +# aliases for the same thing, namely "don't colour highlight +# this, use the default output colour" +# +plain=off +newtext=darkgreen +oldtext=red +diffstuff=magenta +cvsstuff=green diff --git a/.config/nvim/after b/.config/nvim/after new file mode 120000 index 0000000..dcc7fca --- /dev/null +++ b/.config/nvim/after @@ -0,0 +1 @@ +/Users/aereal/devel/src/github.com/aereal/dotfiles/.vim/after \ No newline at end of file diff --git a/.config/nvim/colors b/.config/nvim/colors new file mode 120000 index 0000000..eb2a3b3 --- /dev/null +++ b/.config/nvim/colors @@ -0,0 +1 @@ +/Users/aereal/devel/src/github.com/aereal/dotfiles/.vim/colors \ No newline at end of file diff --git a/.config/nvim/etc b/.config/nvim/etc new file mode 120000 index 0000000..8a080e2 --- /dev/null +++ b/.config/nvim/etc @@ -0,0 +1 @@ +/Users/aereal/devel/src/github.com/aereal/dotfiles/.vim/etc \ No newline at end of file diff --git a/.config/nvim/filetype.vim b/.config/nvim/filetype.vim new file mode 120000 index 0000000..e96f556 --- /dev/null +++ b/.config/nvim/filetype.vim @@ -0,0 +1 @@ +/Users/aereal/devel/src/github.com/aereal/dotfiles/.vim/filetype.vim \ No newline at end of file diff --git a/.config/nvim/ginit.vim b/.config/nvim/ginit.vim new file mode 120000 index 0000000..8c0a24b --- /dev/null +++ b/.config/nvim/ginit.vim @@ -0,0 +1 @@ +/Users/aereal/devel/src/github.com/aereal/dotfiles/.vim/gvimrc \ No newline at end of file diff --git a/.config/nvim/init.vim b/.config/nvim/init.vim new file mode 120000 index 0000000..1c7e39d --- /dev/null +++ b/.config/nvim/init.vim @@ -0,0 +1 @@ +/Users/aereal/devel/src/github.com/aereal/dotfiles/.vim/vimrc \ No newline at end of file diff --git a/.config/nvim/rc b/.config/nvim/rc new file mode 120000 index 0000000..67e61fc --- /dev/null +++ b/.config/nvim/rc @@ -0,0 +1 @@ +/Users/aereal/devel/src/github.com/aereal/dotfiles/.vim/rc \ No newline at end of file diff --git a/.config/nvim/snippets b/.config/nvim/snippets new file mode 120000 index 0000000..bb8328b --- /dev/null +++ b/.config/nvim/snippets @@ -0,0 +1 @@ +/Users/aereal/devel/src/github.com/aereal/dotfiles/.vim/snippets \ No newline at end of file diff --git a/.dotfiles.ignore b/.dotfiles.ignore new file mode 100644 index 0000000..e1bb8b7 --- /dev/null +++ b/.dotfiles.ignore @@ -0,0 +1,4 @@ +.git +.gitmodules +.travis.yml +.dotfiles.ignore diff --git a/.gemrc b/.gemrc new file mode 100644 index 0000000..e643382 --- /dev/null +++ b/.gemrc @@ -0,0 +1,6 @@ +--- +:backtrace: true +:benchmark: false +:verbose: true +gem: --no-rdoc --no-ri +search: -r diff --git a/.gitconfig b/.gitconfig new file mode 100644 index 0000000..3cc6497 --- /dev/null +++ b/.gitconfig @@ -0,0 +1,107 @@ +[user] + email = [email protected] + name = aereal + +[gui] + encoding = utf-8 + +[github] + user = aereal + +[alias] + abort-rebase = rebase --abort + branch-name = name-rev --name-only + ci = commit -v + co = checkout + continue-rebase = rebase --continue + cp = cherry-pick + df = diff + ds = diff --staged + fdf = diff --function-context + fetch-pulls = fetch origin +refs/pull/*:refs/remotes/pull/* + fix = commit --amend + gr = grep + interactive-rebase = rebase --interactive + network = log --graph --all --decorate --oneline + onelog = log --oneline + squashed-merge = merge --squash + st = status --branch --short --untracked-files=normal --ignore-submodules=dirty + ls = ls-files + delete-branch = branch -d + current-branch = symbolic-ref --short HEAD + curret-remote-branch = rev-parse --abbrev-ref --symbolic-full-name @{u} + hard-revert-merge-commit = reset --hard ORIG_HEAD + medetai = !git rev-list HEAD | grep -E '(.)\\1\\1\\1\\1\\1' + pr = pull-request + recently-added = log --grep \"Revert\" --invert-grep --diff-filter=A --format=\"\" --name-only + +[color] + branch = true + diff = true + grep = true + interactive = true + pager = true + status = true + +[color "branch"] + current = green reverse + local = green + remote = yellow + +[color "status"] + changed = green + untracked = cyan + updated = yellow + +[i18n] + commitencoding= utf-8 + +[core] + quotepath = false + whitespace = cr-at-eol + pager = $PAGER + precomposeunicode = true + excludesfile = ~/.global.gitignore + +[push] + default = simple + +[branch] + autosetuprebase = always + +[grep] + lineNumber = true + patternType = perl + +[rebase] + stat = true + +[diff "gzip"] + textconv = gzcat + +[log] + date = iso + +[merge] + stat = true + +[interactive] + singlekey = true + +[ghq] + root = /Users/aereal/devel/src + +[diff] + algorithm = histogram +[include] + path = ~/.secret.gitconfig +[advice] + statusHints = false +[pager] + log = git-diff-highlight | less + show = git-diff-highlight | less + diff = git-diff-highlight | less + grep = false +[url "[email protected]:"] + pushInsteadOf = https://github.com/ + pushInsteadOf = git://github.com/ diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..641bb06 --- /dev/null +++ b/.gitignore @@ -0,0 +1,16 @@ +.vim/cookies/ +.vim/netrwhist +.vim/.netrwhist +.vim/swp/* +.vim/.neocon/* +.vim/.ref/* +.vim/.unite/* +.vim/undo/* +.vim/bundle/* +src +.zcompcache/ +.zcompdump +/.vimperator/info/default/ +/.vim/snippets/*/private/ +.vim/.eskk/log +.vim/cache diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..67a6b5d --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "colors/dircolors-solarized"] + path = colors/dircolors-solarized + url = git://github.com/seebi/dircolors-solarized.git diff --git a/.global.gitignore b/.global.gitignore new file mode 100644 index 0000000..6d00d92 --- /dev/null +++ b/.global.gitignore @@ -0,0 +1,8 @@ +MYMETA.json +MYMETA.yml +/vendor/bundle +/.bundle/ +.DS_Store +tags +.envrc +.local.vimrc diff --git a/.my.cnf b/.my.cnf new file mode 100644 index 0000000..247e55e --- /dev/null +++ b/.my.cnf @@ -0,0 +1,3 @@ +[mysql] +prompt="\u@\h[\d]> " +auto-rehash diff --git a/.peco/config.json b/.peco/config.json new file mode 100644 index 0000000..16a7e49 --- /dev/null +++ b/.peco/config.json @@ -0,0 +1,22 @@ +{ + "Prompt": ">", + "Keymap": { + "M-x": "peco.ToggleSelectionAndSelectNext", + "C-g": "peco.Cancel" + }, + "Style": { + "SavedSelection": [ + "bold" + ], + "Selected": [ + "underline" + ], + "Query": [ + "yellow" + ], + "Matched": [ + "cyan", + "reverse" + ] + } +} diff --git a/.powenv b/.powenv new file mode 100644 index 0000000..a141f9c --- /dev/null +++ b/.powenv @@ -0,0 +1,3 @@ +# vim:set ft=sh: + +export PATH=$HOME/.rbenv/shims:$HOME/.rbenv/bin:$PATH diff --git a/.proverc b/.proverc new file mode 100644 index 0000000..6ef0e4e --- /dev/null +++ b/.proverc @@ -0,0 +1,6 @@ +--color +--lib +--failure +--recurse +--timer +--trap diff --git a/.pryrc b/.pryrc new file mode 100644 index 0000000..5e20ef6 --- /dev/null +++ b/.pryrc @@ -0,0 +1,36 @@ +# vim:set ft=ruby: + +def pbcopy(str) + IO.popen('pbcopy', 'r+') {|io| io.puts str } +end + +Pry.config.commands.command 'hcopy', 'Copy a history to clipboard' do |n| + pbcopy _pry_.input_array[n ? n.to_i : -1] +end + +Pry.config.commands.command 'copy', 'Copy a text to clipboard' do |str| + pbcopy str +end + +Pry.config.commands.command 'lastcopy', 'Copy the last result to clipboard' do + pbcopy _pry_.last_result.chomp +end + +if defined?(Hirb) + Hirb::View.instance_eval do + def enable_output_method + @output_method = true + @original_print = Pry.config.print + Pry.config.print = -> (output, value) { + Hirb::View.view_or_page_output(value) || @original_print.call(output, value) + } + end + + def disable_output_method + Pry.config.print = @original_print + @output_method = nil + end + end + + Hirb.enable +end diff --git a/.screenrc b/.screenrc new file mode 100644 index 0000000..d823d84 --- /dev/null +++ b/.screenrc @@ -0,0 +1,34 @@ +escape ^tt +defscrollback 10000 +defutf8 on +defkanji utf-8 +encoding utf-8 utf-8 +defencoding utf-8 +startup_message off +autodetach on +logfile "/tmp/screen-log-%Y%m%d-%n.log" +log on +deflog on +altscreen on +defbce on +termcapinfo xterm-256color|xterm-color|screen-256color ti@:te@ +term screen-256color +vbell off +bell_msg "Bell in window %^G" + +bind j focus down +bind k focus up +bind w eval 'echo "Operate window"' 'command -c operate' +bind -c operate ^] command +bind -c operate j eval 'focus down' 'command -c operate' +bind -c operate k eval 'focus up' 'command -c operate' +bind -c operate \^ eval 'focus top' 'command -c operate' +bind -c operate $ eval 'focus bottom' 'command -c operate' +bind -c operate x eval 'remove' 'command -c operate' +bind -c operate s eval 'split' 'command -c operate' +bind -c operate v eval 'split -v' 'command -c operate' +bind -c operate + eval 'resize +1' 'command -c operate' +bind -c operate - eval 'resize -1' 'command -c operate' + +caption splitonly "%3n %f %t" +hardstatus alwayslastline "%{.wk}[%S] %-w %{.rd}%{!}%n %f%t%{.wk} %+w" diff --git a/.slate.d/google_chrome.sh b/.slate.d/google_chrome.sh new file mode 100755 index 0000000..586acf3 --- /dev/null +++ b/.slate.d/google_chrome.sh @@ -0,0 +1,3 @@ +#!/bin/sh + +open -a "Google Chrome" diff --git a/.slate.js b/.slate.js new file mode 100644 index 0000000..681fbfd --- /dev/null +++ b/.slate.js @@ -0,0 +1,95 @@ +S.configAll({ + defaultToCurrentScreen: true, + checkDefaultsOnLoad: true, + modalEscapeKey: 'esc' +}); + +var VI_LIKE_WINDOW_PLACEMENT_PREFIX_KEY = ['delete', 'ctrl', 'cmd'].join(','); + +var vi = function(key) { + return [key, VI_LIKE_WINDOW_PLACEMENT_PREFIX_KEY, 'toggle'].join(':'); +}; + +var pushLeftOp = slate.op('push', { + direction: 'left', + style: 'bar-resize:screenSizeX/2' +}); +var pushDownOp = slate.op('push', { + direction: 'down', + style: 'bar-resize:screenSizeY/2' +}); +var pushUpOp = slate.op('push', { + direction: 'up', + style: 'bar-resize:screenSizeY/2' +}); +var pushRightOp = slate.op('push', { + direction: 'right', + style: 'bar-resize:screenSizeX/2' +}); +var moveTopLeftOp = slate.op('move', { + x: 0, + y: 0, + width: 'screenSizeX/2', + height: 'screenSizeY/2' +}); +var moveTopRightOp = slate.op('move', { + x: 'screenSizeX/2', + y: 0, + width: 'screenSizeX/2', + height: 'screenSizeY/2' +}); +var moveBottomRightOp = S.op('move', { + x: 'screenSizeX/2', + y: 'screenSizeY/2', + width: 'screenSizeX/2', + height: 'screenSizeY/2' +}); +var moveBottomLeftOp = slate.op('move', { + x: 0, + y: 'screenSizeY/2', + width: 'screenSizeX/2', + height: 'screenSizeY/2' +}); +var moveFullOp = slate.op('move', { + x: 0, + y: 0, + width: 'screenSizeX', + height: 'screenSizeY' +}); +var moveCenterOp = (function () { + var ratio = 0.75; + var op = slate.op('move', { + x: function () { + return slate.screen().rect().width * ((1 - ratio) / 2); + }, + y: function () { + return slate.screen().rect().height * ((1 - ratio) / 2); + }, + width: 'screenSizeX*0.75', + height: 'screenSizeY*0.75', + }); + return op; +})(); + +var viLikeWindowPlacements = { + h: pushLeftOp, + j: pushDownOp, + k: pushUpOp, + l: pushRightOp, + i: moveTopLeftOp, + o: moveTopRightOp, + m: moveBottomRightOp, + n: moveBottomLeftOp, + 'return': moveFullOp, + 'space': moveCenterOp, +}; + +for (var key in viLikeWindowPlacements) { + var op = viLikeWindowPlacements[key]; + S.bind(vi(key), op); +} + +S.bindAll({ + 'r:ctrl,cmd': S.op('relaunch'), + 'f:ctrl,cmd,shift': S.op('hint'), +}); diff --git a/.tigrc b/.tigrc new file mode 100644 index 0000000..8a91cb8 --- /dev/null +++ b/.tigrc @@ -0,0 +1,11 @@ +set commit-order = topo +set tab-size = 2 + +bind generic g move-first-line +bind generic G move-last-line +bind main o !@hub browse -- commit/%(commit) +bind diff o !@hub browse -- commit/%(commit) +bind log o !@hub browse -- commit/%(commit) +bind generic C !@sh -c '/bin/echo -n %(commit) | pbcopy' +bind diff C !@sh -c '/bin/echo -n %(commit) | pbcopy' +bind diff r !git rebase --interactive %(commit)~1 diff --git a/.tmux.conf b/.tmux.conf new file mode 100644 index 0000000..32499de --- /dev/null +++ b/.tmux.conf @@ -0,0 +1,52 @@ +# key bindings +## prefix key +unbind C-b +bind C-k send-prefix +set -g prefix C-k + +bind ^n next-window +bind ^p previous-window +bind ^c new-window + +bind n next-window +bind p previous-window +bind c new-window +bind r source-file ~/.tmux.conf +bind k confirm-before 'kill-window' +bind -r ^"[" copy-mode +bind -r ^] paste-buffer -s '' +bind | split-window -h +bind _ split-window -v + +## copy mode +unbind -T copy-mode-vi Space +bind -T copy-mode-vi v send -X begin-selection +bind -T copy-mode-vi y send -X copy-pipe "pbcopy" + +# options +set -g history-limit 1000000 +set -g default-terminal screen-256color + +## status +set -g status on +set -g status-interval 1 +set -g status-justify left +set -g status-position top +set -g status-left "" +set -g status-left-length 20 +set -g status-right "Battery:#($HOME/.tmux.d/scripts/macbook-battery) #($HOME/.tmux.d/scripts/today)" +set -g status-bg black +set -g status-fg white + +# window options +setw -g automatic-rename off +setw -g allow-rename on +setw -g mode-keys vi + +setw -g window-status-current-style reverse +setw -g window-status-current-format "#{window_index} #{window_name}" +setw -g window-status-format "#{window_index} #{window_name}" + +set -g default-command 'reattach-to-user-namespace -l $SHELL' + +set -sg escape-time 30 diff --git a/.tmux.d/scripts/macbook-battery b/.tmux.d/scripts/macbook-battery new file mode 100755 index 0000000..bb818f4 --- /dev/null +++ b/.tmux.d/scripts/macbook-battery @@ -0,0 +1,3 @@ +#!/bin/bash + +/usr/bin/pmset -g ps | /usr/bin/tail -1 | /usr/bin/awk '{ print $3 }' | /usr/bin/sed -e 's/;//g' diff --git a/.tmux.d/scripts/today b/.tmux.d/scripts/today new file mode 100755 index 0000000..88a26a0 --- /dev/null +++ b/.tmux.d/scripts/today @@ -0,0 +1,6 @@ +#!/bin/bash + +set -ue +export PATH=/usr/bin:/usr/sbin:/bin:/sbin + +date +'%H:%M' diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..ecf4cb4 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,12 @@ +--- +language: ruby +rvm: + - 2.1.1 +install: + - echo "Install" +before_script: + - mkdir -p $INSTALL_DIRECTORY +script: + - rake +env: + - INSTALL_DIRECTORY=tmp/home diff --git a/.uim b/.uim new file mode 100644 index 0000000..6d47705 --- /dev/null +++ b/.uim @@ -0,0 +1,6 @@ +;; vim:set ft=scheme: + +(define default-im-name 'skk) +(define skk-use-skkserv? #t) +(define skk-serv-hostname "localhost") +(define skk-serv-portnum 1178) diff --git a/.vim/.eskk/.keep b/.vim/.eskk/.keep new file mode 100644 index 0000000..e69de29 diff --git a/.vim/.neocon/.gitkeep b/.vim/.neocon/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/.vim/.unite/.gitkeep b/.vim/.unite/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/.vim/after/ftplugin/go.vim b/.vim/after/ftplugin/go.vim new file mode 100644 index 0000000..c750797 --- /dev/null +++ b/.vim/after/ftplugin/go.vim @@ -0,0 +1,2 @@ +inoremap <buffer><expr> = smartchr#loop(' := ', ' = ', ' == ', ' != ') +inoremap <buffer><expr> , smartchr#loop(', ', '<-', ',') diff --git a/.vim/after/ftplugin/haskell.vim b/.vim/after/ftplugin/haskell.vim new file mode 100644 index 0000000..0add605 --- /dev/null +++ b/.vim/after/ftplugin/haskell.vim @@ -0,0 +1,5 @@ +inoremap <buffer><expr> = smartchr#loop(' = ', '=') +inoremap <buffer><expr> . smartchr#one_of('.', ' -> ', ' => ', '.') +inoremap <buffer><expr> , smartchr#one_of(', ', ' <- ', ',') + +setlocal et diff --git a/.vim/after/ftplugin/html.vim b/.vim/after/ftplugin/html.vim new file mode 100644 index 0000000..c3f44ce --- /dev/null +++ b/.vim/after/ftplugin/html.vim @@ -0,0 +1 @@ +inoremap <buffer> = = diff --git a/.vim/after/ftplugin/javascript.vim b/.vim/after/ftplugin/javascript.vim new file mode 100644 index 0000000..d95076c --- /dev/null +++ b/.vim/after/ftplugin/javascript.vim @@ -0,0 +1,5 @@ +inoremap <buffer><expr> = smartchr#loop(' = ', ' == ', ' === ') +inoremap <buffer><expr> \ smartchr#one_of(' => ', '\') + +nnoremap <silent><buffer> <Space>kj :<C-u>Unite -start-insert -default-action=split ref/javascript<CR> +nnoremap <silent><buffer> <Space>kq :<C-u>Unite -start-insert -default-action=split ref/jquery<CR> diff --git a/.vim/after/ftplugin/perl.vim b/.vim/after/ftplugin/perl.vim new file mode 100644 index 0000000..9742b9e --- /dev/null +++ b/.vim/after/ftplugin/perl.vim @@ -0,0 +1,5 @@ +let b:tap_run_command = expand('~/.vim/bin/prove-wrapper') + +inoremap <buffer><expr> . smartchr#one_of('.', '->', '.') +inoremap <buffer><expr> , smartchr#one_of(', ', ' => ', ',') +inoremap <buffer><expr> = smartchr#loop(' = ', ' == ', ' != ', ' =~ ', ' !~ ', ' <=> ', '=') diff --git a/.vim/after/ftplugin/ruby.vim b/.vim/after/ftplugin/ruby.vim new file mode 100644 index 0000000..7b31aad --- /dev/null +++ b/.vim/after/ftplugin/ruby.vim @@ -0,0 +1,5 @@ +inoremap <buffer><expr> = smartchr#loop(' = ', ' == ', ' === ', ' != ') +inoremap <buffer><expr> , smartchr#loop(', ', ' => ', ',') + +nnoremap <silent><buffer> <Space>k :<C-u>Unite -start-insert -default-action=split ref/refe<CR> +nnoremap <silent><buffer> <S-k> :<C-u>UniteWithCursorWord -default-action=split ref/refe<CR> diff --git a/.vim/after/ftplugin/scala.vim b/.vim/after/ftplugin/scala.vim new file mode 100644 index 0000000..fcdb32f --- /dev/null +++ b/.vim/after/ftplugin/scala.vim @@ -0,0 +1 @@ +inoremap <buffer> ,t :EnType<CR> diff --git a/.vim/after/ftplugin/sh.vim b/.vim/after/ftplugin/sh.vim new file mode 100644 index 0000000..016aa8f --- /dev/null +++ b/.vim/after/ftplugin/sh.vim @@ -0,0 +1 @@ +inoremap <buffer><expr> = smartchr#loop('=', ' = ', ' != ') diff --git a/.vim/after/ftplugin/tt2html.vim b/.vim/after/ftplugin/tt2html.vim new file mode 100644 index 0000000..ccf8490 --- /dev/null +++ b/.vim/after/ftplugin/tt2html.vim @@ -0,0 +1 @@ +autocmd MyInit FileType tt2html inoremap <buffer> = = diff --git a/.vim/after/ftplugin/typescript.vim b/.vim/after/ftplugin/typescript.vim new file mode 100644 index 0000000..f143b07 --- /dev/null +++ b/.vim/after/ftplugin/typescript.vim @@ -0,0 +1 @@ +inoremap <buffer><expr> \ smartchr#one_of(' => ', '\') diff --git a/.vim/after/ftplugin/vim.vim b/.vim/after/ftplugin/vim.vim new file mode 100644 index 0000000..c3f44ce --- /dev/null +++ b/.vim/after/ftplugin/vim.vim @@ -0,0 +1 @@ +inoremap <buffer> = = diff --git a/.vim/after/syntax/sh.vim b/.vim/after/syntax/sh.vim new file mode 100644 index 0000000..700ee10 --- /dev/null +++ b/.vim/after/syntax/sh.vim @@ -0,0 +1,2 @@ +" exclude `--foo)` matches from within `$(cmd --foo)` +syntax match shOption "\s\zs--[^ \t$`'"|)]\+" diff --git a/.vim/bin/prove-wrapper b/.vim/bin/prove-wrapper new file mode 100755 index 0000000..f74733a --- /dev/null +++ b/.vim/bin/prove-wrapper @@ -0,0 +1,6 @@ +#!/bin/bash + +set -e + +env PERL5LIB="$PWD/lib:$PWD/local/lib/perl5" \ + plenv exec perl $@ diff --git a/.vim/colors/freya.vim b/.vim/colors/freya.vim new file mode 100644 index 0000000..a8adbd4 --- /dev/null +++ b/.vim/colors/freya.vim @@ -0,0 +1,79 @@ +set background=dark + +hi clear + +if exists("syntax_on") + syntax reset +endif + +let colors_name = "freya" + +hi Normal ctermbg=0 ctermfg=7 cterm=none guibg=#2a2a2a guifg=#dcdccc gui=none + +hi Cursor guibg=fg guifg=bg gui=none +hi CursorColumn guibg=#3f3f3f gui=none +hi CursorLine guibg=#3f3f3f gui=none +hi DiffAdd guibg=#008b00 guifg=fg gui=none +hi DiffChange guibg=#00008b guifg=fg gui=none +hi DiffDelete guibg=#8b0000 guifg=fg gui=none +hi DiffText guibg=#0000cd guifg=fg gui=bold +hi Directory guibg=bg guifg=#d4b064 gui=none +hi ErrorMsg guibg=bg guifg=#f07070 gui=bold +hi FoldColumn ctermbg=bg guibg=bg guifg=#c2b680 gui=none +hi Folded guibg=#101010 guifg=#c2b680 gui=none +hi IncSearch guibg=#866a4f guifg=fg gui=none +hi LineNr guibg=bg guifg=#9f8f80 gui=none +hi ModeMsg guibg=bg guifg=fg gui=bold +hi MoreMsg guibg=bg guifg=#dabfa5 gui=bold +hi NonText ctermfg=8 guibg=bg guifg=#9f8f80 gui=bold +hi Pmenu guibg=#a78869 guifg=#000000 gui=none +hi PmenuSbar guibg=#B99F86 guifg=fg gui=none +hi PmenuSel guibg=#c0aa94 guifg=bg gui=none +hi PmenuThumb guibg=#f7f7f1 guifg=bg gui=none +hi Question guibg=bg guifg=#dabfa5 gui=bold +hi Search guibg=#c0aa94 guifg=bg gui=none +hi SignColumn ctermbg=bg guibg=bg guifg=#c2b680 gui=none +hi SpecialKey guibg=bg guifg=#d4b064 gui=none +if has("spell") + hi SpellBad guisp=#f07070 gui=undercurl + hi SpellCap guisp=#7070f0 gui=undercurl + hi SpellLocal guisp=#70f0f0 gui=undercurl + hi SpellRare guisp=#f070f0 gui=undercurl +endif +hi StatusLine ctermbg=7 ctermfg=0 guibg=#736559 guifg=#f7f7f1 gui=bold +hi StatusLineNC ctermbg=8 ctermfg=0 guibg=#564d43 guifg=#f7f7f1 gui=none +hi TabLine guibg=#564d43 guifg=#f7f7f1 gui=underline +hi TabLineFill guibg=#564d43 guifg=#f7f7f1 gui=underline +hi TabLineSel guibg=bg guifg=#f7f7f1 gui=bold +hi Title ctermbg=0 ctermfg=15 guifg=#f7f7f1 gui=bold +hi VertSplit ctermbg=7 ctermfg=0 guibg=#564d43 guifg=#f7f7f1 gui=none +if version >= 700 + hi Visual ctermbg=7 ctermfg=0 guibg=#5f5f5f gui=none +else + hi Visual ctermbg=7 ctermfg=0 guibg=#5f5f5f guifg=fg gui=none +endif +hi VisualNOS guibg=bg guifg=#c0aa94 gui=bold,underline +hi WarningMsg guibg=bg guifg=#f07070 gui=none +hi WildMenu guibg=#c0aa94 guifg=bg gui=bold + +hi Comment guibg=bg guifg=#c2b680 gui=none +hi Constant guibg=bg guifg=#afe091 gui=none +hi Error guibg=bg guifg=#f07070 gui=none +hi Identifier guibg=bg guifg=#dabfa5 gui=none +hi Ignore guibg=bg guifg=bg gui=none +hi lCursor guibg=#c0aa94 guifg=bg gui=none +hi MatchParen guibg=#008b8b gui=none +hi PreProc guibg=bg guifg=#c2aed0 gui=none +hi Special guibg=bg guifg=#d4b064 gui=none +hi Statement guibg=bg guifg=#e0af91 gui=bold +hi Todo guibg=#aed0ae guifg=bg gui=none +hi Type guibg=bg guifg=#dabfa5 gui=bold +hi Underlined guibg=bg guifg=#d4b064 gui=underline + +hi htmlBold ctermbg=0 ctermfg=15 guibg=bg guifg=fg gui=bold +hi htmlItalic ctermbg=0 ctermfg=15 guibg=bg guifg=fg gui=italic +hi htmlUnderline ctermbg=0 ctermfg=15 guibg=bg guifg=fg gui=underline +hi htmlBoldItalic ctermbg=0 ctermfg=15 guibg=bg guifg=fg gui=bold,italic +hi htmlBoldUnderline ctermbg=0 ctermfg=15 guibg=bg guifg=fg gui=bold,underline +hi htmlBoldUnderlineItalic ctermbg=0 ctermfg=15 guibg=bg guifg=fg gui=bold,underline,italic +hi htmlUnderlineItalic ctermbg=0 ctermfg=15 guibg=bg guifg=fg gui=underline,italic diff --git a/.vim/colors/github.vim b/.vim/colors/github.vim new file mode 100644 index 0000000..bd48784 --- /dev/null +++ b/.vim/colors/github.vim @@ -0,0 +1,139 @@ +" Vim color file +" +" Author: Anthony Carapetis <[email protected]> +" +" Note: Based on github's syntax highlighting theme +" Used Brian Mock's darkspectrum as a starting point/template +" Thanks to Ryan Heath for an easy list of some of the colours: +" http://rpheath.com/posts/356-github-theme-for-syntax-gem + +hi clear + +set background=light +if version > 580 + " no guarantees for version 5.8 and below, but this makes it stop + " complaining + hi clear + if exists("syntax_on") + syntax reset + endif +endif +let g:colors_name="github" + +hi Normal guifg=#000000 guibg=#F8F8FF + +" {{{ Cursor +hi Cursor guibg=#444454 guifg=#F8F8FF +hi CursorLine guibg=#D8D8DD +hi CursorColumn guibg=#E8E8EE +" }}} + +" {{{ Diff +hi DiffAdd guifg=#003300 guibg=#DDFFDD gui=none +hi DiffChange guibg=#ececec gui=none +hi DiffText guifg=#000033 guibg=#DDDDFF gui=none +hi DiffDelete guifg=#DDCCCC guibg=#FFDDDD gui=none +" }}} + +" {{{ Folding / Line Numbering / Status Lines +hi Folded guibg=#ECECEC guifg=#808080 gui=bold +hi vimFold guibg=#ECECEC guifg=#808080 gui=bold +hi FoldColumn guibg=#ECECEC guifg=#808080 gui=bold + +hi LineNr guifg=#959595 guibg=#ECECEC gui=bold +hi NonText guifg=#808080 guibg=#ECECEC +hi Folded guifg=#808080 guibg=#ECECEC gui=bold +hi FoldeColumn guifg=#808080 guibg=#ECECEC gui=bold + +hi VertSplit guibg=#bbbbbb guifg=#bbbbbb gui=none +hi StatusLine guibg=#bbbbbb guifg=#404040 gui=bold +hi StatusLineNC guibg=#d4d4d4 guifg=#404040 gui=italic +" }}} + +" {{{ Misc +hi ModeMsg guifg=#990000 +hi MoreMsg guifg=#990000 + +hi Title guifg=#ef5939 +hi WarningMsg guifg=#ef5939 +hi SpecialKey guifg=#177F80 gui=italic + +hi MatchParen guibg=#cdcdfd guifg=#000000 +hi Underlined guifg=#000000 gui=underline +hi Directory guifg=#990000 +" }}} + +" {{{ Search, Visual, etc +hi Visual guifg=#FFFFFF guibg=#3465a4 gui=none +hi VisualNOS guifg=#FFFFFF guibg=#204a87 gui=none +hi IncSearch guibg=#cdcdfd guifg=#000000 gui=italic +hi Search guibg=#cdcdfd guifg=#000000 gui=italic +" }}} + +" {{{ Syntax groups +hi Ignore guifg=#808080 +hi Identifier guifg=#0086B3 +hi PreProc guifg=#A0A0A0 gui=bold +hi Comment guifg=#999988 +hi Constant guifg=#177F80 gui=none +hi String guifg=#D81745 +hi Function guifg=#990000 gui=bold +hi Statement guifg=#000000 gui=bold +hi Type guifg=#445588 gui=bold +hi Number guifg=#1C9898 +hi Todo guifg=#FFFFFF guibg=#990000 gui=bold +hi Special guifg=#159828 gui=bold +hi rubySymbol guifg=#960B73 +hi Error guibg=#f8f8ff guifg=#ff1100 gui=undercurl +hi Todo guibg=#f8f8ff guifg=#ff1100 gui=underline +hi Label guifg=#000000 gui=bold +hi StorageClass guifg=#000000 gui=bold +hi Structure guifg=#000000 gui=bold +hi TypeDef guifg=#000000 gui=bold +" }}} + +" {{{ Completion menus +hi WildMenu guifg=#7fbdff guibg=#425c78 gui=none + +hi Pmenu guibg=#808080 guifg=#ffffff gui=bold +hi PmenuSel guibg=#cdcdfd guifg=#000000 gui=italic +hi PmenuSbar guibg=#000000 guifg=#444444 +hi PmenuThumb guibg=#aaaaaa guifg=#aaaaaa +" }}} + +" {{{ Spelling +hi spellBad guisp=#fcaf3e +hi spellCap guisp=#73d216 +hi spellRare guisp=#fcaf3e +hi spellLocal guisp=#729fcf +" }}} + +" {{{ Aliases +hi link cppSTL Function +hi link cppSTLType Type +hi link Character Number +hi link htmlTag htmlEndTag +"hi link htmlTagName htmlTag +hi link htmlLink Underlined +hi link pythonFunction Identifier +hi link Question Type +hi link CursorIM Cursor +hi link VisualNOS Visual +hi link xmlTag Identifier +hi link xmlTagName Identifier +hi link shDeref Identifier +hi link shVariable Function +hi link rubySharpBang Special +hi link perlSharpBang Special +hi link schemeFunc Statement +"hi link shSpecialVariables Constant +"hi link bashSpecialVariables Constant +" }}} + +" {{{ Tabs (non-gui0 +hi TabLine guifg=#404040 guibg=#dddddd gui=none +hi TabLineFill guifg=#404040 guibg=#dddddd gui=none +hi TabLineSel guifg=#404040 gui=bold +" }}} +" +" vim: sw=4 ts=4 foldmethod=marker diff --git a/.vim/colors/liquidcarbon.vim b/.vim/colors/liquidcarbon.vim new file mode 100644 index 0000000..865fe83 --- /dev/null +++ b/.vim/colors/liquidcarbon.vim @@ -0,0 +1,133 @@ +" File: liquidcarbon.vim +" Author: Jeet Sukumaran +" Description: Vim color file +" Last Modified: October 06, 2010 + +" Initialization and Setup {{{1 +" ============================================================================ +set background=dark +highlight clear +if exists("syntax_on") + syntax reset +endif +let colors_name = "liquidcarbon" +" 1}}} + +" Normal Color {{{1 +" ============================================================================ +if exists("g:liquidcarbon_high_contrast") && g:liquidcarbon_high_contrast + hi Normal guifg=#bdcdcd guibg=#202020 + hi CursorLine guifg=NONE guibg=#292929 gui=NONE + hi ColorColumn guifg=NONE guibg=#292929 +else + hi Normal guifg=#bdcdcd guibg=#303030 + hi CursorLine guifg=NONE guibg=#3a3a3a gui=NONE + hi ColorColumn guifg=NONE guibg=#3a3a3a +endif + +" 1}}} + +" Core Highlights {{{1 +" ============================================================================ +hi Cursor guifg=bg guibg=fg gui=NONE +hi CursorIM guifg=bg guibg=fg gui=NONE +hi lCursor guifg=bg guibg=fg gui=NONE +hi DiffAdd guifg=#000000 guibg=#3cb371 gui=NONE +hi DiffChange guifg=#000000 guibg=#4f94cd gui=NONE +hi DiffDelete guifg=#000000 guibg=#8b3626 gui=NONE +hi DiffText guifg=#000000 guibg=#8ee5ee gui=NONE +hi Directory guifg=#1e90ff guibg=bg gui=NONE +hi ErrorMsg guifg=#ff6a6a guibg=NONE gui=bold +hi FoldColumn guifg=#68838b guibg=#4B4B4B gui=bold +hi Folded guifg=#68838b guibg=#4B4B4B gui=NONE +hi IncSearch guifg=#ffffff guibg=#ff4500 gui=bold +hi LineNr guifg=#767676 guibg=#000000 gui=NONE +hi MatchParen guifg=#fff000 guibg=#000000 gui=bold +hi ModeMsg guifg=#000000 guibg=#00ff00 gui=bold +hi MoreMsg guifg=#2e8b57 guibg=bg gui=bold +hi NonText guifg=#9ac0cd guibg=bg gui=NONE +hi Pmenu guifg=#0000ff guibg=#c0c8cf gui=bold +hi PmenuSel guifg=#c0c8cf guibg=#0000ff gui=bold +hi PmenuSbar guifg=#ffffff guibg=#c1cdc1 gui=NONE +hi PmenuThumb guifg=#ffffff guibg=#838b83 gui=NONE +hi Question guifg=#00ee00 guibg=NONE gui=bold +hi Search guifg=#000000 guibg=#fff68f gui=bold +hi SignColumn guifg=#ffffff guibg=#cdcdb4 gui=NONE +hi SpecialKey guifg=#666666 guibg=NONE gui=NONE +hi SpellBad guisp=#ee2c2c gui=undercurl +hi SpellCap guisp=#0000ff gui=undercurl +hi SpellLocal guisp=#008b8b gui=undercurl +hi SpellRare guisp=#ff00ff gui=undercurl +hi StatusLine guifg=#ddeeff guibg=#445566 gui=NONE +hi StatusLineNC guifg=#999999 guibg=#445566 gui=italic +hi TabLine guifg=fg guibg=#d3d3d3 gui=underline +hi TabLineFill guifg=fg guibg=bg gui=reverse +hi TabLineSel guifg=fg guibg=bg gui=bold +hi Title guifg=#009acd guibg=bg gui=bold +hi VertSplit guifg=#445566 guibg=#445566 +hi Visual guifg=#000000 guibg=#90ccff gui=NONE +hi WarningMsg guifg=#ee9a00 guibg=bg gui=NONE +hi WildMenu guifg=#000000 guibg=#87ceeb gui=NONE +" 1}}} + +" Syntax {{{1 +" ============================================================================ + +" General {{{2 +" ----------------------------------------------------------------------------- +hi Comment guifg=#809090 guibg=NONE gui=italic +hi Constant guifg=#cdad00 guibg=NONE gui=NONE +hi String guifg=#559b70 guibg=NONE gui=NONE +hi Boolean guifg=#cd69c9 guibg=NONE gui=NONE +hi Identifier guifg=#9f79ee guibg=NONE gui=NONE +hi Function guifg=#92a5de guibg=NONE gui=NONE +hi Statement guifg=#009acd guibg=NONE gui=NONE +hi PreProc guifg=#009acd guibg=NONE gui=NONE +hi Keyword guifg=#7ac5cd guibg=NONE gui=NONE +hi Type guifg=#4169e1 guibg=NONE gui=NONE +hi Special guifg=#7f9f44 guibg=NONE gui=NONE +hi Ignore guifg=bg guibg=NONE gui=NONE +hi Error guifg=#ff3030 guibg=NONE gui=underline +hi Todo guifg=#ff88ee guibg=NONE gui=bold +" 2}}} + +" Vim {{{2 +" ----------------------------------------------------------------------------- +hi VimError guifg=#ff0000 guibg=#000000 gui=bold +hi VimCommentTitle guifg=#528b8b guibg=bg gui=bold,italic +" 2}}} + +" QuickFix {{{2 +" ----------------------------------------------------------------------------- +hi qfFileName guifg=#607b8b guibg=NONE gui=italic +hi qfLineNr guifg=#0088aa guibg=NONE gui=bold +hi qfError guifg=#ff0000 guibg=NONE gui=bold +" 2}}} + +" Python {{{2 +" ----------------------------------------------------------------------------- +hi pythonDecorator guifg=#cd8500 guibg=NONE gui=NONE +hi link pythonDecoratorFunction pythonDecorator +" 2}}} + +" Diff {{{2 +" ----------------------------------------------------------------------------- +hi diffOldFile guifg=#da70d6 guibg=NONE gui=italic +hi diffNewFile guifg=#ffff00 guibg=NONE gui=italic +hi diffFile guifg=#ffa500 guibg=NONE gui=italic +hi diffLine guifg=#ff00ff guibg=NONE gui=italic +hi link diffOnly Constant +hi link diffIdentical Constant +hi link diffDiffer Constant +hi link diffBDiffer Constant +hi link diffIsA Constant +hi link diffNoEOL Constant +hi link diffCommon Constant +hi diffRemoved guifg=#cd5555 guibg=NONE gui=NONE +hi diffChanged guifg=#4f94cd guibg=NONE gui=NONE +hi diffAdded guifg=#00cd00 guibg=NONE gui=NONE +hi link diffSubname diffLine +hi link diffComment Comment +" 2}}} + +" 1}}} diff --git a/.vim/colors/navajo-night.vim b/.vim/colors/navajo-night.vim new file mode 100644 index 0000000..f0c27f0 --- /dev/null +++ b/.vim/colors/navajo-night.vim @@ -0,0 +1,119 @@ +" Vim colour file +" Maintainer: Matthew Hawkins <[email protected]> +" Last Change: Mon, 22 Apr 2002 15:28:04 +1000 +" URI: http://mh.dropbear.id.au/vim/navajo-night.png +" +" This colour scheme uses a "navajo-black" background +" I have added colours for the statusbar and for spell checking +" as taken from Cream (http://cream.sf.net/) + + +set background=dark +hi clear +if exists("syntax_on") + syntax reset +endif + +let g:colors_name = "navajo-night" + +" This is the list of colour changes from Navajo that +" weren't a simple mathematical subtraction from 0xffffff +" DarkBlue -> #ffff74 +" DarkRed -> #74ffff +" DarkGreen -> #ff9bff +" DarkCyan -> #ff7474 +" DarkMagenta -> #74ff74 +" DarkYellow -> #7474ff +" DarkGray -> #565656 +" Blue -> Yellow +" Red -> Cyan +" Yellow -> Blue +" Gray -> #414141 +" Brown -> #5ad5d5 +" #ff8060 -> #007f9f +" #f6e8d0 -> #09172f +" #edb5cd -> #124a32 +" #c0c0c0 -> #3f3f3f +" #907050 -> #6f8faf +" #808080 -> #7f7f7f +" #707070 -> #8f8f8f +" SeaGreen -> #d174a8 +" LightRed (assuming #ee9090) -> #116f6f +" LightBlue -> #522719 + +hi Normal ctermfg=White guifg=White guibg=#35536f + +hi SpecialKey term=bold ctermfg=darkblue guifg=Yellow +hi NonText term=bold ctermfg=darkblue cterm=bold gui=bold guifg=#7f7f7f +hi Directory term=bold ctermfg=darkblue guifg=Yellow +hi ErrorMsg term=standout ctermfg=grey ctermbg=darkred cterm=bold gui=bold guifg=Black guibg=Cyan +hi IncSearch term=reverse cterm=reverse gui=reverse +hi Search term=reverse ctermbg=White ctermfg=Black cterm=reverse guibg=Black guifg=Yellow +hi MoreMsg term=bold ctermfg=green gui=bold guifg=#d174a8 +hi ModeMsg term=bold cterm=bold gui=bold +hi LineNr term=underline ctermfg=darkcyan ctermbg=grey guibg=#7f7f7f gui=bold guifg=White +hi Question term=standout ctermfg=darkgreen gui=bold guifg=#d174a8 +hi StatusLine term=bold,reverse cterm=bold,reverse gui=bold guifg=Black guibg=White +hi StatusLineNC term=reverse cterm=reverse gui=bold guifg=#116f6f guibg=#8f8f8f +hi VertSplit term=reverse cterm=reverse gui=bold guifg=Black guibg=#8f8f8f +hi Title term=bold ctermfg=green gui=bold guifg=#74ff74 +"+++ Cream: +"hi Visual term=reverse cterm=reverse gui=reverse guifg=#3f3f3f guibg=White +"+++ +hi VisualNOS term=bold,underline cterm=bold,underline gui=reverse guifg=#414141 guibg=Black +hi WarningMsg term=standout ctermfg=darkred gui=bold guifg=Cyan +hi WildMenu term=standout ctermfg=White ctermbg=darkyellow guifg=White guibg=Blue +hi Folded term=standout ctermfg=darkblue ctermbg=grey guifg=White guibg=NONE guifg=#afcfef +hi FoldColumn term=standout ctermfg=darkblue ctermbg=grey guifg=#ffff74 guibg=#3f3f3f +hi DiffAdd term=bold ctermbg=darkblue guibg=Black +hi DiffChange term=bold ctermbg=darkmagenta guibg=#124a32 +hi DiffDelete term=bold ctermfg=darkblue ctermbg=blue cterm=bold gui=bold guifg=#522719 guibg=#09172f +hi DiffText term=reverse ctermbg=darkblue cterm=bold gui=bold guibg=#007f9f +hi Cursor gui=reverse guifg=#bfbfef guibg=Black +hi lCursor guifg=fg guibg=bg +hi Match term=bold,reverse ctermbg=Blue ctermfg=Yellow cterm=bold,reverse gui=bold,reverse guifg=Blue guibg=Yellow + + +" Colours for syntax highlighting +hi Comment term=bold ctermfg=darkblue guifg=#e7e77f +hi Constant term=underline ctermfg=darkred guifg=#3fffa7 +hi Special term=bold ctermfg=darkgreen guifg=#bfbfef +hi Identifier term=underline ctermfg=darkcyan cterm=NONE guifg=#ef9f9f +hi Statement term=bold ctermfg=darkred cterm=bold gui=bold guifg=#5ad5d5 +hi PreProc term=underline ctermfg=darkmagenta guifg=#74ff74 +hi Type term=underline ctermfg=green gui=bold guifg=#d174a8 +hi Ignore ctermfg=grey cterm=bold guifg=bg + +hi Error term=reverse ctermfg=grey ctermbg=darkred cterm=bold gui=bold guifg=Black guibg=Cyan +hi Todo term=standout ctermfg=darkblue ctermbg=Blue guifg=Yellow guibg=Blue + +"+++ Cream: statusbar +" Colours for statusbar +"hi User1 gui=bold guifg=#565656 guibg=#0c0c0c +"hi User2 gui=bold guifg=White guibg=#0c0c0c +"hi User3 gui=bold guifg=Yellow guibg=#0c0c0c +"hi User4 gui=bold guifg=Cyan guibg=#0c0c0c +highlight User1 gui=bold guifg=#999933 guibg=#45637f +highlight User2 gui=bold guifg=#e7e77f guibg=#45637f +highlight User3 gui=bold guifg=Black guibg=#45637f +highlight User4 gui=bold guifg=#33cc99 guibg=#45637f +"+++ + +"+++ Cream: selection +highlight Visual gui=bold guifg=Black guibg=#aacc77 +"+++ + +"+++ Cream: bookmarks +highlight Cream_ShowMarksHL ctermfg=blue ctermbg=lightblue cterm=bold guifg=Black guibg=#aacc77 gui=bold +"+++ + +"+++ Cream: spell check +" Colour misspelt words +"hi BadWord ctermfg=White ctermbg=darkred cterm=bold guifg=Yellow guibg=#522719 gui=bold +" mathematically correct: +"highlight BadWord ctermfg=black ctermbg=lightblue gui=NONE guifg=White guibg=#003333 +" adjusted: +highlight BadWord ctermfg=black ctermbg=lightblue gui=NONE guifg=#ff9999 guibg=#003333 +"+++ + + diff --git a/.vim/colors/railscasts.vim b/.vim/colors/railscasts.vim new file mode 100644 index 0000000..2055b41 --- /dev/null +++ b/.vim/colors/railscasts.vim @@ -0,0 +1,96 @@ +" Vim color scheme +" +" Name: railscasts.vim +" Maintainer: Nick Moffitt <[email protected]> +" Last Change: 01 Mar 2008 +" License: WTFPL <http://sam.zoy.org/wtfpl/> +" Version: 2.1 +" +" This theme is based on Josh O'Rourke's Vim clone of the railscast +" textmate theme. The key thing I have done here is supply 256-color +" terminal equivalents for as many of the colors as possible, and fixed +" up some of the funny behaviors for editing e-mails and such. +" +" To use for gvim: +" 1: install this file as ~/.vim/colors/railscasts.vim +" 2: put "colorscheme railscasts" in your .gvimrc +" +" If you are using Ubuntu, you can get the benefit of this in your +" terminals using ordinary vim by taking the following steps: +" +" 1: sudo apt-get install ncurses-term +" 2: put the following in your .vimrc +" if $COLORTERM == 'gnome-terminal' +" set term=gnome-256color +" colorscheme railscasts +" else +" colorscheme default +" endif +" 3: if you wish to use this with screen, add the following to your .screenrc: +" attrcolor b ".I" +" termcapinfo xterm 'Co#256:AB=\E[48;5;%dm:AF=\E[38;5;%dm' +" defbce "on" +" term screen-256color-bce + +set background=dark +hi clear +if exists("syntax_on") + syntax reset +endif + +let g:colors_name = "railscasts" + +hi link htmlTag xmlTag +hi link htmlTagName xmlTagName +hi link htmlEndTag xmlEndTag + +highlight Normal guifg=#E6E1DC guibg=#111111 +highlight Cursor guifg=#000000 ctermfg=0 guibg=#FFFFFF ctermbg=15 +highlight CursorLine guibg=#000000 ctermbg=233 cterm=NONE + +highlight Comment guifg=#BC9458 ctermfg=180 gui=italic +highlight Constant guifg=#6D9CBE ctermfg=73 +highlight Define guifg=#CC7833 ctermfg=173 +highlight Error guifg=#FFC66D ctermfg=221 guibg=#990000 ctermbg=88 +highlight Function guifg=#FFC66D ctermfg=221 gui=NONE cterm=NONE +highlight Identifier guifg=#6D9CBE ctermfg=73 gui=NONE cterm=NONE +highlight Include guifg=#CC7833 ctermfg=173 gui=NONE cterm=NONE +highlight PreCondit guifg=#CC7833 ctermfg=173 gui=NONE cterm=NONE +highlight Keyword guifg=#CC7833 ctermfg=173 cterm=NONE +highlight LineNr guifg=#2B2B2B ctermfg=159 guibg=#C0C0FF +highlight Number guifg=#A5C261 ctermfg=107 +highlight PreProc guifg=#E6E1DC ctermfg=103 +highlight Search guifg=NONE ctermfg=NONE guibg=#2b2b2b ctermbg=235 gui=italic cterm=underline +highlight Statement guifg=#CC7833 ctermfg=173 gui=NONE cterm=NONE +highlight String guifg=#A5C261 ctermfg=107 +highlight Title guifg=#FFFFFF ctermfg=15 +highlight Type guifg=#DA4939 ctermfg=167 gui=NONE cterm=NONE +highlight Visual guibg=#5A647E ctermbg=60 + +highlight DiffAdd guifg=#E6E1DC ctermfg=7 guibg=#519F50 ctermbg=71 +highlight DiffDelete guifg=#E6E1DC ctermfg=7 guibg=#660000 ctermbg=52 +highlight Special guifg=#DA4939 ctermfg=167 + +highlight pythonBuiltin guifg=#6D9CBE ctermfg=73 gui=NONE cterm=NONE +highlight rubyBlockParameter guifg=#FFFFFF ctermfg=15 +highlight rubyClass guifg=#FFFFFF ctermfg=15 +highlight rubyConstant guifg=#DA4939 ctermfg=167 +highlight rubyInstanceVariable guifg=#D0D0FF ctermfg=189 +highlight rubyInterpolation guifg=#519F50 ctermfg=107 +highlight rubyLocalVariableOrMethod guifg=#D0D0FF ctermfg=189 +highlight rubyPredefinedConstant guifg=#DA4939 ctermfg=167 +highlight rubyPseudoVariable guifg=#FFC66D ctermfg=221 +highlight rubyStringDelimiter guifg=#A5C261 ctermfg=143 + +highlight xmlTag guifg=#E8BF6A ctermfg=179 +highlight xmlTagName guifg=#E8BF6A ctermfg=179 +highlight xmlEndTag guifg=#E8BF6A ctermfg=179 + +highlight mailSubject guifg=#A5C261 ctermfg=107 +highlight mailHeaderKey guifg=#FFC66D ctermfg=221 +highlight mailEmail guifg=#A5C261 ctermfg=107 gui=italic cterm=underline + +highlight SpellBad guifg=#D70000 ctermfg=160 ctermbg=NONE cterm=underline +highlight SpellRare guifg=#D75F87 ctermfg=168 guibg=NONE ctermbg=NONE gui=underline cterm=underline +highlight SpellCap guifg=#D0D0FF ctermfg=189 guibg=NONE ctermbg=NONE gui=underline cterm=underline +highlight MatchParen guifg=#FFFFFF ctermfg=15 guibg=#005f5f ctermbg=23 diff --git a/.vim/colors/shandy.vim b/.vim/colors/shandy.vim new file mode 100644 index 0000000..44e707a --- /dev/null +++ b/.vim/colors/shandy.vim @@ -0,0 +1,53 @@ +set bg=dark +hi clear + +if exists("syntax_on") + syntax reset +endif + +let colors_name = "shandy" + +" blue: #7d95a6 +" red: #a67d7d +" yellow: #a6a67d +" green: #7da67d +" light green: #7da69d +" purple: #817da6 +" violet: #997da6 +" magenta: #a67d92 + +hi Normal guifg=#aaacb3 guibg=#1a1a1a +hi Cursor guifg=bg guibg=fg +hi MatchParen guifg=fg guibg=bg gui=underline +hi NonText guifg=#454545 +hi SpecialKey guifg=#454545 +hi LineNr guifg=#626872 +hi Visual guifg=fg guibg=#738499 +hi Title guifg=#a6a67d + +hi StatusLine guifg=fg guibg=#5b6477 gui=none +hi StatusLineNC guifg=#000000 guibg=#c1c8d6 gui=none +" DiffAdd +" DiffChange +" DiffDelete +" DiffText + +hi ModeMsg guifg=#98a3b2 +hi MoreMsg guifg=#98a3b2 +hi ErrorMsg guifg=#a67d7d guibg=fg gui=reverse +hi WarningMsg guifg=#a6a67d guibg=fg gui=reverse + +hi Pmenu guibg=#5b6477 +hi PmenuSel guifg=fg guibg=bg gui=reverse + +hi Comment guifg=#575d66 +hi Constant guifg=#7d95a6 +hi Identifier guifg=#7d95a6 +hi Statement guifg=#626872 +hi PreProc guifg=#626872 +hi Type guifg=#997da6 +hi Delimiter guifg=#98a3b2 +hi Special guifg=#a6a67d +hi Error guifg=#a67d7d guibg=fg gui=reverse +hi Todo guifg=#98a3b2 gui=underline + diff --git a/.vim/colors/tiro_finale.vim b/.vim/colors/tiro_finale.vim new file mode 100644 index 0000000..5326bf4 --- /dev/null +++ b/.vim/colors/tiro_finale.vim @@ -0,0 +1,48 @@ +hi clear +if exists("syntax_on") + syntax reset +endif + +let colors_name = "tiro_finale" + +set background=dark + +" #e7abc2 #e78baf #c2537e #754d5c #550726 +" #633008 #876d59 #e19860 #f3bc92 #f3cfb4 +" #053d39 #365351 #3b8a84 #7ed1cb #9bd1cd +" #345a08 #677a50 #96cc57 #c0eb8d #cfebae + +hi Normal guifg=#eaeaea guibg=#121111 +hi SpecialKey guifg=#555555 +hi Cursor guifg=bg guibg=fg +hi CursorLine guifg=fg guibg=bg gui=underline +hi LineNr guifg=#e7abc2 +hi MatchParen gui=underline cterm=underline +hi NonText guifg=#872c2a +hi DiffAdd guifg=#5f8486 guibg=bg +hi DiffChange guifg=#e19860 guibg=bg +hi DiffDelete guifg=#876d59 guibg=bg +hi DiffText guifg=fg guibg=bg gui=underline +hi Pmenu guibg=#6e0b23 +hi PmenuSel guifg=#121111 guibg=#dddddd gui=bold +hi PmenuSbar guifg=#dddddd guibg=#dddddd +hi Search guifg=bg guibg=#e39343 gui=underline,bold +hi IncSearch guifg=bg guibg=#e39343 gui=underline,bold +hi StatusLine guifg=#121111 guibg=#e19860 gui=NONE +hi StatusLineNC guifg=#e19860 guibg=#121111 gui=underline +hi MoreMsg guifg=#306ada +hi ModeMsg guifg=#cccccc +hi ErrorMsg guifg=white guibg=#6e0b23 +hi Todo guifg=fg guibg=bg gui=underline +hi Title guifg=#c2537e +hi WarningMsg guifg=#e39343 + +hi Comment guifg=#876d59 +hi Constant guifg=#f3bc92 +hi Statement guifg=#e19860 +hi PreProc guifg=#e19860 +hi Identifier guifg=#5f8486 +hi Type guifg=#c2537e +hi Delimiter guifg=#555555 +hi Special guifg=#e39343 + diff --git a/.vim/colors/wombat256mod.vim b/.vim/colors/wombat256mod.vim new file mode 100644 index 0000000..1137eb8 --- /dev/null +++ b/.vim/colors/wombat256mod.vim @@ -0,0 +1,96 @@ +" Vim color file +" Original Maintainer: Lars H. Nielsen ([email protected]) +" Last Change: 2010-07-23 +" +" Modified version of wombat for 256-color terminals by +" David Liang ([email protected]) +" based on version by +" Danila Bespalov ([email protected]) + +set background=dark + +if version > 580 + hi clear + if exists("syntax_on") + syntax reset + endif +endif + +let colors_name = "wombat256mod" + + +" General colors +hi Normal ctermfg=252 ctermbg=234 cterm=none guifg=#e3e0d7 guibg=#242424 gui=none +hi Cursor ctermfg=234 ctermbg=228 cterm=none guifg=#242424 guibg=#eae788 gui=none +hi Visual ctermfg=251 ctermbg=239 cterm=none guifg=#c3c6ca guibg=#554d4b gui=none +hi VisualNOS ctermfg=251 ctermbg=236 cterm=none guifg=#c3c6ca guibg=#303030 gui=none +hi Search ctermfg=177 ctermbg=241 cterm=none guifg=#d787ff guibg=#636066 gui=none +hi Folded ctermfg=103 ctermbg=237 cterm=none guifg=#a0a8b0 guibg=#3a4046 gui=none +hi Title ctermfg=230 cterm=bold guifg=#ffffd7 gui=bold +hi StatusLine ctermfg=230 ctermbg=238 cterm=none guifg=#ffffd7 guibg=#444444 gui=italic +hi VertSplit ctermfg=238 ctermbg=238 cterm=none guifg=#444444 guibg=#444444 gui=none +hi StatusLineNC ctermfg=241 ctermbg=238 cterm=none guifg=#857b6f guibg=#444444 gui=none +hi LineNr ctermfg=241 ctermbg=232 cterm=none guifg=#857b6f guibg=#080808 gui=none +hi SpecialKey ctermfg=241 ctermbg=235 cterm=none guifg=#626262 guibg=#2b2b2b gui=none +hi WarningMsg ctermfg=203 guifg=#ff5f55 +hi ErrorMsg ctermfg=196 ctermbg=236 cterm=bold guifg=#ff2026 guibg=#3a3a3a gui=bold + +" Vim >= 7.0 specific colors +if version >= 700 +hi CursorLine ctermbg=236 cterm=none guibg=#32322f +hi MatchParen ctermfg=228 ctermbg=101 cterm=bold guifg=#eae788 guibg=#857b6f gui=bold +hi Pmenu ctermfg=230 ctermbg=238 guifg=#ffffd7 guibg=#444444 +hi PmenuSel ctermfg=232 ctermbg=192 guifg=#080808 guibg=#cae982 +endif + +" Diff highlighting +hi DiffAdd ctermbg=17 guibg=#2a0d6a +hi DiffDelete ctermfg=234 ctermbg=60 cterm=none guifg=#242424 guibg=#3e3969 gui=none +hi DiffText ctermbg=53 cterm=none guibg=#73186e gui=none +hi DiffChange ctermbg=237 guibg=#382a37 + +"hi CursorIM +"hi Directory +"hi IncSearch +"hi Menu +"hi ModeMsg +"hi MoreMsg +"hi PmenuSbar +"hi PmenuThumb +"hi Question +"hi Scrollbar +"hi SignColumn +"hi SpellBad +"hi SpellCap +"hi SpellLocal +"hi SpellRare +"hi TabLine +"hi TabLineFill +"hi TabLineSel +"hi Tooltip +"hi User1 +"hi User9 +"hi WildMenu + + +" Syntax highlighting +hi Keyword ctermfg=111 cterm=none guifg=#88b8f6 gui=none +hi Statement ctermfg=111 cterm=none guifg=#88b8f6 gui=none +hi Constant ctermfg=173 cterm=none guifg=#e5786d gui=none +hi Number ctermfg=173 cterm=none guifg=#e5786d gui=none +hi PreProc ctermfg=173 cterm=none guifg=#e5786d gui=none +hi Function ctermfg=192 cterm=none guifg=#cae982 gui=none +hi Identifier ctermfg=192 cterm=none guifg=#cae982 gui=none +hi Type ctermfg=186 cterm=none guifg=#d4d987 gui=none +hi Special ctermfg=229 cterm=none guifg=#eadead gui=none +hi String ctermfg=113 cterm=none guifg=#95e454 gui=italic +hi Comment ctermfg=246 cterm=none guifg=#9c998e gui=italic +hi Todo ctermfg=101 cterm=none guifg=#857b6f gui=italic + + +" Links +hi! link FoldColumn Folded +hi! link CursorColumn CursorLine +hi! link NonText LineNr + +" vim:set ts=4 sw=4 noet: diff --git a/.vim/colors/xoria256.vim b/.vim/colors/xoria256.vim new file mode 100644 index 0000000..7d1010b --- /dev/null +++ b/.vim/colors/xoria256.vim @@ -0,0 +1,142 @@ +" Vim color file +" +" Name: xoria256.vim +" Version: 1.5 +" Maintainer: Dmitriy Y. Zotikov (xio) <[email protected]> +" +" Should work in recent 256 color terminals. 88-color terms like urxvt are +" NOT supported. +" +" Don't forget to install 'ncurses-term' and set TERM to xterm-256color or +" similar value. +" +" Color numbers (0-255) see: +" http://www.calmar.ws/vim/256-xterm-24bit-rgb-color-chart.html +" +" For a specific filetype highlighting rules issue :syntax list when a file of +" that type is opened. + +" Initialization {{{ +if &t_Co != 256 && ! has("gui_running") + echomsg "" + echomsg "err: please use GUI or a 256-color terminal (so that t_Co=256 could be set)" + echomsg "" + finish +endif + +set background=dark + +hi clear + +if exists("syntax_on") + syntax reset +endif + +let colors_name = "xoria256" +"}}} +" Colours {{{1 +"" General {{{2 +hi Normal ctermfg=252 guifg=#d0d0d0 ctermbg=234 guibg=#1c1c1c cterm=none gui=none +hi Cursor ctermbg=214 guibg=#ffaf00 +hi CursorColumn ctermbg=238 guibg=#444444 +hi CursorLine ctermbg=237 guibg=#3a3a3a cterm=none gui=none +hi Error ctermfg=15 guifg=#ffffff ctermbg=1 guibg=#800000 +hi ErrorMsg ctermfg=15 guifg=#ffffff ctermbg=1 guibg=#800000 +hi FoldColumn ctermfg=247 guifg=#9e9e9e ctermbg=233 guibg=#121212 +hi Folded ctermfg=255 guifg=#eeeeee ctermbg=60 guibg=#5f5f87 +hi IncSearch ctermfg=0 guifg=#000000 ctermbg=223 guibg=#ffdfaf cterm=none gui=none +hi LineNr ctermfg=247 guifg=#9e9e9e ctermbg=233 guibg=#121212 +hi MatchParen ctermfg=188 guifg=#dfdfdf ctermbg=68 guibg=#5f87df cterm=bold gui=bold +" TODO +" hi MoreMsg +hi NonText ctermfg=247 guifg=#9e9e9e ctermbg=233 guibg=#121212 cterm=bold gui=bold +hi Pmenu ctermfg=0 guifg=#000000 ctermbg=250 guibg=#bcbcbc +hi PmenuSel ctermfg=255 guifg=#eeeeee ctermbg=243 guibg=#767676 +hi PmenuSbar ctermbg=252 guibg=#d0d0d0 +hi PmenuThumb ctermfg=243 guifg=#767676 +hi Search ctermfg=0 guifg=#000000 ctermbg=149 guibg=#afdf5f +hi SignColumn ctermfg=248 guifg=#a8a8a8 +hi SpecialKey ctermfg=77 guifg=#5fdf5f +hi SpellBad ctermfg=160 guifg=fg ctermbg=bg cterm=underline guisp=#df0000 +hi SpellCap ctermfg=189 guifg=#dfdfff ctermbg=bg guibg=bg cterm=underline gui=underline +hi SpellRare ctermfg=168 guifg=#df5f87 ctermbg=bg guibg=bg cterm=underline gui=underline +hi SpellLocal ctermfg=98 guifg=#875fdf ctermbg=bg guibg=bg cterm=underline gui=underline +hi StatusLine ctermfg=15 guifg=#ffffff ctermbg=239 guibg=#4e4e4e cterm=bold gui=bold +hi StatusLineNC ctermfg=249 guifg=#b2b2b2 ctermbg=237 guibg=#3a3a3a cterm=none gui=none +hi TabLine ctermfg=fg guifg=fg ctermbg=242 guibg=#666666 cterm=none gui=none +hi TabLineFill ctermfg=fg guifg=fg ctermbg=237 guibg=#3a3a3a cterm=none gui=none +" FIXME +hi Title ctermfg=225 guifg=#ffdfff +hi Todo ctermfg=0 guifg=#000000 ctermbg=184 guibg=#dfdf00 +hi Underlined ctermfg=39 guifg=#00afff cterm=underline gui=underline +hi VertSplit ctermfg=237 guifg=#3a3a3a ctermbg=237 guibg=#3a3a3a cterm=none gui=none +" hi VIsualNOS ctermfg=24 guifg=#005f87 ctermbg=153 guibg=#afdfff cterm=none gui=none +" hi Visual ctermfg=24 guifg=#005f87 ctermbg=153 guibg=#afdfff +hi Visual ctermfg=255 guifg=#eeeeee ctermbg=96 guibg=#875f87 +" hi Visual ctermfg=255 guifg=#eeeeee ctermbg=24 guibg=#005f87 +hi VisualNOS ctermfg=255 guifg=#eeeeee ctermbg=60 guibg=#5f5f87 +hi WildMenu ctermfg=0 guifg=#000000 ctermbg=150 guibg=#afdf87 cterm=bold gui=bold + +"" Syntax highlighting {{{2 +hi Comment ctermfg=244 guifg=#808080 +hi Constant ctermfg=229 guifg=#ffffaf +hi Identifier ctermfg=182 guifg=#dfafdf cterm=none +hi Ignore ctermfg=238 guifg=#444444 +hi Number ctermfg=180 guifg=#dfaf87 +hi PreProc ctermfg=150 guifg=#afdf87 +hi Special ctermfg=174 guifg=#df8787 +hi Statement ctermfg=110 guifg=#87afdf cterm=none gui=none +hi Type ctermfg=146 guifg=#afafdf cterm=none gui=none + +"" Special {{{2 +""" .diff {{{3 +hi diffAdded ctermfg=150 guifg=#afdf87 +hi diffRemoved ctermfg=174 guifg=#df8787 +""" vimdiff {{{3 +hi diffAdd ctermfg=bg guifg=bg ctermbg=151 guibg=#afdfaf +"hi diffDelete ctermfg=bg guifg=bg ctermbg=186 guibg=#dfdf87 cterm=none gui=none +hi diffDelete ctermfg=bg guifg=bg ctermbg=246 guibg=#949494 cterm=none gui=none +hi diffChange ctermfg=bg guifg=bg ctermbg=181 guibg=#dfafaf +hi diffText ctermfg=bg guifg=bg ctermbg=174 guibg=#df8787 cterm=none gui=none +""" HTML {{{3 +" hi htmlTag ctermfg=146 guifg=#afafdf +" hi htmlEndTag ctermfg=146 guifg=#afafdf +hi htmlTag ctermfg=244 +hi htmlEndTag ctermfg=244 +hi htmlArg ctermfg=182 guifg=#dfafdf +hi htmlValue ctermfg=187 guifg=#dfdfaf +hi htmlTitle ctermfg=254 ctermbg=95 +" hi htmlArg ctermfg=146 +" hi htmlTagName ctermfg=146 +" hi htmlString ctermfg=187 +""" django {{{3 +hi djangoVarBlock ctermfg=180 +hi djangoTagBlock ctermfg=150 +hi djangoStatement ctermfg=146 +hi djangoFilter ctermfg=174 +""" python {{{3 +hi pythonExceptions ctermfg=174 +""" NERDTree {{{3 +hi Directory ctermfg=110 guifg=#87afdf +hi treeCWD ctermfg=180 guifg=#dfaf87 +hi treeClosable ctermfg=174 guifg=#df8787 +hi treeOpenable ctermfg=150 guifg=#afdf87 +hi treePart ctermfg=244 guifg=#808080 +hi treeDirSlash ctermfg=244 guifg=#808080 +hi treeLink ctermfg=182 guifg=#dfafdf + +""" VimDebug {{{3 +" FIXME +" you may want to set SignColumn highlight in your .vimrc +" :help sign +" :help SignColumn + +" hi currentLine term=reverse cterm=reverse gui=reverse +" hi breakPoint term=NONE cterm=NONE gui=NONE +" hi empty term=NONE cterm=NONE gui=NONE + +" sign define currentLine linehl=currentLine +" sign define breakPoint linehl=breakPoint text=>> +" sign define both linehl=currentLine text=>> +" sign define empty linehl=empty + diff --git a/.vim/colors/zenesque.vim b/.vim/colors/zenesque.vim new file mode 100644 index 0000000..9789aad --- /dev/null +++ b/.vim/colors/zenesque.vim @@ -0,0 +1,384 @@ +" ============================================================================= +" File: zenesque.vim +" Description: Vim color scheme file +" Maintainer: Paul L +" ============================================================================= +set background=light +highlight clear +if exists("syntax_on") + syntax reset +endif +let colors_name = "zenesque" +" ============================================================================= + +" default scheme + +hi Normal guifg=#000000 guibg=#e0e0d8 gui=NONE +hi CursorLine guifg=NONE guibg=#e1e1d0 gui=NONE +hi CursorColumn guifg=NONE guibg=#e1e1d0 gui=NONE +hi LineNr guifg=#a9a99e guibg=NONE gui=NONE +hi Constant guifg=#353535 guibg=NONE gui=bold +hi Statement guifg=#363636 guibg=NONE gui=italic +hi Function guifg=fg guibg=NONE gui=bold +hi String guifg=#3c3c3c guibg=NONE gui=NONE +hi Type guifg=#616161 guibg=NONE gui=bold,italic +hi Conditional guifg=#4d4d4d guibg=NONE gui=bold +hi Todo guifg=fg guibg=NONE gui=bold,underline +hi Comment guifg=#797979 guibg=NONE gui=italic +hi PmenuSel guifg=fg guibg=#a9a9aa gui=bold +hi ColorColumn guifg=NONE guibg=#e6e6e6 +hi Cursor guifg=bg guibg=fg gui=NONE +hi CursorIM guifg=bg guibg=fg gui=NONE +hi lCursor guifg=bg guibg=fg gui=NONE +hi DiffAdd guifg=NONE guibg=#d1d1d1 gui=NONE +hi DiffChange guifg=NONE guibg=#9d9d9d gui=NONE +hi DiffDelete guifg=NONE guibg=#949494 gui=NONE +hi DiffText guifg=#000000 guibg=#bababa gui=bold +hi Directory guifg=#525252 guibg=bg gui=NONE +hi ErrorMsg guifg=#6f6f6f guibg=NONE gui=NONE +hi FoldColumn guifg=#555555 guibg=#cccbcb gui=bold +hi Folded guifg=#555555 guibg=#cccccc gui=italic + +hi IncSearch guifg=#000000 guibg=#adadad gui=NONE +hi Search guifg=#000000 guibg=#c5c3c3 gui=NONE +hi MatchParen guifg=#000000 guibg=#a8a8a8 gui=bold +hi ModeMsg guifg=#ffffff guibg=#767676 gui=bold +hi MoreMsg guifg=#7c7c7c guibg=bg gui=bold +hi NonText guifg=#7e7e7e guibg=bg gui=bold + +hi Pmenu guifg=#646564 guibg=#b1b2b1 gui=reverse +hi PmenuSbar guifg=#ffffff guibg=#989898 gui=NONE +hi PmenuThumb guifg=#ffffff guibg=#777777 gui=NONE + +hi Question guifg=#454545 guibg=bg gui=bold +hi SignColumn guifg=#ffffff guibg=#696969 gui=NONE + +hi SpecialKey guifg=#ffffff guibg=#696969 gui=NONE + +hi SpellBad guisp=#323232 guibg=#d1cdcd gui=undercurl +hi SpellCap guisp=#5d5d5d gui=undercurl +hi SpellLocal guisp=#434343 gui=undercurl +hi SpellRare guisp=#7d7d7d gui=undercurl +hi StatusLine guifg=#e8e8e8 guibg=#858585 gui=bold +hi StatusLineNC guifg=#808080 guibg=#bbbbbb gui=italic +hi TabLine guifg=fg guibg=#898a8b gui=underline +hi TabLineFill guifg=fg guibg=bg gui=reverse +hi TabLineSel guifg=fg guibg=bg gui=bold +hi Title guifg=#6d6d6d guibg=bg gui=bold +hi VertSplit guifg=#b9b9b9 guibg=#b9b9b9 +hi Visual guifg=#ffffff guibg=#9a9a9a gui=NONE +hi WarningMsg guifg=#cfcfcf guibg=#5b5b5b gui=NONE +hi WildMenu guifg=#000000 guibg=#c2c2c2 gui=NONE + +hi Boolean guifg=#616060 guibg=NONE gui=bold +hi Identifier guifg=#141414 guibg=NONE gui=bold +hi Keyword guifg=#666666 guibg=NONE gui=underline +hi PreProc guifg=#6b6b6b guibg=NONE gui=NONE +hi Special guifg=#6e6e6e guibg=NONE gui=NONE +hi Ignore guifg=bg guibg=NONE gui=NONE +hi Error guifg=#727272 guibg=NONE gui=undercurl +" ----------------------------------------------------------------------------- +hi VimError guifg=#b6b6b6 guibg=#313131 gui=bold +hi VimCommentTitle guifg=#5c5c5c guibg=bg gui=bold,italic +hi qfFileName guifg=#6a6a6a guibg=NONE gui=italic +hi qfLineNr guifg=fg guibg=NONE gui=NONE +hi qfError guifg=fg guibg=#c4c2c2 gui=undercurl + +" ----------------------------------------------------------------------------- +hi pythonDecorator guifg=#3b3b3b guibg=NONE gui=bold +hi link pythonDecoratorFunction pythonDecorator + +" ----------------------------------------------------------------------------- +hi htmlLink guifg=#666666 guibg=NONE gui=underline,italic + +if exists('g:zenesque_colors') && g:zenesque_colors==1 + " light scheme with colors + + hi Normal guifg=#0b092c guibg=#e5e5d8 gui=NONE + hi CursorLine guifg=NONE guibg=#d4d4c0 gui=NONE + hi CursorColumn guifg=NONE guibg=#d4d4c0 gui=NONE + hi LineNr guifg=#888875 guibg=NONE gui=NONE + hi Constant guifg=#73221A guibg=NONE gui=NONE + hi String guifg=#073010 guibg=NONE gui=NONE + hi Function guifg=#3b1c5b guibg=NONE gui=bold + hi Statement guifg=#100051 guibg=NONE gui=italic + hi Conditional guifg=#6e220e guibg=NONE gui=NONE + hi Type guifg=#421b4d guibg=NONE gui=italic + hi Todo guifg=#6c0303 guibg=NONE gui=NONE + hi Comment guifg=#6e6e6e guibg=NONE gui=italic + hi PmenuSel guifg=fg guibg=#c37a23 gui=bold + hi ColorColumn guifg=NONE guibg=#e6e6e6 + hi Cursor guifg=bg guibg=fg gui=NONE + hi CursorIM guifg=bg guibg=fg gui=NONE + hi lCursor guifg=bg guibg=fg gui=NONE + + hi diffAdd guifg=bg guibg=#5a7e5d gui=none + hi diffDelete guifg=#bf6a6a guibg=#3d2424 gui=none + hi diffChange guifg=bg guibg=#b55c5c gui=none + hi diffText guifg=bg guibg=#264928 gui=none + + hi Directory guifg=#525252 guibg=bg gui=NONE + hi ErrorMsg guifg=#6f6f6f guibg=NONE gui=NONE + hi FoldColumn guifg=#555555 guibg=#cccbcb gui=bold + hi Folded guifg=#555555 guibg=#cccccc gui=italic + + hi IncSearch guifg=#000000 guibg=#adadad gui=NONE + hi Search guifg=#000000 guibg=#c5c3c3 gui=NONE + hi MatchParen guifg=#000000 guibg=#a8a8a8 gui=bold + hi ModeMsg guifg=#ffffff guibg=#767676 gui=bold + hi MoreMsg guifg=#7c7c7c guibg=bg gui=bold + hi NonText guifg=#7e7e7e guibg=bg gui=bold + + hi Pmenu guifg=#646564 guibg=#b1b2b1 gui=reverse + hi PmenuSbar guifg=#ffffff guibg=#989898 gui=NONE + hi PmenuThumb guifg=#ffffff guibg=#777777 gui=NONE + + hi Question guifg=#454545 guibg=bg gui=bold + hi SignColumn guifg=#ffffff guibg=#696969 gui=NONE + + hi SpecialKey guifg=#ffffff guibg=#696969 gui=NONE + + hi SpellBad guisp=#323232 guibg=#d1cdcd gui=undercurl + hi SpellCap guisp=#5d5d5d gui=undercurl + hi SpellLocal guisp=#434343 gui=undercurl + hi SpellRare guisp=#7d7d7d gui=undercurl + hi StatusLine guifg=fg guibg=#c0bebe gui=bold + hi StatusLineNC guifg=#808080 guibg=#c5c5af gui=italic + hi TabLine guifg=fg guibg=#898a8b gui=underline + hi TabLineFill guifg=fg guibg=bg gui=reverse + hi TabLineSel guifg=fg guibg=bg gui=bold + hi Title guifg=#6d6d6d guibg=bg gui=bold + hi VertSplit guifg=#c5c5af guibg=#c5c5af + hi Visual guifg=#ffffff guibg=#9a9a9a gui=NONE + hi WarningMsg guifg=#cfcfcf guibg=#5b5b5b gui=NONE + hi WildMenu guifg=#000000 guibg=#c2c2c2 gui=NONE + hi Boolean guifg=#616060 guibg=NONE gui=bold + hi Identifier guifg=#141414 guibg=NONE gui=bold + hi Keyword guifg=#666666 guibg=NONE gui=underline + hi PreProc guifg=#272c61 guibg=NONE gui=NONE + hi Special guifg=#6e6e6e guibg=NONE gui=NONE + hi Ignore guifg=bg guibg=NONE gui=NONE + hi Error guifg=#727272 guibg=NONE gui=undercurl + " ----------------------------------------------------------------------------- +hi VimError guifg=#b6b6b6 guibg=#313131 gui=bold +hi VimCommentTitle guifg=#5c5c5c guibg=bg gui=bold,italic +hi qfFileName guifg=#6a6a6a guibg=NONE gui=italic +hi qfLineNr guifg=fg guibg=NONE gui=NONE +hi qfError guifg=fg guibg=#c4c2c2 gui=undercurl + +" ----------------------------------------------------------------------------- +hi pythonDecorator guifg=#3b3b3b guibg=NONE gui=bold +hi link pythonDecoratorFunction pythonDecorator +" ----------------------------------------------------------------------------- +hi htmlLink guifg=#666666 guibg=NONE gui=underline,italic +elseif exists('g:zenesque_colors') && g:zenesque_colors==2 + " dark scheme without colors + + set background=dark + + hi Normal guifg=#adadad guibg=#1a1a1a gui=NONE + hi CursorLine guifg=NONE guibg=#000000 gui=NONE + hi CursorColumn guifg=NONE guibg=#000000 gui=NONE + hi LineNr guifg=#555555 guibg=NONE gui=NONE + hi Constant guifg=#848484 guibg=NONE gui=bold + hi Statement guifg=#a6a6a6 guibg=NONE gui=italic + hi Function guifg=#919191 guibg=NONE gui=bold + hi String guifg=#838383 guibg=NONE gui=italic + hi Type guifg=#838383 guibg=NONE gui=bold,italic + hi Conditional guifg=#787878 guibg=NONE gui=bold + hi Todo guifg=#ffffff guibg=NONE gui=underline + hi Comment guifg=#555555 guibg=NONE gui=NONE + hi PmenuSel guifg=#000000 guibg=#a9a9aa gui=bold + hi Special guifg=#868585 guibg=NONE gui=NONE + hi Identifier guifg=#626262 guibg=NONE gui=bold + hi Keyword guifg=#858585 guibg=NONE gui=underline + hi PreProc guifg=#6b6b6b guibg=NONE gui=italic + + + hi Visual guifg=NONE guibg=#313131 gui=NONE + hi ColorColumn guifg=NONE guibg=#e6e6e6 + hi Cursor guifg=bg guibg=fg gui=NONE + hi CursorIM guifg=bg guibg=fg gui=NONE + hi lCursor guifg=bg guibg=fg gui=NONE + + hi DiffAdd guifg=fg guibg=#444444 gui=NONE + hi DiffChange guifg=bg guibg=#909090 gui=NONE + hi DiffDelete guifg=NONE guibg=#292929 gui=NONE + hi DiffText guifg=NONE guibg=#383838 gui=NONE + + hi Directory guifg=#525252 guibg=bg gui=NONE + hi ErrorMsg guifg=#6f6f6f guibg=NONE gui=NONE + hi FoldColumn guifg=#555555 guibg=#414141 gui=bold + hi Folded guifg=#828282 guibg=#212121 gui=italic + + hi IncSearch guifg=#000000 guibg=#adadad gui=NONE + hi Search guifg=#000000 guibg=#c5c3c3 gui=NONE + hi MatchParen guifg=#000000 guibg=#a8a8a8 gui=bold + hi ModeMsg guifg=#ffffff guibg=#767676 gui=bold + hi MoreMsg guifg=#7c7c7c guibg=bg gui=bold + hi NonText guifg=#7e7e7e guibg=bg gui=bold + + hi Pmenu guifg=#656565 guibg=#3f3f3f gui=NONE + hi PmenuSbar guifg=fg guibg=#5d5d5d gui=NONE + hi PmenuThumb guifg=fg guibg=#777777 gui=NONE + + hi Question guifg=#454545 guibg=bg gui=bold + hi SignColumn guifg=#ffffff guibg=#696969 gui=NONE + + hi SpecialKey guifg=#ffffff guibg=#696969 gui=NONE + + hi SpellBad guisp=#ffffff guibg=#000000 gui=undercurl + hi SpellCap guisp=#5d5d5d gui=undercurl + hi SpellLocal guisp=#434343 gui=undercurl + hi SpellRare guisp=#7d7d7d gui=undercurl + hi StatusLine guifg=#000000 guibg=#727272 gui=bold + hi StatusLineNC guifg=#5a5959 guibg=#222222 gui=italic + hi TabLine guifg=fg guibg=#757575 gui=underline + hi TabLineFill guifg=fg guibg=bg gui=reverse + hi TabLineSel guifg=fg guibg=bg gui=bold + hi Title guifg=#6d6d6d guibg=bg gui=bold + hi VertSplit guifg=#222222 guibg=#222222 + hi WarningMsg guifg=#cfcfcf guibg=#5b5b5b gui=NONE + hi WildMenu guifg=#000000 guibg=#828282 gui=NONE + hi Boolean guifg=#616060 guibg=NONE gui=bold + hi Ignore guifg=bg guibg=NONE gui=NONE + hi Error guifg=#727272 guibg=NONE gui=undercurl + " ----------------------------------------------------------------------------- + hi VimError guifg=#b6b6b6 guibg=#313131 gui=bold + hi VimCommentTitle guifg=#5c5c5c guibg=bg gui=bold,italic + hi qfFileName guifg=#6a6a6a guibg=NONE gui=italic + hi qfLineNr guifg=fg guibg=NONE gui=NONE + hi qfError guifg=fg guibg=#000000 gui=undercurl + + " ----------------------------------------------------------------------------- + hi pythonDecorator guifg=#3b3b3b guibg=NONE gui=bold + hi link pythonDecoratorFunction pythonDecorator + " ----------------------------------------------------------------------------- + hi htmlLink guifg=#666666 guibg=NONE gui=underline,italic + +elseif exists('g:zenesque_colors') && g:zenesque_colors==3 + " dark scheme with colors + + set background=dark + + hi Normal guifg=#adadad guibg=#0f1216 gui=NONE + hi CursorLine guifg=NONE guibg=#000000 gui=NONE + hi CursorColumn guifg=NONE guibg=#000000 gui=NONE + hi LineNr guifg=#4d4d44 guibg=NONE gui=NONE + hi Constant guifg=#8d5c57 guibg=NONE gui=NONE + hi String guifg=#5d7a64 guibg=NONE gui=NONE + hi Function guifg=#9784a2 guibg=NONE gui=NONE + hi Statement guifg=#5a89a4 guibg=NONE gui=italic + hi Conditional guifg=#8c7867 guibg=NONE gui=NONE + hi Type guifg=#518991 guibg=NONE gui=italic + hi Todo guifg=#9b3535 guibg=NONE gui=NONE + hi Comment guifg=#777777 guibg=NONE gui=NONE + hi PmenuSel guifg=bg guibg=#9b601a gui=bold + hi Special guifg=#a7a863 guibg=NONE gui=NONE + hi Identifier guifg=#a16f51 guibg=NONE gui=NONE + hi Keyword guifg=#737354 guibg=NONE gui=underline + hi PreProc guifg=#5567a1 guibg=NONE gui=NONE + hi Visual guifg=NONE guibg=#462e44 gui=NONE + hi ColorColumn guifg=NONE guibg=#e6e6e6 + hi Cursor guifg=bg guibg=fg gui=NONE + hi CursorIM guifg=bg guibg=fg gui=NONE + hi lCursor guifg=bg guibg=fg gui=NONE + hi diffAdd guifg=bg guibg=#5a7e5d gui=none + hi diffDelete guifg=#bf6a6a guibg=#2d1212 gui=none + hi diffChange guifg=bg guibg=#7e4444 gui=none + hi diffText guifg=bg guibg=#345535 gui=none + + + hi Directory guifg=#525252 guibg=bg gui=NONE + hi ErrorMsg guifg=#6f6f6f guibg=NONE gui=NONE + hi FoldColumn guifg=#555555 guibg=#414141 gui=bold + hi Folded guifg=#828282 guibg=#212121 gui=italic + + hi IncSearch guifg=#000000 guibg=#adadad gui=NONE + hi Search guifg=#000000 guibg=#c5c3c3 gui=NONE + hi MatchParen guifg=#000000 guibg=#a8a8a8 gui=bold + hi ModeMsg guifg=#ffffff guibg=#767676 gui=bold + hi MoreMsg guifg=#7c7c7c guibg=bg gui=bold + hi NonText guifg=#7e7e7e guibg=bg gui=bold + + hi Pmenu guifg=#656565 guibg=#3f3f3f gui=NONE + hi PmenuSbar guifg=fg guibg=#5d5d5d gui=NONE + hi PmenuThumb guifg=fg guibg=#777777 gui=NONE + + hi Question guifg=#454545 guibg=bg gui=bold + hi SignColumn guifg=#ffffff guibg=#696969 gui=NONE + + hi SpecialKey guifg=#ffffff guibg=#696969 gui=NONE + + hi SpellBad guisp=#ffffff guibg=#000000 gui=undercurl + hi SpellCap guisp=#5d5d5d gui=undercurl + hi SpellLocal guisp=#434343 gui=undercurl + hi SpellRare guisp=#7d7d7d gui=undercurl + hi StatusLine guifg=#000000 guibg=#727272 gui=bold + hi StatusLineNC guifg=#5a5959 guibg=#222222 gui=italic + hi TabLine guifg=fg guibg=#5f5f5f gui=underline + hi TabLineFill guifg=fg guibg=bg gui=reverse + hi TabLineSel guifg=fg guibg=bg gui=bold + hi Title guifg=#6d6d6d guibg=bg gui=bold + hi VertSplit guifg=#222222 guibg=#222222 + hi WarningMsg guifg=#cfcfcf guibg=#5b5b5b gui=NONE + hi WildMenu guifg=#000000 guibg=#828282 gui=NONE + hi Boolean guifg=#616060 guibg=NONE gui=bold + hi Ignore guifg=bg guibg=NONE gui=NONE + hi Error guifg=#727272 guibg=NONE gui=undercurl + " ----------------------------------------------------------------------------- + hi VimError guifg=#b6b6b6 guibg=#313131 gui=bold + hi VimCommentTitle guifg=#5c5c5c guibg=bg gui=bold,italic + hi qfFileName guifg=#6a6a6a guibg=NONE gui=italic + hi qfLineNr guifg=fg guibg=NONE gui=NONE + hi qfError guifg=fg guibg=#000000 gui=undercurl + + " ----------------------------------------------------------------------------- + hi pythonDecorator guifg=#3b3b3b guibg=NONE gui=bold + hi link pythonDecoratorFunction pythonDecorator + " ----------------------------------------------------------------------------- + hi htmlLink guifg=#666666 guibg=NONE gui=underline,italic +endif + +hi htmlTagName guifg=NONE guibg=NONE gui=NONE +hi link htmlScriptTag htmlTagName +hi link htmlTagN htmlTagName +hi link htmlEndTag htmlTagName +hi link htmlSpecialTagName htmlTagName + +hi link cssRenderAttr Constant +hi link cssTextAttr Constant +hi link cssUIAttr Constant +hi link cssTableAttr Constant +hi link cssColorAttr Constant +hi link cssBoxAttr Constant +hi link cssCommonAttr Constant +hi link cssFunctionName Constant +hi link cssRenderProp Type +hi link cssBoxProp cssRenderProp + +hi link cssTagName Statement +hi link cssClassName cssTagName +hi link cssIdentifier cssTagName +hi link cssPseudoClass cssTagName +hi link cssPseudoClassId cssTagName + +hi cssBraces guifg=fg guibg=bg gui=NONE +hi javaScript guifg=fg guibg=NONE +hi link javaScriptFunction Statement +hi link javaScriptMember Statement +hi link javaScriptValue Constant + +hi link objcClass Type +hi link cocoaClass objcClass +hi link objcSubclass objcClass +hi link objcSuperclass objcClass +hi link cocoaFunction Function +hi link objcMethodName Identifier +hi link objcMethodArg Normal +hi link objcMessageName Identifier + +hi link javaType Statement +hi link cppStatement Statement + + diff --git a/.vim/etc/lazy.toml b/.vim/etc/lazy.toml new file mode 100644 index 0000000..06ca9f9 --- /dev/null +++ b/.vim/etc/lazy.toml @@ -0,0 +1,158 @@ +[[plugins]] +repo = 'groenewege/vim-less' +on_ft = ['less'] + +[[plugins]] +repo = 'hail2u/vim-css3-syntax' +on_ft = ['css'] + +[[plugins]] +repo = 'hallison/vim-markdown' +on_ft = ['markdown'] + +[[plugins]] +repo = 'motemen/hatena-vim' +on_ft = ['hatena'] + +[[plugins]] +repo = 'othree/html5.vim' +on_ft = ['html'] + +[[plugins]] +repo = 'pangloss/vim-javascript' +on_ft = ['typescript', 'javascript'] + +[[plugins]] +repo = 'MaxMEllon/vim-jsx-pretty' +on_ft = ['javascript'] + +[[plugins]] +repo = 'vim-perl/vim-perl' +on_ft = ['perl'] +hook_add = ''' +let g:perl_fold = 0 +''' + +[[plugins]] +repo = 'vim-ruby/vim-ruby' +on_ft = ['ruby'] + +[[plugins]] +repo = 'davidoc/taskpaper.vim' +on_ft = ['taskpaper'] + +[[plugins]] +repo = 'motemen/tap-vim' +on_ft = ['perl'] +hook_add = ''' +let g:tap#use_vimproc = 1 +''' + +[[plugins]] +repo = 'eagletmt/ghcmod-vim' +external_commands = 'ghc-mod' +on_ft = ['haskell'] + +[[plugins]] +repo = 'eagletmt/ghci-vim' +external_commands = ['ghc'] +on_ft = ['haskell'] + +[[plugins]] +repo = 'eagletmt/neco-ghc' +on_ft = ['haskell'] +external_commands = ['ghc', 'ghc-mod'] + +[[plugins]] +repo = 'itchyny/vim-haskell-indent' +on_ft = ['haskell'] + +[[plugins]] +repo = 'ekalinin/Dockerfile.vim' +on_ft = 'dockerfile' + +[[plugins]] +repo = 'leafgarland/typescript-vim' +on_ft = ['typescript'] + +[[plugins]] +repo = 'Quramy/tsuquyomi' +on_ft = ['typescript'] + +[[plugins]] +repo = 'keith/swift.vim' +on_ft = ['swift'] + +[[plugins]] +repo = 'derekwyatt/vim-scala' +on_ft = ['scala'] + +[[plugins]] +repo = 'mattn/emmet-vim' +on_ft = ['html', 'haml', 'slim', 'css', 'tt2html'] +hook_add = ''' +let g:user_emmet_leader_key = '<C-e>' +''' + +[[plugins]] +repo = 'vim-scripts/sudo.vim' +on_cmd = ['SudoWrite', 'SudoRead'] + +[[plugins]] +repo = 'haya14busa/incsearch.vim' +on_map = ['<Plug>'] +hook_add = ''' +let g:incsearch#auto_nohlsearch = 1 +map / <Plug>(incsearch-forward) +map ? <Plug>(incsearch-backward) +map g/ <Plug>(incsearch-stay) + +map n <Plug>(incsearch-nohl-n) +map N <Plug>(incsearch-nohl-N) +nmap n <Plug>(incsearch-nohl)<Plug>(anzu-n-with-echo) +nmap N <Plug>(incsearch-nohl)<Plug>(anzu-N-with-echo) +''' + +[[plugins]] +repo = 'h1mesuke/vim-alignta' +on_cmd = ['Alignta'] +hook_add = ''' +vmap ,a :Alignta +vmap ,= :Alignta =<CR> +vmap ,> :Alignta =><CR> +''' + +[[plugins]] +repo = 'cespare/vim-toml' +on_ft = ['toml'] + +[[plugins]] +repo = 'motemen/xslate-vim' +on_ft = ['xslate'] + +[[plugins]] +repo = 'Shougo/neomru.vim' +if = '!has("nvim")' +on_unite = ['file_mru'] +hook_source = ''' +call unite#custom#source( + \ 'file_mru', 'matchers', + \ ['matcher_project_files', 'matcher_fuzzy'], + \ ) +''' + + +[[plugins]] +repo = 'subosito/nginx.vim' +on_ft = ['nginx'] + +[[plugins]] +repo = 'fatih/vim-go' +on_ft = ['go'] + +[[plugins]] +repo = 'flowtype/vim-flow' +on_ft = ['javascript'] +hook_add = ''' +let g:flow#autoclose = 1 +''' diff --git a/.vim/etc/operator.toml b/.vim/etc/operator.toml new file mode 100644 index 0000000..121f5e2 --- /dev/null +++ b/.vim/etc/operator.toml @@ -0,0 +1,22 @@ +[[plugins]] +repo = 'rhysd/vim-operator-surround' +on_map = ['<Plug>(operator-surround-'] +depends = ['vim-operator-user'] +hook_add = ''' +map <silent> sa <Plug>(operator-surround-append) +map <silent> sd <Plug>(operator-surround-delete) +map <silent> sr <Plug>(operator-surround-replace) +''' + +[[plugins]] +repo = 'haya14busa/vim-operator-flashy' +on_map = ['<Plug>(operator-flashy'] +depends = ['vim-operator-user'] +hook_add = ''' +map y <Plug>(operator-flashy) +nmap Y <Plug>(operator-flashy)$ +''' + +[[plugins]] +repo = 'emonkak/vim-operator-comment' +on_map = ['<Plug>(operator-comment)', '<Plug>(operator-uncomment)'] diff --git a/.vim/etc/plugins.toml b/.vim/etc/plugins.toml new file mode 100644 index 0000000..f18a60b --- /dev/null +++ b/.vim/etc/plugins.toml @@ -0,0 +1,258 @@ +[[plugins]] +repo = 'thinca/vim-quickrun' +hook_source = ''' +runtime rc/plugins/quickrun.vim +''' + +[[plugins]] +repo = 'kana/vim-textobj-user' + +[[plugins]] +repo = 'kana/vim-textobj-indent' +depends = ['kana/vim-textobj-user'] + +[[plugins]] +repo = 'kana/vim-textobj-line' +depends = ['kana/vim-textobj-user'] + +[[plugins]] +repo = 'vim-jp/vimdoc-ja' +if = '!has("nvim")' + +[[plugins]] +repo = 'Shougo/unite.vim' +if = '!has("nvim")' +hook_add = ''' +runtime rc/plugins/unite.added.vim +''' + +[[plugins]] +repo = 'Shougo/neocomplete.vim' +vim_version = '7.3.885' +if = '!has("nvim")' +disabled = '!has("lua")' +hook_add = ''' +let g:neocomplete#enable_at_startup = 1 +let g:neocomplete#data_directory = $VIM_CACHE_DIR . '/neocomplete' +''' +hook_source = ''' +runtime rc/plugins/neocomplete.vim +''' + +[[plugins]] +repo = 'Shougo/deoplete.nvim' +if = 'has("nvim")' +hook_add = ''' +let g:deoplete#enable_at_startup = 1 +''' + +[[plugins]] +repo = 'LeafCage/foldCC' +hook_source = ''' +set foldtext=FoldCCtext() +set foldcolumn=4 +''' + +[[plugins]] +repo = 'tyru/current-func-info.vim' + +[[plugins]] +repo = 'Yggdroot/indentLine' +hook_source = ''' +let g:indentLine_char = '|' +let g:indentLine_showFirstIndentLevel = 1 + +autocmd MyInit BufEnter \* :IndentLinesReset<CR> +''' + +[[plugins]] +repo = 'itchyny/lightline.vim' +hook_add = ''' +runtime rc/plugins/lightline.vim +''' + +[[plugins]] +repo = 'osyo-manga/vim-anzu' +hook_add = ''' +nmap n <Plug>(anzu-n-with-echo) +nmap N <Plug>(anzu-N-with-echo) +nmap * <Plug>(anzu-star-with-echo) +nmap # <Plug>(anzu-sharp-with-echo) +nmap <Esc><Esc> <Plug>(anzu-clear-search-status) +''' + +[[plugins]] +repo = 'Shougo/neosnippet' +hook_add = ''' +let g:neosnippet#disable_select_mode_mappings = 0 +let g:neosnippet#snippets_directory = '~/.vim/snippets' + +imap <expr><TAB> neosnippet#expandable_or_jumpable() ? "\<Plug>(neosnippet_expand_or_jump)" : pumvisible() ? "\<C-n>" : "\<TAB>" +smap <expr><TAB> neosnippet#expandable_or_jumpable() ? "\<Plug>(neosnippet_expand_or_jump)" : "\<TAB>" +''' + +[[plugins]] +repo = 'kana/vim-smartinput' +hook_add = ''' +call smartinput#map_to_trigger('i', '<Plug>(smartinput_BS)', '<BS>', '<BS>') +call smartinput#map_to_trigger('i', '<Plug>(smartinput_C-h)', '<BS>', '<C-h>') +call smartinput#map_to_trigger('i', '<Plug>(smartinput_CR)', '<Enter>', '<Enter>') +call smartinput#define_rule({ + \ 'at' : '\s\+\%#', + \ 'char' : '<CR>', + \ 'input' : "<C-o>:call setline('.', substitute(getline('.'), '\\s\\+$', '', ''))<CR><CR>", + \ }) +call smartinput#define_rule({ + \ 'at' : '\%#', + \ 'char' : '[', + \ 'input' : '[%%]<Left><Left>', + \ 'filetype': ['tt2html'], + \ }) +''' + +[[plugins]] +repo = 'kana/vim-smartchr' +hook_add = ''' +inoremap <expr> = smartchr#loop(' = ', ' == ', '=') +''' + +[[plugins]] +repo = 'sickill/vim-pasta' + +[[plugins]] +repo = 'Shougo/neosnippet-snippets' + +[[plugins]] +repo = 'Shougo/vimproc' +build = 'make -f make_mac.mak' + +[[plugins]] +repo = 'editorconfig/editorconfig-vim' + +[[plugins]] +repo = 'thinca/vim-localrc' + +[[plugins]] +repo = 'Shougo/dein.vim' + +[[plugins]] +repo = 'tpope/vim-fugitive' +hook_add = ''' +nnoremap [fugitive] <Nop> +nmap ,g [fugitive] + +nnoremap [fugitive]s :<C-u>Gstatus<CR> +nnoremap [fugitive]c :<C-u>Gcommit<CR> +nnoremap [fugitive]C :<C-u>Gcommit --amend<CR> +nnoremap [fugitive]b :<C-u>Gblame<CR> +nnoremap [fugitive]a :<C-u>Gwrite<CR> +nnoremap [fugitive]d :<C-u>Gdiff<CR> +nnoremap [fugitive]D :<C-u>Gdiff --staged<CR> + +vmap ,go :Gbrowse<CR> + +autocmd MyInit BufReadPost fugitive://* set bufhidden=delete +''' + +[[plugins]] +repo = 'tyru/eskk.vim' +hook_add = ''' +imap <C-o> <Plug>(eskk:toggle) +let g:eskk#directory = expand('~/.vim/.eskk') + +let user_dictionary = expand('~/Library/Application Support/AquaSKK/skk-jisyo.utf8') +let large_dictionary = expand('~/Library/Application Support/AquaSKK/SKK-JISYO.L') + +if filereadable(user_dictionary) + let g:eskk#dictionary = user_dictionary +endif + +if filereadable(large_dictionary) + let g:eskk#large_dictionary = large_dictionary +endif +''' + +[[plugins]] +repo = 'toupeira/vim-desertink' + +[[plugins]] +repo = 'KeitaNakamura/neodark.vim' + +[[plugins]] +repo = 'crusoexia/vim-monokai' + +[[plugins]] +repo = 'roosta/vim-srcery' + +[[plugins]] +repo = 'altercation/vim-colors-solarized' +if = '!has("nvim")' + +[[plugins]] +repo = 'lifepillar/vim-solarized8' +if = 'has("nvim")' + +[[plugins]] +repo = 'nanotech/jellybeans.vim' + +[[plugins]] +repo = 'hail2u/h2u_colorscheme' + +[[plugins]] +repo = 'ajh17/Spacegray.vim' + +[[plugins]] +repo = 'jdkanani/vim-material-theme' + +[[plugins]] +repo = 'morhetz/gruvbox' + +[[plugins]] +repo = 'Shougo/tabpagebuffer.vim' + +[[plugins]] +repo = 'Shougo/unite-outline' + +[[plugins]] +repo = 'thinca/vim-unite-history' + +[[plugins]] +repo = 'sorah/unite-ghq' + +[[plugins]] +repo = 'ujihisa/unite-colorscheme' + +[[plugins]] +repo = 'kana/vim-operator-user' + +[[plugins]] +repo = 'tpope/vim-rhubarb' + +[[plugins]] +repo = 'w0rp/ale' +hook_add = ''' +let g:ale_sign_error = 'E' +let g:ale_sign_warning = 'W' +let g:ale_statusline_format = ['E%d', 'W%d', ''] +let g:ale_lint_on_enter = 0 +let g:ale_lint_on_text_changed = 'never' +let g:ale_set_loclist = 1 +let g:ale_set_quickfix = 1 +let g:ale_open_list = 1 +let g:ale_keep_list_window_open = 0 + +let g:ale_javascript_eslint_options = '--quiet' +let g:ale_linters = { 'javascript': ['eslint', 'flow'] } + +let g:ale_perl_perl_executable = 'env PERL5LIB="./local/lib/perl5" perl' +''' + +[[plugins]] +repo = 'Shougo/denite.nvim' +if = 'has("nvim")' +on_cmd = 'Denite' +hook_add = 'runtime rc/plugins/denite.added.vim' +hook_source = 'runtime rc/plugins/denite.sourced.vim' + +[[plugins]] +repo = 'aereal/vim-colors-japanesque' diff --git a/.vim/filetype.vim b/.vim/filetype.vim new file mode 100644 index 0000000..b11779a --- /dev/null +++ b/.vim/filetype.vim @@ -0,0 +1,21 @@ +autocmd BufEnter */templates/*.html setf tt2html +autocmd BufEnter *.tt setf tt2html + +autocmd BufEnter *.es6,*.es setf javascript + +autocmd BufEnter */nginx/*.conf setf nginx +autocmd BufEnter */*.nginx.conf setf nginx + +autocmd BufEnter cpanfile setf cpanfile +autocmd BufEnter cpanfile set syntax=perl.cpanfile +autocmd BufEnter *.t setf perl +autocmd BufEnter *.psgi setf perl + +autocmd BufEnter *.podspec setf ruby +autocmd BufEnter Podfile setf ruby + +autocmd BufEnter *.hatena setf hatena + +autocmd BufEnter *.scala setf scala + +autocmd BufEnter *.toml setf toml diff --git a/.vim/gvimrc b/.vim/gvimrc new file mode 100644 index 0000000..cab3b16 --- /dev/null +++ b/.vim/gvimrc @@ -0,0 +1,15 @@ +let g:macvim_skip_cmd_opt_movement = 1 + +set bg=dark + +if has("gui_running") + try + colorscheme japanesque + catch + colorscheme desert + endtry + + set guifontwide=SourceHanCodeJP-Regular:h14 + set guifont=FiraMono-Regular:h14 + set tranparency=15 +endif diff --git a/.vim/plugin/memolist-templates/hatena.txt b/.vim/plugin/memolist-templates/hatena.txt new file mode 100644 index 0000000..912845d --- /dev/null +++ b/.vim/plugin/memolist-templates/hatena.txt @@ -0,0 +1,2 @@ +* {{_title_}} + diff --git a/.vim/rc/00_autocmd.vim b/.vim/rc/00_autocmd.vim new file mode 100644 index 0000000..a9aae7a --- /dev/null +++ b/.vim/rc/00_autocmd.vim @@ -0,0 +1,112 @@ +augroup MyInit + autocmd! +augroup END + +" screen title {{{ +if ! has('gui_running') + autocmd MyInit BufEnter * if bufname("") !~ "^\[A-Za-z0-9\]://" | silent! exe '!echo -n "k%:t\\"' | endif +endif " }}} +" Markdown {{{ +autocmd MyInit FileType markdown setlocal et ts=4 sts=4 sw=4 +" }}} +" Close window with `q` key {{{ +autocmd MyInit FileType help,ref-*,tap-result nnoremap <buffer> q :q<CR> +" }}} +" Git config {{{ +autocmd MyInit FileType gitconfig setlocal noexpandtab +" }}} + +" function! ReloadConfig() abort +" call dein#clear_state() +" source $MYVIMRC +" if has('gui_running') +" source $MYGVIMRC +" endif +" endfunction +" autocmd MyInit BufWritePost *vimrc,*gvimrc,*/rc/*.vim call ReloadConfig() + +function! LooksLikePerlProject(project_root) abort + let cpanfile = a:project_root . '/cpanfile' + if filereadable(cpanfile) + return 1 + else + return 0 + endif +endfunction + +function! ConfigureCartonPath() abort + let project_root = getcwd() + let is_perl = LooksLikePerlProject(project_root) + let t:is_perl_project = is_perl + let w:is_perl_project = is_perl + if is_perl + let paths = [ + \ project_root . '/lib', + \ project_root . '/local/lib/perl5', + \ project_root . '/templates', + \ ] + execute "setlocal path+=" . join(paths, ',') + endif +endfunction +autocmd MyInit BufEnter,TabEnter * call ConfigureCartonPath() + + +function! SetupCustomHighlightLinks() abort + highlight! link Noise Conceal + + " Perl + highlight! link perlVarPlain Identifier + highlight! link perlVarPlain2 Identifier + highlight! link perlStatementStorage StorageClass + highlight! link perlSharpBang Comment + highlight! link perlStringStartEnd Conceal + highlight! link perlMatchStartEnd Conceal + highlight! link perlFunction Statement + highlight! link perlSubName Function + highlight! link perlOperator Operator + highlight! link perlMethod Function + highlight! link perlStatementInclude Include + + " JavaScript + highlight! link jsObjectKey Type + highlight! link jsFuncCall Function + + " HTML + highlight! link htmlTag Conceal + highlight! link htmlEndTag Conceal + highlight! link htmlTagName Identifier + + " TT2 + highlight! link tt2_tag Conceal + highlight! link tt2_bracket_r Conceal + highlight! link tt2_operator Conceal + + " TypeScript + highlight! link typescriptEndColons Conceal + highlight! link typescriptParens Conceal + highlight! link typescriptBraces Conceal + + " Git + highlight! link gitcommitWarning WarningMsg + + " Fugitive + highlight! link FugitiveblameDelimiter Delimiter + + " Ruby + highlight! link rubyStringDelimiter Conceal + + " Vim + highlight! link vimParenSep Conceal + + " Markdown + highlight! link mkdDelimiter Statement + + " YAML + highlight! link yamlKeyValueDelimiter Statement + + highlight! link SignColumn LineNr +endfunction + +autocmd MyInit ColorScheme * call SetupCustomHighlightLinks() + +" vim:set foldmethod=marker: diff --git a/.vim/rc/00_base.vim b/.vim/rc/00_base.vim new file mode 100644 index 0000000..7dbbe03 --- /dev/null +++ b/.vim/rc/00_base.vim @@ -0,0 +1,121 @@ +set hidden +set history=1000 +set autoread +set fileformats=unix,dos,mac +set scrolloff=100000 " 常にカーソルのある行を中心に (したい) +set backspace=indent,eol,start +set formatoptions-=ro +set ttyfast +" set lazyredraw +set completeopt=menuone,menu + +" Cache directory {{{ +if !exists('$VIM_CACHE_DIR') + if isdirectory(expand($TMPDIR)) + let tmp_dir = expand($TMPDIR) + else + let tmp_dir = '/tmp' + endif + let path_separator = '/' + let path_cmps = split(simplify(tmp_dir), path_separator, 1) + let $VIM_CACHE_DIR = simplify(join(extend(path_cmps, ['vim']), path_separator)) + unlet tmp_dir path_separator path_cmps +endif + +if !isdirectory(expand($VIM_CACHE_DIR)) + call mkdir($VIM_CACHE_DIR, 'p') +endif +" }}} + +" Backup & Swap {{{ +set nobackup +set swapfile +set directory=~/.vim/swp +" }}} +" Indentation {{{ +set autoindent +set nosmartindent +set nocindent +set smarttab +set shiftwidth=2 +set tabstop=2 +set softtabstop=2 +set expandtab +set shiftround +" }}} +" Encoding {{{ +set fileencodings=utf-8,iso-2022-jp,euc-jp,cp932,ucs-bom,default,latin1 +set encoding=utf-8 +set termencoding=utf-8 +" }}} +" Search {{{ +set ignorecase +set smartcase +set hlsearch +set incsearch +set wrapscan +" }}} +" Visualization {{{ +set ambiwidth=double +set list +set listchars=tab:»\ ,precedes:<,extends:>,trail:_,eol:↲ +" }}} +" UI {{{ +set langmenu=none " メニューをローカライズしない +set laststatus=2 +set number +set ruler +set modeline +set noshowcmd +set noshowmode +set shortmess+=I + +if v:version >= 704 + " set relativenumber " 7.4 以降だと絶対行数も表示される +endif +" }}} +" IME {{{ +set noimdisable +set iminsert=0 imsearch=0 +set noimcmdline +" }}} +" Persistent Undo {{{ +if has('persistent_undo') + set undodir=~/.vim/undo + set undofile +endif +" }}} +" Clipboard Integration {{{ +if has('clipboard') + if has('nvim') + set clipboard+=unnamedplus + else + set clipboard=unnamed,autoselect + endif +endif +" }}} +" fish-shell fix {{{ +if $SHELL =~# 'fish$' + if executable('zsh') + set shell=zsh + else + set shell=sh + endif +endif +" }}} + +if has('gui_running') + set guioptions& + set guioptions-=T + set guioptions-=m + set guioptions-=r + set guioptions-=R + set guioptions-=l + set guioptions-=l + set guioptions-=L + set guioptions-=L + set guioptions-=b + set guioptions-=e +endif + +" vim:set foldmethod=marker: diff --git a/.vim/rc/10_dein.vim b/.vim/rc/10_dein.vim new file mode 100644 index 0000000..7b9ef86 --- /dev/null +++ b/.vim/rc/10_dein.vim @@ -0,0 +1,32 @@ +set runtimepath& runtimepath^=~/devel/src/github.com/Shougo/dein.vim + +let s:dein_cache_dir = expand('~/.vim/cache/dein') +let s:plugins_toml = expand('~/.vim/etc/plugins.toml') +let s:lazy_plugins_toml = expand('~/.vim/etc/lazy.toml') +let s:operator_plugins_toml = expand('~/.vim/etc/operator.toml') + +if dein#load_state(s:dein_cache_dir) + call dein#begin(s:dein_cache_dir, [ + \ expand('<sfile>'), + \ s:plugins_toml, + \ s:lazy_plugins_toml, + \ s:operator_plugins_toml, + \ ]) + + call dein#load_toml(s:plugins_toml) + call dein#load_toml(s:lazy_plugins_toml, { 'lazy': 1 }) + call dein#load_toml(s:operator_plugins_toml, { 'lazy': 1, 'depends': ['vim-operator-user'] }) + call dein#local('~/devel/src/github.com/aereal', { + \ 'frozen': 1, + \ 'merged': 1, + \ }, ['vim-*']) + + call dein#end() + call dein#save_state() +endif + +if dein#check_install() + call dein#install() +endif + +unlet s:dein_cache_dir diff --git a/.vim/rc/20_command.vim b/.vim/rc/20_command.vim new file mode 100644 index 0000000..c52f631 --- /dev/null +++ b/.vim/rc/20_command.vim @@ -0,0 +1,72 @@ +command! Sketch call s:sketch() " {{{ +function! s:sketch() " {{{ + if !exists('g:sketch_dir') + let g:sketch_dir = expand('~/sketches') + endif + + if !isdirectory(g:sketch_dir) + call mkdir(g:sketch_dir, 'p') + endif + + let basename = strftime('%Y%m%d%H%M%S') + let filename = g:sketch_dir . '/' . basename + execute ':edit ' . filename +endfunction " }}} +" }}} + +command! Prove call s:prove() +function! s:prove() + let func_name = cfi#format('%s', '') + if func_name != '' + let $TEST_METHOD = func_name + endif + call tap#prove() +endfunction " }}} + +command! Memo call s:memo() +function! s:memo() + let memo_root = expand('~/memo') + let dt = strftime('%Y%m%d-%H%M%S') + let suffix = '.md' + let filename = memo_root . '/' . dt . suffix + + execute ":edit " . filename +endfunction + +function! s:get_syn_id(transparent) + let synid = synID(line("."), col("."), 1) + if a:transparent + return synIDtrans(synid) + else + return synid + endif +endfunction +function! s:get_syn_attr(synid) + let name = synIDattr(a:synid, "name") + let ctermfg = synIDattr(a:synid, "fg", "cterm") + let ctermbg = synIDattr(a:synid, "bg", "cterm") + let guifg = synIDattr(a:synid, "fg", "gui") + let guibg = synIDattr(a:synid, "bg", "gui") + return { + \ "name": name, + \ "ctermfg": ctermfg, + \ "ctermbg": ctermbg, + \ "guifg": guifg, + \ "guibg": guibg} +endfunction +function! s:get_syn_info() + let baseSyn = s:get_syn_attr(s:get_syn_id(0)) + echo "name: " . baseSyn.name . + \ " ctermfg: " . baseSyn.ctermfg . + \ " ctermbg: " . baseSyn.ctermbg . + \ " guifg: " . baseSyn.guifg . + \ " guibg: " . baseSyn.guibg + let linkedSyn = s:get_syn_attr(s:get_syn_id(1)) + echo "link to" + echo "name: " . linkedSyn.name . + \ " ctermfg: " . linkedSyn.ctermfg . + \ " ctermbg: " . linkedSyn.ctermbg . + \ " guifg: " . linkedSyn.guifg . + \ " guibg: " . linkedSyn.guibg +endfunction +command! SyntaxInfo call s:get_syn_info() diff --git a/.vim/rc/20_key.vim b/.vim/rc/20_key.vim new file mode 100644 index 0000000..3cd9dd6 --- /dev/null +++ b/.vim/rc/20_key.vim @@ -0,0 +1,25 @@ +let mapleader = ';' +let g:mapleader = ';' + +nnoremap j gj +nnoremap k gk +nnoremap Y y$ + +nnoremap <Leader><Space> :update<CR> +nnoremap <ESC><ESC> :nohlsearch<CR> + +nnoremap Q <Nop> +nnoremap ZQ <Nop> +nnoremap ZZ <Nop> + +nnoremap ) % +nnoremap ( % + +nnoremap H ^ +nnoremap L $ + +nnoremap ]q :<C-u>cnext<CR> +nnoremap [q :<C-u>cprev<CR> + +xnoremap < <gv +xnoremap > >gv diff --git a/.vim/rc/20_tab.vim b/.vim/rc/20_tab.vim new file mode 100644 index 0000000..2c03d0c --- /dev/null +++ b/.vim/rc/20_tab.vim @@ -0,0 +1 @@ +set showtabline=2 diff --git a/.vim/rc/command_line_window.vim b/.vim/rc/command_line_window.vim new file mode 100644 index 0000000..9cd75a8 --- /dev/null +++ b/.vim/rc/command_line_window.vim @@ -0,0 +1,18 @@ +nnoremap <SID>(command-line-enter) q: +xnoremap <SID>(command-line-enter) q: +nnoremap <SID>(command-line-norange) q:<C-u> +nmap : <SID>(command-line-enter) +xmap : <SID>(command-line-enter) + +autocmd MyInit CmdwinEnter * call s:init_cmdwin() + +function! s:init_cmdwin() " {{{ + nnoremap <silent><buffer> q :<C-u>quit<CR> + nnoremap <silent><buffer> <TAB> :<C-u>quit<CR> + inoremap <buffer><expr><CR> pumvisible() ? "\<C-y>\<CR>" : "\<CR>" + inoremap <buffer><expr><C-h> pumvisible() ? "\<C-y>\<C-h>" : "\<C-h>" + inoremap <buffer><expr><BS> pumvisible() ? "\<C-y>\<C-h>" : "\<C-h>" + inoremap <buffer><expr><TAB> pumvisible() ? "\<C-n>" : "\<TAB>" + + startinsert! +endfunction " }}} diff --git a/.vim/rc/plugins/denite.added.vim b/.vim/rc/plugins/denite.added.vim new file mode 100644 index 0000000..7216b72 --- /dev/null +++ b/.vim/rc/plugins/denite.added.vim @@ -0,0 +1,14 @@ +nnoremap <SID>[denite] <Nop> +nmap gj <SID>[denite] + +nmap <SID>[denite]p <SID>(project-files) +nmap <SID>[denite]f <SID>(files) +nmap <SID>[denite]F <SID>(files-from-buffer) +nmap <SID>[denite][ <SID>(outline) +nmap <SID>[denite]b <SID>(buffers) + +nnoremap <silent> <SID>(project-files) :<C-u>Denite file_rec -buffer-name=files -source-names=hide<CR> +nnoremap <silent> <SID>(files) :<C-u>DeniteProjectDir file file:new -buffer-name=files -source-names=hide<CR> +nnoremap <silent> <SID>(files-from-buffer) :<C-u>DeniteBufferDir file file:new -buffer-name=files -source-names=hide<CR> +nnoremap <silent> <SID>(buffers) :<C-u>Denite buffer<CR> +nnoremap <silent> <SID>(outline) :<C-u>Denite outline<CR> diff --git a/.vim/rc/plugins/denite.sourced.vim b/.vim/rc/plugins/denite.sourced.vim new file mode 100644 index 0000000..94325a9 --- /dev/null +++ b/.vim/rc/plugins/denite.sourced.vim @@ -0,0 +1,13 @@ +call denite#custom#option('default', 'prompt', '>') +call denite#custom#option('files', 'prompt', '>') + +if executable('rg') + call denite#custom#var('file_rec', 'command', ['rg', '--files', '--glob', '!.git', '--glob', '!*.{png,jpg,min.js,gif,svg,woff,woff2,eot,ttf,otf,ico}']) + call denite#custom#var('grep', 'command', 'rg') +endif + +call denite#custom#map('normal', '<C-w>h', '<denite:do_action:vsplitswitch>', 'noremap') +call denite#custom#map('normal', '<C-w>l', '<denite:do_action:vsplitswitch>', 'noremap') + +call denite#custom#map('normal', '<C-w>j', '<denite:do_action:splitswitch>', 'noremap') +call denite#custom#map('normal', '<C-w>k', '<denite:do_action:splitswitch>', 'noremap') diff --git a/.vim/rc/plugins/lightline.vim b/.vim/rc/plugins/lightline.vim new file mode 100644 index 0000000..7828b26 --- /dev/null +++ b/.vim/rc/plugins/lightline.vim @@ -0,0 +1,42 @@ +if ! exists('g:lightline') + let g:lightline = {} +endif +if ! has_key(g:lightline, 'component') + let g:lightline.component = {} +endif +if ! has_key(g:lightline, 'component_visible_condition') + let g:lightline.component_visible_condition = {} +endif +let g:lightline.colorscheme = 'seoul256' +let g:lightline.component.anzu = '%{anzu#search_status()}' +let g:lightline.component.fugitive = '%{fugitive#head()}' +let g:lightline.component_visible_condition.fugitive = '(exists("*fugitive#head") && ""!=fugitive#head())' +let g:lightline.active = { + \ 'right': [ + \ ['syntastic', 'lineinfo'], + \ ['percent'], + \ ['fileformat', 'fileencoding', 'filetype'], + \ ], + \ 'left' : [ + \ ['mode', 'paste'], + \ ['fugitive'], + \ ['readonly', 'filename', 'modified'], + \ ['ale'] + \ ], + \ } +let g:lightline.component_expand = { + \ 'syntastic' : 'SyntasticStatuslineFlag', + \ } +let g:lightline.component_type = { + \ 'syntastic' : 'error', + \ } +let g:lightline.component_function = { + \ 'ale' : 'ALEGetStatusLine', + \ } +let g:lightline.tabline = { + \ 'left': [ ['tabs'] ], + \ } +let g:lightline.tab = { + \ 'active' : ['tabnum', 'readonly', 'filename', 'modified'], + \ 'inactive' : ['tabnum', 'readonly', 'filename', 'modified'], + \ } diff --git a/.vim/rc/plugins/neocomplete.vim b/.vim/rc/plugins/neocomplete.vim new file mode 100644 index 0000000..f57fd9d --- /dev/null +++ b/.vim/rc/plugins/neocomplete.vim @@ -0,0 +1,31 @@ +if ! exists('g:neocomplete#force_omni_input_patterns') + let g:neocomplete#force_omni_input_patterns = {} +endif + +let g:neocomplete#enable_smart_case = 1 +let g:neocomplete#max_list = 1000 + +let g:neocomplete#force_overwrite_completefunc = 1 +let g:neocomplete#force_omni_input_patterns.c = '[^.[:digit:] *\t]\%(\.\|->\)' +let g:neocomplete#force_omni_input_patterns.objc = '[^.[:digit:] *\t]\%(\.\|->\)\|\h\w*::' +let g:neocomplete#force_omni_input_patterns.cpp = '[^.[:digit:] *\t]\%(\.\|->\)\|\h\w*::' +let g:neocomplete#force_omni_input_patterns.objcpp = '[^.[:digit:] *\t]\%(\.\|->\)\|\h\w*::' + +let g:neocomplete#sources#syntax#min_keyword_length = 3 + +let g:neocomplete#keyword_patterns = {} +let g:neocomplete#keyword_patterns.default = '\h\w*' + +let g:neocomplete#delimiter_patterns = {} +let g:neocomplete#delimiter_patterns.vim = ['#'] +let g:neocomplete#delimiter_patterns.perl = [] +let g:neocomplete#delimiter_patterns.ruby = ['::'] + +call neocomplete#custom#source('omni', 'rank', 7) +call neocomplete#custom#source('omni', 'converters', ['converter_remove_last_paren']) + +imap <expr> <C-h> neocomplete#smart_close_popup() . "\<Plug>(smartinput_C-h)" +imap <expr> <BS> neocomplete#smart_close_popup() . "\<Plug>(smartinput_BS)" +inoremap <expr> <C-g> neocomplete#undo_completion() + +autocmd MyInit CmdwinEnter * let b:neocomplete_sources = ['vim'] diff --git a/.vim/rc/plugins/quickrun.vim b/.vim/rc/plugins/quickrun.vim new file mode 100644 index 0000000..c88b6fc --- /dev/null +++ b/.vim/rc/plugins/quickrun.vim @@ -0,0 +1,17 @@ +if !exists('g:quickrun_config') + let g:quickrun_config = {} +endif +let g:quickrun_config['prove/carton'] = { + \ 'exec' : 'carton exec -- %c %o %s', + \ 'command' : 'prove', + \ } +let g:quickrun_config['prove/carton/contextual'] = extend(g:quickrun_config['prove/carton'], { + \ 'exec' : 'TEST_METHOD=%a ' . g:quickrun_config['prove/carton'].exec, + \ }) +" let g:quickrun_config.vim = { +" \ 'outputter' : 'error', +" \ 'outputter/error/success' : 'null', +" \ 'outputter/error/error' : 'buffer', +" \ } + +" vim:set foldmethod=marker: diff --git a/.vim/rc/plugins/syntastic.added.vim b/.vim/rc/plugins/syntastic.added.vim new file mode 100644 index 0000000..261496f --- /dev/null +++ b/.vim/rc/plugins/syntastic.added.vim @@ -0,0 +1,13 @@ +let g:syntastic_mode_map = { + \ 'mode' : 'passive', + \ } + +augroup auto-syntastic + autocmd! + autocmd BufWritePost *.rb, *.js, *.scala call s:syntastic() +augroup END + +function! s:syntastic() abort + SyntasticCheck + call lightline#update() +endfunction diff --git a/.vim/rc/plugins/unite.added.vim b/.vim/rc/plugins/unite.added.vim new file mode 100644 index 0000000..c2dffe0 --- /dev/null +++ b/.vim/rc/plugins/unite.added.vim @@ -0,0 +1,129 @@ +" mapping {{{ +nnoremap <SID>[unite] <Nop> +nmap gj <SID>[unite] + +nmap <SID>[unite]p <SID>(project-files) +nmap <SID>[unite]f <SID>(files) +nmap <SID>[unite]F <SID>(files-from-buffer) +nmap <SID>[unite]w <SID>(windows) +nmap <SID>[unite][ <SID>(outline) +nmap <SID>[unite]: <SID>(history) +nmap <SID>[unite]q <SID>(quickfix) +nmap <SID>[unite]t <SID>(tabs) +nmap <SID>[unite]B <SID>(buffers) +nmap <SID>[unite]mv <SID>(rename) +nmap <SID>[unite]G <SID>(ghq-list) + +if has('gui_running') + nmap <SID>[unite]b <SID>(tab-buffers) +else + nmap <SID>[unite]b <SID>(buffers) +endif + +" definitions {{{ +nnoremap <silent> <SID>(project-files) :<C-u>Unite file_rec/git -hide-source-names -buffer-name=files<CR> +nnoremap <silent> <SID>(files) :<C-u>UniteWithCurrentDir file file/new -hide-source-names -buffer-name=files<CR> +nnoremap <silent> <SID>(files-from-buffer) :<C-u>UniteWithBufferDir file file/new -hide-source-names -buffer-name=files<CR> +nnoremap <silent> <SID>(windows) :<C-u>Unite window:no-current -no-empty<CR> +nnoremap <silent> <SID>(outline) :<C-u>Unite outline -hide-source-names -winwidth=40 -buffer-name=outline<CR> +nnoremap <silent> <SID>(history) :<C-u>Unite history/command -start-insert<CR> +nnoremap <silent> <SID>(quickfix) :<C-u>Unite quickfix -no-quit -no-empty -auto-resize -buffer-name=quickfix<CR> +nnoremap <silent> <SID>(tabs) :<C-u>Unite tab:no-current -no-empty -immediately<CR> +nnoremap <silent> <SID>(tab-buffers) :<C-u>Unite buffer_tab -no-empty<CR> +nnoremap <silent> <SID>(buffers) :<C-u>Unite buffer -no-empty<CR> +nnoremap <silent><expr> <SID>(rename) ':<C-u>Unite file -input=' . expand('%:p') . ' -default-action=exrename -immediately<CR>' +nnoremap <silent> <SID>(ghq-list) :<C-u>Unite ghq<CR> +" }}} +" }}} +function! s:unite_my_settings() " {{{ + let unite = unite#get_current_unite() + + nmap <buffer> <BS> <Plug>(unite_delete_backward_path) + + nnoremap <buffer><silent><expr> <C-w>h unite#do_action('left') + nnoremap <buffer><silent><expr> <C-w>l unite#do_action('right') + nnoremap <buffer><silent><expr> <C-w>j unite#do_action('below') + nnoremap <buffer><silent><expr> <C-w>k unite#do_action('above') + + nnoremap <buffer><silent><expr> p unite#do_action('preview') + + if unite.buffer_name == 'files' + nnoremap <buffer><silent><expr> r unite#do_action('rename') + endif +endfunction " }}} +" variables {{{ +let g:unite_data_directory = $VIM_CACHE_DIR . '/unite' +let g:unite_force_overwrite_statusline = 0 + +if executable('ag') + let g:unite_source_grep_command = 'ag' + let g:unite_source_grep_default_opts = '--nocolor --nogroup' + let g:unite_source_grep_recursive_opt = '' + let g:unite_source_grep_max_candidates = 200 +endif +" }}} +" autocmd {{{ +autocmd MyInit FileType unite nmap <buffer><BS> <Plug>(unite_delete_backward_path) +autocmd MyInit FileType unite call s:unite_my_settings() +" }}} +" Custom sources {{{ +" unite-git-files-conflict {{{ +let s:unite_git_files_conflict = { + \ 'name' : 'git/files/conflict', + \ } +function! s:unite_git_files_conflict.gather_candidates(args, context) + let output = unite#util#system('git diff-files --name-only --diff-filter=U') + let candidates = map(split(output, "\n"), '{ + \ "word" : fnamemodify(v:val, ":p"), + \ "source" : "git/files/conflict", + \ "kind" : "file", + \ "action__path" : fnamemodify(v:val, ":p"), + \ }') + return candidates +endfunction +call unite#define_source(s:unite_git_files_conflict) +" }}} +" unite-git-files-modified {{{ +let s:unite_git_files_modified = { + \ 'name' : 'git/files/modified', + \ } +function! s:unite_git_files_modified.gather_candidates(args, context) + let output = unite#util#system('git ls-files --modified') + let candidates = map(split(output, "\n"), '{ + \ "word" : fnamemodify(v:val, ":p"), + \ "source" : "git/files/modified", + \ "kind" : "file", + \ "action__path" : fnamemodify(v:val, ":p"), + \ }') + return candidates +endfunction +call unite#define_source(s:unite_git_files_modified) +" }}} +" unite-git-files-others {{{ +let s:unite_git_files_others = { + \ 'name' : 'git/files/others', + \ } +function! s:unite_git_files_others.gather_candidates(args, context) + let output = unite#util#system('git ls-files --others --exclude-standard') + let candidates = map(split(output, "\n"), '{ + \ "word" : fnamemodify(v:val, ":p"), + \ "source" : "git/files/others", + \ "kind" : "file", + \ "action__path" : fnamemodify(v:val, ":p"), + \ }') + return candidates +endfunction +call unite#define_source(s:unite_git_files_others) +" }}} +" }}} + +call unite#custom#default_action('source/ghq/*', 'tabnew_lcd') + +" converter_relative_abbr: 候補を表示するときに相対パスに +" matcher_project_files: 候補はリポジトリのファイルからのみ +call unite#custom#source('file_mru', 'matchers', ['converter_relative_abbr', 'matcher_project_files', 'matcher_fuzzy']) + +let s:unite_project_ignore_pattern = '\.\(gif\|jpe\?g\|png\|min\.js\|vendor\)' +call unite#custom#source('file_rec/git', 'ignore_pattern', s:unite_project_ignore_pattern) + +" vim:set foldmethod=marker: diff --git a/.vim/rc/plugins/watchdogs.vim b/.vim/rc/plugins/watchdogs.vim new file mode 100644 index 0000000..7c8a630 --- /dev/null +++ b/.vim/rc/plugins/watchdogs.vim @@ -0,0 +1,29 @@ +let g:watchdogs_check_BufWritePost_enable = 1 +let g:watchdogs_check_BufWritePost_enables = { + \ "typescript": 0, + \ } +if !exists('g:quickrun_config') + let g:quickrun_config = {} +endif +let g:quickrun_config['watchdogs_checker/_'] = { + \ 'outputter/quickfix/open_cmd' : '', + \ 'hook/hier_update/enable_exit' : 1, + \ 'runner/vimproc/updatetime' : 40, + \ } +let g:quickrun_config['watchdogs_checker/efm_perl'] = { + \ 'command' : expand('~/.vim/tools/efm_perl.pl'), + \ 'exec' : '%c %o %s:p', + \ 'quickfix/errorformat' : '%f:%l:%m', + \ } +let g:quickrun_config['watchdogs_checker/cpanfile'] = { + \ 'command' : 'perl', + \ 'exec' : '%c %o -w -MModule::CPANfile -e "Module::CPANfile->load(q|%S:p|)"', + \ 'quickfix/errorformat' : '%m\ at\ %f\ line\ %l%.%#', + \ } +let g:quickrun_config['perl/watchdogs_checker'] = { + \ 'type' : 'watchdogs_checker/efm_perl', + \ } +let g:quickrun_config['cpanfile/watchdogs_checker'] = { + \ 'type' : 'watchdogs_checker/cpanfile', + \ } +call watchdogs#setup(g:quickrun_config) diff --git a/.vim/snippets/eruby.snip b/.vim/snippets/eruby.snip new file mode 100644 index 0000000..0390d82 --- /dev/null +++ b/.vim/snippets/eruby.snip @@ -0,0 +1,22 @@ +snippet case + <% case ${1:object} %> + <% when ${2:condition} %> + ${3} + <% end %> +snippet when + <% when ${1:condition} %> + ${2} +snippet if + <% if ${1:condition} %> + ${2} + <% end %> +snippet ife + <% if ${1:condition} %> + ${2} + <% else %> + ${3} + <% end %> +snippet unless + <% unless ${1:condition} %> + ${2} + <% end %> diff --git a/.vim/snippets/io.snip b/.vim/snippets/io.snip new file mode 100644 index 0000000..b3123a7 --- /dev/null +++ b/.vim/snippets/io.snip @@ -0,0 +1,5 @@ +snippet if + if(${1:/* condition */}, ${2:/* then-clause */}) + +snippet ife + if(${1:/* condition */}, ${2:/* then-clause */}, ${3:/* else-clause */}) diff --git a/.vim/snippets/javascript.snippet b/.vim/snippets/javascript.snippet new file mode 100644 index 0000000..0a799f3 --- /dev/null +++ b/.vim/snippets/javascript.snippet @@ -0,0 +1,11 @@ +snippet func +alias function + function (${0:args}) {${1:body}}; + +snippet if + if (${1:true}) ${0:$TM_SELECTED_TEXT} + +snippet for + for (var ${2:i}=0; $2 < ${1:Things}.length; $2++) { + ${0} + }; diff --git a/.vim/snippets/markdown.snippet b/.vim/snippets/markdown.snippet new file mode 100644 index 0000000..f553dc7 --- /dev/null +++ b/.vim/snippets/markdown.snippet @@ -0,0 +1,27 @@ +snippet link + [${1:#:title}](${2:#:url}) + +snippet link_paste + [${1}](`getreg('+')`) + +snippet image + ![${1:#:alt text}](${2:#:url}) + +snippet image_paste + ![${1}](`getreg('+')`) + +snippet README +options head + # ${1:NAME} + + ${2:DESCRIPTION} + + ## Usage + + ${3:USAGE} + + ## License + + ${4:LICENSE} + +# vim:set ft=neosnippet noexpandtab: diff --git a/.vim/snippets/objc.snip b/.vim/snippets/objc.snip new file mode 100644 index 0000000..4e2b955 --- /dev/null +++ b/.vim/snippets/objc.snip @@ -0,0 +1,50 @@ +" vim:set noexpandtab: + +snippet import + #import "${1:Header}.h" + +snippet if + if (${1:condition}) { + ${2} + } + +snippet else + else { + ${1} + } + +snippet elif +abbr else_if + else if (${1:condition}) { + ${2} + } + +snippet method +abbr instance_method + - (${1:ReturnType})${2:MethodName} + { + ${3} + } + +snippet cmethod +abbr class_method + + (${1:ReturnType})${2:MethodName} + { + ${3} + } + +snippet for_in + for (${1:value} in ${2:FastEnumeration}) { + ${3} + } + +snippet block + ^(${1:args}) { + ${2} + } + +snippet extern + extern ${1:type} const ${2:Constant}; + +snippet const + ${1:type} const ${2:NAME} = ${3:value}; diff --git a/.vim/snippets/perl.snip b/.vim/snippets/perl.snip new file mode 100644 index 0000000..62b1e79 --- /dev/null +++ b/.vim/snippets/perl.snip @@ -0,0 +1,77 @@ +# vim:set ft=snippet noet: +snippet pl + #!/usr/bin/env perl + + use strict; + use warnings; +alias shebang + +snippet use + use ${1:Package}; + +snippet uselib + use lib 'lib', glob "${1:Package}"; + +snippet ddd + require Data::Dumper; + sub p ($) { warn Data::Dumper->new(\@_)->Useqq(1)->Terse(1)->Dump(); } + ${1} + +snippet sub_self +options head + sub ${1:method} { + my ($self${2:#:rest args}) = @_; + ${3:# body} + } + +snippet sub_class +options head + sub ${1:method} { + my ($class${2:#:rest args}) = @_; + ${3:#:# body} + } + +snippet package +options head + package ${1:`substitute(substitute(expand('%:p:r'), '.*/lib/', '', 'g'), '/', '::', 'g')`}; + + use strict; + use warnings; + + ${2:#:body} + + 1; + +snippet package_block +options head + package ${1:`substitute(substitute(expand('%:p:r'), '.*/lib/', '', 'g'), '/', '::', 'g')`} { + ${2:#:body} + } + +snippet t +options head + package ${1:`substitute(substitute(expand('%:p:r'), '.*/t/', 't-', 'g'), '-', '::', 'g')`}; + + sub _require : Test(startup => 1) { + require_ok '${2:`substitute(substitute(expand('%:p:r'), '.*/t/', '', 'g'), '-', '::', 'g')`}'; + } + + ${2:#:# body} + + 1; + +snippet subtest + subtest ${1:test_name} => sub { + ${2:#:body} + }; + +snippet tests + sub ${1:test_name} : Tests { + ${2:#:body} + } + +snippet todo_test + TODO: { + local $TODO = '${1:reason}'; + fail '$1'; + }; diff --git a/.vim/snippets/rspec.snip b/.vim/snippets/rspec.snip new file mode 100644 index 0000000..081c396 --- /dev/null +++ b/.vim/snippets/rspec.snip @@ -0,0 +1,35 @@ +snippet describe + describe ${1:object} do + ${2} + end + +snippet it + it "${1:description}" do + ${2} + end + +snippet specify + specify "${1:description}" do + ${2} + end + +snippet context + context "${1:case}" do + ${2} + end + +snippet expect + expect { ${1:subject} }.${2:to} \ + ${3} + +snippet change change ... from ... by ... + change { ${1:object} }.from(${2:pre}).to(${3:post}) + +snippet change change ... by + change { ${1:object} }.by(${2:pre}) + +snippet let + let(:${1:name}) { ${2} } + +snippet let! + let!(:${1:name}) { ${2} } diff --git a/.vim/snippets/ruby.snip b/.vim/snippets/ruby.snip new file mode 100644 index 0000000..0223d21 --- /dev/null +++ b/.vim/snippets/ruby.snip @@ -0,0 +1,170 @@ +# vim:set ft=snippet noet: +snippet shebang + #!/usr/bin/env ruby + +snippet =b + =begin rdoc + ${1} + =end + +snippet beg +abbr begin rescue end + begin + ${3} + rescue ${1:Exception} => ${2:e} + end + +snippet req + require "${1}"${2} + +snippet case + case ${1:object} + when ${2:condition} + ${3} + end + +snippet when + when ${1:condition} + ${2} + +snippet if + if ${1:condition} + ${2} + end + +snippet if else + if ${1:condition} + ${2} + else + ${3} + end + +snippet unless + unless ${1:condition} + ${2} + end + +snippet while + while ${1:condition} + ${2} + end + +snippet for + for ${1:e} in ${2:c} + ${3} + end + +snippet until + until ${1:condition} + ${2} + end + +snippet module + module ${1:ModuleName} + ${2} + end + +snippet class + class ${1:ClassName} + ${2} + end + +snippet class self +abbr class << self + class << self + ${1} + end + +snippet def + def ${1:method_name} + ${2} + end + +snippet defs +abbr def self.method ... end + def self.${1:class_method_name} + ${2} + end + +snippet atr +abbr attr_reader + attr_reader :${1:attr_names} + +snippet atw +abbr attr_writer + attr_writer :${1:attr_names} + +snippet ata +abbr attr_accessor + attr_accessor :${1:attr_names} + +snippet do var end +abbr do |var| ... end + do |${1:variable}| + ${2} + end + +snippet do end +abbr do ... end + do + ${1} + end + +snippet open + open(${1:"path/or/url/or/pipe"}, "${2:w}") {|${3:io}| ${4} } + +snippet task + desc "${1:Task description\}" + task :${2:task_name => [:dependent, :tasks]} do + ${3} + end + +snippet describe + describe ${1:object} do + ${2} + end + +snippet it + it "${1:description}" do + ${2} + end + +snippet context + context "${1:case}" do + ${2} + end + +snippet before + before do + ${1} + end + +snippet before each + before :each do + ${1} + end + +snippet before all + before :all do + ${1} + end + +snippet after + after do + ${1} + end + +snippet after each + after :each do + ${1} + end + +snippet after all + after :all do + ${1} + end + +snippet subject + subject do + ${1} + end diff --git a/.vim/snippets/tap.snip b/.vim/snippets/tap.snip new file mode 100644 index 0000000..b127dd7 --- /dev/null +++ b/.vim/snippets/tap.snip @@ -0,0 +1,5 @@ +snippet subtest +abbr st + subtest ${1:test_name} => sub { + ${2:# test cases} + }; diff --git a/.vim/snippets/textile.snip b/.vim/snippets/textile.snip new file mode 100644 index 0000000..afd5269 --- /dev/null +++ b/.vim/snippets/textile.snip @@ -0,0 +1,22 @@ +snippet link + "${1:#:title}":${2:#:url} + +snippet link_paste + "${1:#:title}":`getreg('+')` + +snippet image + !${1:#:url}! + +snippet image_paste + !`getreg('+')`! + +snippet pre + <pre><code>${1:#:code}</code></pre> + +snippet collapse +options head + {{collapse + ${1} + }} + +# vim:set noexpandtab diff --git a/.vim/snippets/tt2.snip b/.vim/snippets/tt2.snip new file mode 100644 index 0000000..dff14c7 --- /dev/null +++ b/.vim/snippets/tt2.snip @@ -0,0 +1,24 @@ +snippet if + [% IF ${1:condition} %] + ${2:then} + [% END # IF $1 %] + +snippet ife + [% IF ${1:condition} %] + ${2:then} + [% ELSE %] + ${3:else} + [% END # IF $1 %] + +snippet unless + [% UNLESS ${1:condition} %] + ${2:then} + [% END # UNLESS $1 %] + +snippet foreach + [% FOREACH ${1:element} IN ${2:collection} %] + ${3:loop} + [% END # FOREACH $1 IN $2 %] + +snippet include + [% INCLUDE "${1:path}" %] diff --git a/.vim/snippets/tt2html.snip b/.vim/snippets/tt2html.snip new file mode 100644 index 0000000..822ec7a --- /dev/null +++ b/.vim/snippets/tt2html.snip @@ -0,0 +1 @@ +include tt2.snip diff --git a/.vim/snippets/vim.snip b/.vim/snippets/vim.snip new file mode 100644 index 0000000..82dd8ea --- /dev/null +++ b/.vim/snippets/vim.snip @@ -0,0 +1,14 @@ +# vim:set ft=neosnippet noet: +snippet plugin_config + let ${2:symbol} = neobundle#get('${1:plugin_name}') + function! $2.hooks.on_source(bundle) " {{{ + ${3:TARGET} + endfunction " }}} + unlet $2 + +snippet lazybundle +options head + NeoBundleLazy '${1:owner}/${2:name}' " {{{ + call neobundle#config('$2', { + ${3:config} + }) " }}} diff --git a/.vim/snippets/zsh.snip b/.vim/snippets/zsh.snip new file mode 100644 index 0000000..35fcbf0 --- /dev/null +++ b/.vim/snippets/zsh.snip @@ -0,0 +1,47 @@ +include sh.snip + +snippet length + ${#${1:variable}} + +snippet capitalize + ${(C)${1:variable}} + +snippet downcase + ${(L)${1:variable}} + +snippet upcase + ${(U)${1:variable}} + +snippet keys + ${(k)${1:variable}} + +snippet split + ${(s:${1:pattern}:)${2:variable}} + +snippet join + ${(j:${1:needle}:)${2:variable}} + +snippet split_by_newline +abbr splitlf + ${(f)${1:variable}} + +snippet join_by_newline +abbr joinlf + ${(F)${1:variable}} + +snippet sort_asc + ${(o)${1:variable}} + +snippet sort_desc + ${(O)${1:variable}} + +snippet sort_numeric +abbr sort_num + ${(n)${1:variable}} + +snippet function +abbr func +options head + function ${1:func}() { # {{{ + ${2:#:body} + } # }}} diff --git a/.vim/swp/.gitkeep b/.vim/swp/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/.vim/tools/efm_perl.pl b/.vim/tools/efm_perl.pl new file mode 100755 index 0000000..9e1270d --- /dev/null +++ b/.vim/tools/efm_perl.pl @@ -0,0 +1,67 @@ +#!/usr/bin/env perl + +# stolen from https://github.com/hakobe/dotfiles/blob/master/.vim/tools/efm_perl.pl + +use strict; +use warnings; + +use Cwd; +use File::Basename; +use File::Spec; + +my $file = shift or die "No filename to check!\n"; +my $dir = dirname( $file ) . '/lib'; +my $cwd = cwd(); + +my $error = qr{(.*)\sat\s(.*)\sline\s(\d+)(\.|,\snear\s\".*\"?)}; + +# Error messages to be skipped. +my @skip = ( + + '"DB::single" used only once: possible typo', + 'BEGIN failed--compilation aborted', + +); + +my $skip = join '|', map { quotemeta $_ } @skip; +my @checks; + +push @checks, '-M-circular::require' if `perldoc -l circular::require 2> /dev/null`; +push @checks, '-M-indirect' if `perldoc -l indirect 2> /dev/null`; +push @checks, '-Mwarnings::method' if `perldoc -l warnings::method 2> /dev/null`; +push @checks, '-Mwarnings::unused' if `perldoc -l warnings::unused 2> /dev/null`; + +# uninit is not included in 5.10 and later +push @checks, '-Muninit' if ( $] < 5.010 ) && `perldoc -l uninit 2> /dev/null`; + +my @incs; +push @incs, "-I $cwd/lib"; +push @incs, "-I $cwd/t/lib"; +push @incs, map { "-I $_" } glob("$cwd/modules/*/lib"); + +# need to turn on taint if it's on the shebang line. +# naive check for [tT] switch ... will both t and T ever be used at the same time? +my ( $taint ) = `head -n 1 $file` =~ /\s.*-.*?(t)/i; +push @checks, "-$taint" if defined $taint; + +my $checks = join(' ', @checks); +my $incs = join(' ', @incs); +my $command = (-f "$cwd/cpanfile") || (-f "$cwd/Makefile.PL") ? + "carton exec @incs -- perl @incs @checks -c $file 2>&1" : # cartonのバージョン違いの吸収のために@incsが二回展開されてる + "perl @incs @checks -c $file 2>&1"; + +my ( $message, $extracted_file, $lineno, $rest ); + +for my $line ( `$command` ) { + + chomp $line; + next if $line =~ /$skip/; + $line =~ s/([()])/\\$1/g; + + if ( ( $message, $extracted_file, $lineno, $rest ) = $line =~ /^$error$/ ) { + + $message .= $rest if ($rest =~ s/^,//); + print "$file:$lineno:$message\n"; + + } +} diff --git a/.vim/undo/.gitkeep b/.vim/undo/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/.vim/vimrc b/.vim/vimrc new file mode 100644 index 0000000..2dbcfed --- /dev/null +++ b/.vim/vimrc @@ -0,0 +1,33 @@ +" vim:set et foldmethod=marker: + +let did_load_filetypes = 1 +let g:loaded_2html_plugin = 1 +let g:loaded_getscriptPlugin = 1 +let g:loaded_vimballPlugin = 1 + +function! s:OnLoaded() abort + if !has('vim_starting') + echomsg '---> Reload bundles' + call dein#call_hook('source') + call dein#call_hook('post_source') + endif + + syntax enable + filetype plugin indent on +endfunction + +runtime rc/00_base.vim +runtime rc/00_autocmd.vim +runtime rc/10_dein.vim +runtime rc/20_tab.vim +runtime rc/20_key.vim +runtime rc/20_command.vim + +if !has('vim_starting') + echomsg '---> Reload bundles' + call dein#call_hook('source') + call dein#call_hook('post_source') +endif + +syntax enable +filetype plugin indent on diff --git a/.vimperator/colors/solarized_light.vimp b/.vimperator/colors/solarized_light.vimp new file mode 100644 index 0000000..b525a71 --- /dev/null +++ b/.vimperator/colors/solarized_light.vimp @@ -0,0 +1,59 @@ +hi clear + +hi StatusLine <<CSS + background-color: #fdf6e3; + color: #586e75; + font-size: 16px; + padding: 0.2em 0; + outline: none; +CSS + +hi CmdLine <<CSS + background-color: #fdf6e3; + color: #586e75; + font-size: 16px; + border-top: solid 1px #93a1a1; +CSS + +hi CompItem <<CSS + background-color: #fdf6e3; + color: #586e75; + font-size: 16px; +CSS + +hi CompItem[selected] <<CSS + background-color: #268bd2; + color: #fdf6e3; +CSS + +hi CompTitle <<CSS + background-color: #eee8d5; + color: #657b83; +CSS + +hi ErrorMsg <<CSS + background-color: #dc322f; + color: #fdf6e3; + font-size: 16px; +CSS + +hi Filter <<CSS + color: #b58900; +CSS + +hi Hint <<CSS + z-index: 999; + padding: 0.1em 0.3em; + font-size: 16px; + background-color: rgba(0, 43, 54, 0.8); + color: #fdf6e3; + font-family: monospace; +CSS + +hi HintElem <<CSS + background-color: rgba(253, 246, 227, 0.7); +CSS + +hi HintActive <<CSS + background-color: rgba(220, 50, 47, 0.6); +CSS diff --git a/.vimperatorrc b/.vimperatorrc new file mode 100644 index 0000000..86edc57 --- /dev/null +++ b/.vimperatorrc @@ -0,0 +1,63 @@ +" let {{{ +let g:plugin_loader_roots = "~/devel/src/github.com/vimpr/vimperator-plugins" +let g:plugin_loader_plugins = "_libly,asdfghjkl,feedSomeKeys_3" + +let g:asdfghjkl_default = "true" +let g:asdfghjkl_hintchars = ":asdfghjkl" +" }}} +" set {{{ +set scrollbars +set notabnumbers +set history=10000 +" }}} +" Prefs (firefox) {{{ +set! ui.key.generalAccessKey=0 +set! ui.key.contentAccessKey=0 + +set! browser.tabs.autoHide=false + +set! browser.sessionstore.interval=120000 + +set! javascript.options.jit.chrome=true +set! javascript.options.jit.content=true + +set! browser.tabs.closeWindowWithLastTab=false + +set! browser.startup.page=3 + +set! network.http.pipelining=true +" }}} +" Mapping {{{ +nnoremap j 5<C-e> +nnoremap k 5<C-y> + +" page info +nnoremap <C-g> g<C-g> + +nnoremap <C-q> <Nop> +nnoremap q <Nop> + +nnoremap y :<C-u>js<Space>util.copyToClipboard(buffer.URL)<CR> + +cnoremap <C-n> <Tab> +cnoremap <C-p> <S-Tab> +cnoremap <C-g> <ESC> + +" for AquaSKK +cnoremap <C-j> <Nop> +" }}} +" Command {{{ +command! -nargs=+ sitesearch :exe ":tabopen <args> site:" + content.document.domain +" }}} +" Quickmarks {{{ +silent qmark r http://reader.livedoor.com/reader/ +silent qmark m https://mail.google.com/mail/#mbox +" }}} + +ignorekeys add -except=:,d,t,gT mail\.google\.com + +autocmd VimperatorEnter .* source ~/.vimperatorrc.js + +colorscheme solarized_light + +" vim:set ft=vim foldmethod=marker: diff --git a/.vimperatorrc.js b/.vimperatorrc.js new file mode 100644 index 0000000..7901c43 --- /dev/null +++ b/.vimperatorrc.js @@ -0,0 +1,11 @@ +liberator.globalVariables.hBookmark_shortcuts = { + hintsAdd: 'Ba', + hintsComment: 'Bc', + add: ['C'], + comment: ['c'], +}; +if (typeof hBookmark != 'undefined') { + liberator.loadScript('chrome://hatenabookmark/content/vimperator/plugin/hatenabookmark.js', { + __proto__: this + }); +} diff --git a/.zsh.d/functions/_carton b/.zsh.d/functions/_carton new file mode 100644 index 0000000..bc1a882 --- /dev/null +++ b/.zsh.d/functions/_carton @@ -0,0 +1,70 @@ +#compdef carton + +function _carton () { + local curcontext="$curcontext" state line + typeset -A opt_args + + _arguments -C \ + ':command:->command' \ + '*::options:->options' + + case $state in + command) + _values 'carton commands' \ + version'[Display version]' \ + update'[Update the dependencies]' \ + tree'[Show the tree of dependency graph]' \ + show'[Show the module information]' \ + list'[List dependencies tracked in the cpanfile.snapshot file]' \ + check'[Check if your cpanfile and local environment are in sync]' \ + install'[Install the dependencies]' \ + bundle'[Bundle cached tarballs in vendor/cache]' \ + 'exec[execute your script in a carton local environment]' + ;; + options) + case $line[1] in + update) + _arguments \ + '*:MODULE:_perl_modules' + ret=0 + ;; + show) + _arguments \ + '*:MODULE:_perl_modules' + ret=0 + ;; + list) + _arguments \ + --distfile'[Displays the list of distributions in a distfile format]' + ret=0 + ;; + check|tree|version) + ret=0 + ;; + bundle) + _arguments \ + {-h,--help}'[Show help message]' \ + --no-fatpack'[Skip generating fatpacked "carton" in "vendor/bin"]' + ret=0 + ;; + install) + _arguments \ + {-h,--help}'[Show help message]' \ + --deployment'[Force the deployment mode. See "DEPLOYMENT MODE" above]' \ + --cached'[Locate distribution tarballs in "vendor/cache" rather than fetching them from CPAN mirrors]' \ + --cpanfile'[Specify the alternate path for cpanfile]:cpanfile:_files' \ + --path'[Specify the path to install modules to]:path:_dirs' \ + --without'[You can specify phases or features to exclude, in the comma separated list]:phases_or_features' + ret=0 + ;; + exec) + _normal + ret=0 + ;; + esac + esac +} + +_carton "$@" + +# vim:set ft=zsh: diff --git a/.zsh.d/functions/_padrino b/.zsh.d/functions/_padrino new file mode 100644 index 0000000..121f39e --- /dev/null +++ b/.zsh.d/functions/_padrino @@ -0,0 +1,133 @@ +#compdef padrino + +_runtime_options=( + --help'[Show help usage]' \ + {-e,--environment}'[Padrino Environment]:ENVIRONMENT:(test development production)' \ + {-c,--chdir}'[Change to dir before starting]:CHDIR:_files -/' +) + +_padrino() { + local curcontext="$curcontext" state line + typeset -A opt_args + + _arguments -C \ + ':command:->command' \ + '*::options:->options' + + case $state in + command) + _values "padrino subcommands" \ + {g,gen,generate}'[Executes the Padrino generator with given options]' \ + {c,console}'[Boots up the Padrino application irb console]' \ + {s,start}'[Starts the Padrino application]' \ + help'[Describe available tasks or one specific task]' \ + rake'[Execute rake tasks]' \ + stop'[Stops the Padrino application]' \ + version'[Show current Padrino Version]' + ;; + options) + case $line[1] in + start|s) + _arguments $_runtime_options \ + {-a,--server}'[Rack Handler (default: autodetect)]:SERVER' \ + {-p,--port}'[Use PORT (default: 3000)]:N' \ + {-h,--host}'[Bind to HOST address (default: 0.0.0.0)]:HOST' \ + {-d,--daemonize}'[Run daemonized in the buckground]' \ + {--debug}'[Set debugging flags]' \ + {-e,--environment}'[Padrino Environment]:ENVIRONMENT:(test development production)' \ + ret=0 + ;; + stop) + _arguments $_runtime_options \ + {-p,--pid}'[File to store pid (default: tmp/pids/server.pid)]:PID' + ret=0 + ;; + generate|gen|g) + __padrino_generate + ;; + esac + ;; + esac +} + +__padrino_generate() { + local curcontext="$curcontext" state line + typeset -A opt_args + + _generators_options=( + --help'[Show help usage]' \ + {-r,--root}'[The root destination (default: .)]:ROOT:_files -/' \ + {-d,--destroy} + ) + + _arguments -C \ + ':command:->command' \ + '*::options:->options' + + case $state in + command) + _arguments -C $_generators_options + _values 'padrino generators' \ + 'project' \ + 'app' \ + 'mailer' \ + 'controller' \ + 'model' \ + 'migration' \ + 'plugin[sets up a plugin within a Padrino application]' + ;; + options) + case $line[1] in + app) + _arguments $_generators_options \ + {-i--tiny}'[Generate tiny app skeleton]' + ret=0 + ;; + controller) + _arguments $_generators_options \ + {-a,--app}'[The application destination path]:APP:_files -/' + ret=0 + ;; + mailer) + _arguments $_generators_options \ + {-a,--app}'[The application destination path]:APP:_files -/' + ret=0 + ;; + migration) + _arguments $_generators_options + ret=0 + ;; + model) + _arguments $_generators_options \ + {-a,--app}'[The application destination path]:APP:_files -/' \ + {-s,--skip-migration} + ret=0 + ;; + plugin) + _arguments $_generators_options \ + {-l,--list}'[list available plugins]' + ret=0 + ;; + project) + _arguments $_generators_options \ + '*:APP' \ + {-n,--app}'[The application name]:APP' \ + {-b,--bundle}'[Run bundle install]' \ + --dev'[Use padrino from a git checkout]' \ + {-i,--tiny}'[Generate tiny app skeleton]' \ + {-a,--adapter}'[SQL adapter for ORM (default: sqlite)]:ADAPTER:(sqlite mysql mysql2 postgres)' \ + {-p,--template}'[Generate project from template]:TEMPLATE:_files' \ + {-d,--orm}'[The database engine component (default: none)]:ORM:(activerecord mini_record datamapper mongomapper mongoid sequel couchrest ohm mongomatic ripple none)' \ + {-t,--test}'[The testing framework component (default: none)]:TEST:(rspec shoulda cucumber bacon testspec riot minitest)' \ + {-m,--mock}'[The mocking library component (default: none)]:MOCK:(mocha rr none)' \ + {-s,--script}'[The javascript library component (default: none)]:SCRIPT:(jquery prototype rightjs mootools extcore dojo none)' \ + {-e,--renderer}'[The template engine component (default: haml)]:RENDERER:(haml erb liquid slim none)' \ + {-c,--stylesheet}'[The stylesheet component (default: none)]:STYLESHEET:(less sass compass scss none)' + esac + ;; + esac +} + +_padrino "$@" + +# vim:set ft=zsh diff --git a/.zsh.d/functions/_pkgutil b/.zsh.d/functions/_pkgutil new file mode 100644 index 0000000..151e6ba --- /dev/null +++ b/.zsh.d/functions/_pkgutil @@ -0,0 +1,111 @@ +#compdef pkgutil + +function _pkgutil() { + local curcontext=$curcontext state line ret=1 + declare -A opt_args + + _arguments -C \ + '(-): :->command' \ + '(-)*:: :->option-or-argument' + + case $state in + command) + __pkgutil_commands && return 0 + ;; + option-or-argument) + if (( $+functions[__pkgutil_$words[1]] )); then + _call_function ret __pkgutil_$words[1] + else + : # TODO + fi + ;; + esac + + return $ret +} + +function __pkgutil_commands() { + local curcontext=$curcontext state line ret=1 + declare -A opt_args + + local -a __pkgutil_receipt_database_commands + __pkgutil_receipt_database_commands=( + {--packages,--pkgs}:'List all installed package IDs on the specified --volume' + --pkgs-plist:'List all installed package IDs on the specified --volume in Mac OS X plist(5) format' + --files:'List all of the files installed under the package-id' + --export-plist:'Print all receipt information about the specified package-id in the standard Mac OS X plist(5) format' + --verify:'Run repair_packages(8) to verify the specified package-id' + --repair:'Run repair_packages(8) to repair the specified package-id' + --pkg-info:'Print extended information about the specified package-id' + --pkg-info-plist:'Print extended information about the specified package-id in Mac OS X plist(5) format' + --forget:'Discard all receipt data about package-id, but do not touch the installed files' + --learn:'Update the ACLs of the given path in the receipt identified by --edit-pkg' + --pkg-groups:'List all of the package groups this package-id is a member of' + --groups:'List all of the package groups on the specified --volume' + --groups-plist:'List all of the package groups on the specified --volume in Mac OS X plist(5) format.' + --group-pkgs:'List all of the packages that are members of this group-id.' + --file-info:'Show the metadata known about path.' + --file-info-plist:'Show the metadata known about path in Mac OS X plist(5) format.' + ) + + local -a __pkgutil_options + __pkgutil_options=( + {-h,--help}':A brief summary of commands and usage' + {-f,--force}":Don't ask for confirmation before performing a potentially destructive or ambiguous operation" + {-v,--verbose}':Output in a "human-readable" format with extra headers, footers, indentation, and other contextual information' + --volume":Perform all operations on the specified volume or home directory. The root volume '/' will be used if unspecified" \ + --edit-pkg':Specifies an existing receipt to be modified in-place by --learn' + --only-files':List only files (not directories) in --files listing' + --only-dirs':List only directories (not files) in --files listing' + --regexp":Try to match package-id arguments as a regular expression if an exact match isn't found. See egrep(1) and re_format(7) for syntax" + ) + + local -a __pkgutil_file_commands + __pkgutil_file_commands=( + --expand:'Expand the flat package at pkg-path into a new directory specified by dir-path' + --flatten:'Flatten the dir-path into a new flat package created at pkg-path' + --bom:'Extract any BOM files from the flat pkg at path into /tmp and return the filename(s).' + --payload-files:'List the files archived within the payload of the uninstalled flat package(s) contained at path' + --check-signature:'Check the validity and trust of the signature on the package at pkg-path.' + ) + + _describe -t pkgutil-options "Options" __pkgutil_options && ret=0 + _describe -t pkgutil-receipt-database-commands "Receipt Database Commands" __pkgutil_receipt_database_commands && ret=0 + _describe -t pkgutil-file-commands "File Commands" __pkgutil_file_commands && ret=0 + + return $ret +} + +function __pkgutil_package_ids() { + local -a package_ids + package_ids=($(pkgutil --pkgs 2>/dev/null)) + _values 'package-id' $package_ids +} + +function __pkgutil_group_ids() { + local -a group_ids + group_ids=($(pkgutil --groups 2>/dev/null)) + _values 'group-id' $group_ids +} + +function __pkgutil_--volume() { _arguments -C '*:path:_dirs' && return 0 } +function __pkgutil_--edit-pkg() { _arguments -C '*:package-id:__pkgutil_package_ids' && return 0 } +function __pkgutil_--verify() { _arguments -C '*:package-id:__pkgutil_package_ids' && return 0 } +function __pkgutil_--repair() { _arguments -C '*:package-id:__pkgutil_package_ids' && return 0 } +function __pkgutil_--pkg-info() { _arguments -C '*:package-id:__pkgutil_package_ids' && return 0 } +function __pkgutil_--pkg-info-plist() { _arguments -C '*:package-id:__pkgutil_package_ids' && return 0 } +function __pkgutil_--forget() { _arguments -C '*:package-id:__pkgutil_package_ids' && return 0 } +function __pkgutil_--learn() { _arguments -C '*:path:_files' && return 0 } +function __pkgutil_--pkg-groups() { _arguments -C '*:package-id:__pkgutil_package_ids' && return 0 } +function __pkgutil_--group-pkgs() { _arguments -C '*:group-id:__pkgutil_group_ids' && return 0 } +function __pkgutil_--file-info() { _arguments -C '*:path:_files' && return 0 } +function __pkgutil_--file-info-plist() { _arguments -C '*:path:_files' && return 0 } +function __pkgutil_--files() { _arguments -C '*:package-id:__pkgutil_package_ids' && return 0 } +function __pkgutil_--export-plist() { _arguments -C '*:package-id:__pkgutil_package_ids' && return 0 } +function __pkgutil_--bom() { _arguments -C '*:path:_files' && return 0 } +function __pkgutil_--payload-files() { _arguments -C '*:path:_files' && return 0 } +function __pkgutil_--check-signature() { _arguments -C '*:pkg-path:_files' && return 0 } +# TODO function __pkgutil_--expand +# TODO function __pkgutil_--flatten + +# vim:set ft=zsh: diff --git a/.zsh.d/functions/_prove b/.zsh.d/functions/_prove new file mode 100644 index 0000000..d177c49 --- /dev/null +++ b/.zsh.d/functions/_prove @@ -0,0 +1,50 @@ +#compdef prove + +typeset -A options +local context state line + +_arguments -s -C \ + '*:TEST:_files' \ + {-a,--archive}'[Store the resulting TAP in an archive file.]':OUTPUT:_files \ + {-b,--blib}"[Add 'blib/lib' and 'blib/arch' to the path for your tests]" \ + {-c,--color}'[Colored test output (default).]' \ + {-o,--comments}'[Show comments.]' \ + --count'[Show the X/Y test count when not verbose (default)]' \ + --directives'[Only show results with TODO or SKIP directives.]' \ + {-D,--dry}'[Dry run. Show test that would have run.]' \ + {-e,--exec}"[Interpreter to run the tests ('' for compiled tests.)]":EXECUTOR \ + --ext"[Set the extension for tests (default '.t')]":EXTENSION \ + {-f,--failures}'[Show failed tests.]' \ + --formatter'[Result formatter to use. See FORMATTERS.]':FORMATTER \ + --harness'[Define test harness to use. See TAP::Harness.]':HARNESS \ + {-?,-h,--help}'[Display this help]' \ + -I'[Library paths to include.]':DIR:_dirs \ + --ignore-exit'[Ignore exit status from test scripts.]' \ + {-j,--jobs}'[Run N test jobs in parallel (try 9.)]':N \ + {-l,--lib}"[Add 'lib' to the path for your tests (-Ilib).]" \ + -M'[Load a module.]':MODULE:_perl_modules \ + {-H,--man}'[Longer manpage for prove]' \ + {-m,--merge}"[Merge test scripts' STDERR with their STDOUT.]" \ + --nocolor'[Do not color test output.]' \ + --nocount'[Disable the X/Y test count.]' \ + --norc"[Don't process default .proverc]" \ + --normalize'[Normalize TAP output in verbose output]' \ + -P'[Load plugin (searches App::Prove::Plugin::*.)]':PLUGIN \ + {-p,--parse}'[Show full list of TAP parse errors, if any.]' \ + {-q,--quiet}'[Suppress some test output while running tests.]' \ + {-Q,--QUIET}'[Only print summary results.]' \ + --rc'[Process options from rcfile]':RCFILE:_files \ + {-r,--recurse}'[Recursively descend into directories.]' \ + --reverse'[Run the tests in reverse order.]' \ + {-s,--shuffle}'[Run the tests in random order.]' \ + --source'[Load and/or configure a SourceHandler. See SOURCE HANDLERS.]':HANDLER \ + --state"[Control prove's persistent state.]":OPTION:'(last failed passed all hot todo slow fast new old fresh save)' \ + -T'[Enable tainting checks.]' \ + -t'[Enable tainting warnings.]' \ + --timer'[Print elapsed time after each test.]' \ + --trap'[Trap Ctrl-C and print summary on interrupt.]' \ + {-v,--verbose}'[Print all test lines.]' \ + -W'[Enable fatal warnings.]' \ + -w'[Enable warnings.]' + +# vim:set ft=zsh: diff --git a/.zsh.d/functions/_proxychains4 b/.zsh.d/functions/_proxychains4 new file mode 100644 index 0000000..c9584cd --- /dev/null +++ b/.zsh.d/functions/_proxychains4 @@ -0,0 +1,16 @@ +#compdef proxychains4 + +local curcontext="$curcontext" state line ret=1 + +_arguments -C \ + '*:: :->app' && ret=0 + +case "$state" in + app) + _normal && ret=0 + ;; +esac + +return ret + +# vim: set ft=sh: diff --git a/.zsh.d/functions/_rails b/.zsh.d/functions/_rails new file mode 100644 index 0000000..7519ac1 --- /dev/null +++ b/.zsh.d/functions/_rails @@ -0,0 +1,216 @@ +#compdef rails + +_runtime_options=( + '(-f --force -s --skip)'{-f,--force}'[Overwrite files that already exist]' + {-p,--pretend}'[Run but do not make any changes]' + {-q,--quiet}'[Supress status output]' + '(-s --skip -f --force)'{-s,--skip}'[Skip files that already exist]' +) + +_rails() { + local curcontext="$curcontext" state line + typeset -A opt_args + + _arguments -C \ + ':command:->command' \ + '*::options:->options' + + case $state in + command) + _values "rails subcommands" \ + {g,generate}'[Generate new code]' \ + {c,console}'[Start the Rails console]' \ + {s,server}'[Start the Rails server]' \ + {db,dbconsole}'[Start a console for the database specified in config/database.yml]' \ + {d,destroy}'[Undo code generated with "generate"]' \ + {r,runner}'[Run a piece of code in the application environment]' \ + benchmarker'[See how fast a piece of code runs]' \ + new'[Create a new Rails application]' \ + application'[Generate the Rails application code]' \ + profiler'[Get profile information from a piece of code]' \ + plugin'[Install a plugin]' + ;; + options) + case $line[1] in + console|c) + _arguments \ + {-h,--help}'[Show help message]' \ + --sandbox'[Rollback database modifications on exit]' \ + --debugger'[Enable ruby-debugging for the console]' + ret=0 + ;; + server|s) + _arguments \ + {-h,--help}'[Show help message]' \ + {-p,--port}'[Runs Rails on the specified port]:port' \ + {-b,--binding}'[Binds Rails to the specified ip]:ip' \ + {-c,--config}'[Use custom rackup configuration file]:file:_files' \ + {-d,--daemon}'[Make server run as a Daemon]' \ + {-u,--debugger}'[Enable ruby-debugging for the server]' \ + {-e,--environment}'[Specifies the environment to run this server under (test/development/production)]:name:(test development production)' \ + {-p,--pid}'[Specifies the PID file]:pid' + ret=0 + ;; + dbconsole|db) + _arguments \ + {-h,--help}'[Show help message]' \ + {-p,--include-password}'[Automatically provide the password from database.yml]' \ + --mode'[Automatically put the sqlite3 database in the specified mode]:MODE:(html list line column)' \ + --header + ret=0 + ;; + application|new) + _arguments \ + '*:APP_PATH:_files -/' \ + {-h,--help}'[Show help message]' \ + $_runtime_options \ + {-r,--ruby}'[Path to the Ruby binary of your choice]:PATH' \ + {-b,--builder}'[Path to a application builder (can be a filesystem path or URL)]:BUILDER:_files' \ + {-m,--template}'[Path to an application template (can be a filesystem path or URL)]:TEMPLATE:_files' \ + --skip-gemfile"[Don't create a Gemfile]" \ + "(--skip-gemfile --skip-bundle)--skip-bundle[Don't run bundle install]" \ + {-G,--skip-git}'[Skip Git ignores and keeps]' \ + {-O,--skip-active-record}'[Skip Active Record files]' \ + {-S,--skip-sprockets}'[Skip Sprockets files]' \ + {-d,--database}'[Preconfigure for selected database]:DATABASE:(mysql oracle postgresql sqlite3 frontbase ibm_db sqlserver jdbcmysql jdbcsqlite3 jdbcpostgresql jdbc)' \ + '(-J --skip-javascript -j --javascript)'{-j,--javascript}'[Preconfigure for selected JavaScript library]:JAVASCRIPT' \ + '(-J --skip-javascript -j --javascript)'{-J,--skip-javascript}'[Skip JavaScript files]' \ + '(--dev --edge)--dev[Setup the application with Gemfile pointing to your Rails checkout]' \ + '(--edge --dev)--edge[Setup the application with Gemfile pointing to Rails repository]' \ + {-T,--skip-test-unit}'[Skip Test::Unit files]' \ + --old-style-hash"[Force using old style hash (:foo => 'bar') on Ruby >= 1.9]" + ;; + generate|g) + __rails_generate + ;; + esac + ;; + esac +} + +__rails_generate() { + local curcontext="$curcontext" state line + typeset -A opt_args + + _generators_optins=( + --skip-namespace'[Skip namespace (affects only isolated applications)]' \ + --old-style-hash"[Force using old style hash (:foo => 'bar') on Ruby >= 1.9]" \ + ) + + _arguments -C \ + ':command:->command' \ + '*::options:->options' + + case $state in + command) + _arguments -C $_runtime_options + _values 'rails generators' \ + 'assets[Stubs out new asset placeholders.]' \ + 'controller[Stubs out a new controller and its views.]' \ + 'generator[Stubs out a new generator at lib/generators.]' \ + 'helper[Stubs out a new helper.]' \ + 'integration_test[Create rails files for integration_test generator]' \ + 'mailer[Stubs out a new maiiler and its views.]' \ + 'migration[Create rails files for migration generator.]' \ + 'model[Create rails files for model generator.]' \ + 'observer[Create rails files for observer generator.]' \ + 'performance_test[Create rails files for performance_test generator.]' \ + 'resource[Create rails files for resource generator.]' \ + 'scaffold[Scaffolds an entire resource, from model and migration to controller and views, along with a full test suite]' \ + 'scaffold_controller[Stubs out a scaffolded controller and its views.]' \ + 'session_migration[Create rails files for session_migration generator.]' \ + 'task[Stubs out a new Rake task.]' + ;; + options) + case $line[1] in + assets) + _arguments -C $_runtime_options $_generators_optins \ + {-j,--javascripts}'[Generate JavaScripts]:boolean:(true false)' \ + {-y,--stylesheets}'[Generate Stylesheets]:boolean:(true false)' \ + {-je,--javascript-engine}'[Engine for JavaScripts]:JAVASCRIPT_ENGINE' \ + {-se,--stylesheet-engine}'[Engine for Stylesheets]:STYLESHEET_ENGINE' + ;; + controller) + _arguments -C $_runtime_options $_generators_optins \ + {-e,--template-engine}'[Template engine to be invoked]:NAME' \ + {-t,--test-framework}'[Test framework to be invoked]:NAME' \ + --helper'[Indicates when to generate helper]:boolean:(true false)' \ + --assets'[Indicates where to generate assets]:boolean:(true false)' + ;; + generatorer) + _arguments -C $_runtime_options $_generators_optins \ + --namespace'[Namespace generator under lib/generators/name]:boolean:(true false)' + ;; + helper) + _arguments -C $_runtime_options $_generators_optins \ + {-t,--test-framework}'[Test framework to be invoked]:NAME' + ;; + integration_test) + _arguments -C $_runtime_options $_generators_optins \ + --integration-tool'[Integration tool to be invoked]:NAME' + ;; + mailer) + _arguments -C $_runtime_options $_generators_optins \ + {-e,--template-engine}'[Template engine to be invoked]:NAME' \ + {-t,--test-framework}'[Test framework to be invoked]:NAME' + ;; + migration) + _arguments -C $_runtime_options $_generators_optins \ + {-o,--orm}'[ORM to be invoked]:NAME' + ;; + model) + _arguments -C $_runtime_options $_generators_optins \ + {-o,--orm}'[ORM to be invoked]:NAME' + ;; + observer) + _arguments -C $_runtime_options $_generators_optins \ + {-o,--orm}'[ORM to be invoked]:NAME' + ;; + performance_test) + _arguments -C $_runtime_options $_generators_optins \ + --performance-tool'[Performance tool to be invoked]:NAME' + ;; + resource) + _arguments -C $_runtime_options $_generators_optins \ + --force-plural'[Forces the use of a plural ModelName]' \ + {-o,--orm}'[ORM to be invoked]:NAME' \ + {-c,--resource-controller}'[Resource controller to be invoked]:NAME' \ + {-a,--actions}'[Resource controller to be invoked]:ACTION' \ + {-e,--template-engine}'[Template engine to be invoked]:NAME' \ + --helper'[Indicates when to generate helper]:boolean:(true false)' \ + --assets'[Indicates where to generate assets]:boolean:(true false)' + ;; + scaffold) + _arguments -C $_runtime_options $_generators_optins \ + {-o,--orm}'[ORM to be invoked]:NAME' \ + {-c,--scaffold-controller}'[Scaffold controller to be invoked]:NAME' \ + {-e,--template-engine}'[Template engine to be invoked]:NAME' \ + {-y,--stylesheets}'[Generate Stylesheets]:boolean:(true false)' \ + {-se,--stylesheet-engine}'[Engine for Stylesheets]:STYLESHEET_ENGINE' \ + --force-plural'[Forces the use of a plural ModelName]' \ + --assets'[Indicates where to generate assets]:boolean:(true false)' \ + --helper'[Indicates when to generate helper]:boolean:(true false)' + ;; + scaffold_controller) + _arguments -C $_runtime_options $_generators_optins \ + {-o,--orm}'[ORM to be invoked]:NAME' \ + {-e,--template-engine}'[Template engine to be invoked]:NAME' \ + {-t,--test-framework}'[Test framework to be invoked]:NAME' \ + --force-plural'[Forces the use of a plural ModelName]' \ + --helper'[Indicates when to generate helper]:boolean:(true false)' + ;; + session_migration) + _arguments -C $_runtime_options $_generators_optins \ + {-o,--orm}'[ORM to be invoked]:NAME' + ;; + task) + _arguments -C $_runtime_options $_generators_optins + ;; + esac + ;; + esac +} + +_rails "$@" + +# vim:set ft=zsh diff --git a/.zsh.d/functions/_tsocks b/.zsh.d/functions/_tsocks new file mode 100644 index 0000000..52c75f9 --- /dev/null +++ b/.zsh.d/functions/_tsocks @@ -0,0 +1,16 @@ +#compdef tsocks + +local curcontext="$curcontext" state line ret=1 + +_arguments -C \ + '*:: :->app' && ret=0 + +case "$state" in + app) + _normal && ret=0 + ;; +esac + +return ret + +# vim: set ft=sh: diff --git a/.zsh.d/functions/git_info b/.zsh.d/functions/git_info new file mode 100644 index 0000000..43c1c09 --- /dev/null +++ b/.zsh.d/functions/git_info @@ -0,0 +1,107 @@ +# vim:set ft=zsh foldmethod=marker: + +git_info() { # {{{ + # http://d.hatena.ne.jp/uasi/20091025/1256458798 + if [[ $(git rev-parse --is-inside-work-tree 2>/dev/null) != "true" ]]; then + return + fi + + local git==git + local st color annotation stashes + + local name=$($git symbolic-ref --short HEAD 2> /dev/null) + name=${name:="(detached)"} + + local git_dir=$($git rev-parse --git-dir 2> /dev/null) + local action=$(VCS_INFO_git_getaction "$git_dir") + action=${action:+"($action)"} + + # Remote and Local changes {{{ + local \ + threshold \ + current_remote \ + merge_name \ + remote_ref \ + revs_count \ + behind_count \ + ahead_count \ + behind_and_ahead + + current_remote=$($git config branch.${name}.remote 2> /dev/null) + merge_name=$($git config branch.${name}.merge 2> /dev/null) + + local is_tracked + local -a remote_local_revs + if [[ "." = "$current_remote" ]] || [[ "x" = "x$current_remote" ]]; then + # Clone from local + remote_ref=$merge_name + remote_local_revs=($($git rev-list --left-right ${merge_name}...HEAD)) + is_tracked="" + else + remote_ref="refs/remotes/${current_remote}/${merge_name#refs/heads/}" + remote_local_revs=($($git rev-list --left-right ${remote_ref}...HEAD)) + is_tracked=" %{${fg[green]}%}♺%{${reset_color}%}" + fi + + local ahead_commits_color="${fg[green]}" + local behind_commits_color="${fg[red]}" + local ahead_annotation="+" + local behind_annotation="-" + + revs_count=$#remote_local_revs + + local -a behind_commits ahead_commits + behind_commits=(${(M)remote_local_revs:#<*}) + ahead_commits=(${(M)remote_local_revs:#>*}) + ahead_count=$#ahead_commits + behind_count=$#behind_commits + + if [[ $ahead_count -gt 0 ]]; then + behind_and_ahead="${behind_and_ahead} %{$ahead_commits_color%}${ahead_annotation}${ahead_count}%f%b" + fi + if [[ $behind_count -gt 0 ]]; then + behind_and_ahead="${behind_and_ahead} %{$behind_commits_color%}${behind_annotation}${behind_count}%f%b" + fi + # }}} + + # stashes count {{{ + declare -a stashes_count + local stash_annotation="⟐" + stashes_count=($($git stash list --format='format:%h' 2> /dev/null)) + if [[ $#stashes_count > 0 ]]; then + stashes=" %{${fg[yellow]}%}${stash_annotation}$#stashes_count" + fi + # }}} + + st=$($git status --short --porcelain -b 2> /dev/null) + + # Staged changes {{{ + if [[ -n `echo "$st" | grep "^[UMADRC]"` ]]; then + # Staged + color=%F{yellow} + annotation="${annotation}${color}*" + fi + # }}} + + # Untracked changes {{{ + if [[ -n `echo "$st" | grep "??"` ]]; then + # Untracked + color=%F{yellow} + annotation="${annotation}${color}?%f" + fi + # }}} + + # Changed, but not staged {{{ + if [[ -n `echo "$st" | grep "^[ ][MD]"` ]]; then + # Changed, but not staged + color=%F{red} + annotation="${annotation}${color}!%f" + fi + # }}} + + if [[ -z "$color" ]]; then + color=%F{green} + fi + + echo "${color}${name}${action}${annotation}${behind_and_ahead}${stashes}%f%b${is_tracked}" +} # }}} diff --git a/.zsh.d/functions/gyapbox b/.zsh.d/functions/gyapbox new file mode 100644 index 0000000..a42aaf6 --- /dev/null +++ b/.zsh.d/functions/gyapbox @@ -0,0 +1,45 @@ +# vim:set ft=zsh: + +function gyapbox() { + local base_dir=~/Dropbox/Public/g + local enable_notify=0 + + if whence terminal-notifier >/dev/null; then + enable_notify=1 + fi + + if [[ -z "$DROPBOX_USER_ID" ]]; then + echo "\$DROPBOX_USER_ID must be specified" + return 1 + fi + + if [[ ! -d $base_dir ]]; then + echo "\$base_dir is not found" + return 1 + fi + + local preview + + if [[ $1 = '-P' ]]; then + preview="-P" + fi + + local timestamp_hash="$(date +%s | md5)" + local image_filename="${timestamp_hash}.png" + local image_path="$base_dir/$image_filename" + + if [ $enable_notify ]; then + terminal-notifier -message "Take a screen capture" -title "Gyapbox" + fi + screencapture $preview -i "$base_dir/$image_filename" + + if [[ -e "$image_path" ]]; then + local url="http://dl.dropboxusercontent.com/u/$DROPBOX_USER_ID/g/$image_filename" + + if [ $enable_notify ] && [[ -n "$url" ]]; then + terminal-notifier -message "Captured" -title "Gyapbox" -open "$url" + fi + + echo -n $url | pbcopy + fi +} diff --git a/.zsh.d/functions/llenv_version_origin b/.zsh.d/functions/llenv_version_origin new file mode 100644 index 0000000..925b076 --- /dev/null +++ b/.zsh.d/functions/llenv_version_origin @@ -0,0 +1,19 @@ +llenv_version_origin() { + local llenv="$1" + local llenv_root="$($llenv root)" + local global_version_file="${llenv_root}/version" + local version_origin="$($llenv version-origin)" + + local version_source + if [[ $version_origin = $global_version_file ]]; then + version_source='global' + elif [[ -f $version_origin ]]; then + version_source='local' + else + version_source='shell' + fi + + echo $version_source +} + +# vim:set ft=zsh: diff --git a/.zsh.d/functions/prompt_aereal_setup b/.zsh.d/functions/prompt_aereal_setup new file mode 100644 index 0000000..26887e1 --- /dev/null +++ b/.zsh.d/functions/prompt_aereal_setup @@ -0,0 +1,81 @@ +# vim:set ft=zsh foldmethod=marker: + +function prompt_aereal_setup() { # {{{ + if ! (which add-zsh-hook > /dev/null); then + autoload -Uz add-zsh-hooks + fi + add-zsh-hook precmd aereal_update_prompt +} # }}} + +function detect_ruby_version() { # {{{ + which rbenv > /dev/null 2>&1 + if [ $? -ne 0 ]; then + return + fi + echo "ruby-$(rbenv version-name)" +} # }}} + +function detect_perl_version() { # {{{ + which plenv > /dev/null 2>&1 + if [ $? -ne 0 ]; then + return + fi + echo "perl-$(plenv version-name)" +} # }}} + +function detect_python_version() { # {{{ + which pyenv > /dev/null 2>&1 + if [ $? -ne 0 ]; then + return + fi + echo "python-$(pyenv version-name)" +} # }}} + +function git_repository_relative_dir() { # {{{ + if ! git rev-parse --is-inside-work-tree 1>/dev/null 2>&1; then + return + fi + + local project repository_dir prefix + repository_dir=${${$(git rev-parse --show-cdup 2>/dev/null):-"."}:a} + project=${repository_dir:t} + prefix=$(git rev-parse --show-prefix 2>/dev/null) + echo "${project}${prefix:+":$prefix"}" +} # }}} + +function aereal_update_prompt() { # {{{ + local \ + ruby_version \ + perl_version \ + additional_info \ + current_working_directory \ + git_info \ + top_line \ + command_line + + ruby_version="%{${fg[red]}%}$(detect_ruby_version)%{${reset_color}%}" + perl_version="%{${fg[blue]}%}$(detect_perl_version)%{${reset_color}%}" + python_version="%{${fg[green]}%}$(detect_python_version)%{${reset_color}%}" + + git_info=$(git_info) + git_info=${git_info:+" [$git_info]"} + + if git rev-parse --is-inside-work-tree 1>/dev/null 2>&1; then + current_working_directory="%{${fg[yellow]}%}$(git_repository_relative_dir)%{${reset_color}%}" + else + current_working_directory="%{${fg[magenta]}%}%~%{${reset_color}%}" + fi + + additional_info="${ruby_version} ${perl_version} ${python_version}" + + top_line="${current_working_directory:+"(${current_working_directory})"}${git_info}" + + ok_prompt=" %{${fg[yellow]}%}X | _ | X%{${reset_color}%} < " + ng_prompt=" %{${fg[red]}%}X > _ < X%{${reset_color}%} < " + command_line="%(?,$ok_prompt,$ng_prompt)" + + PROMPT="$(echo -n "${top_line}\n${command_line}")" + RPROMPT=${additional_info:+"($additional_info)"} +} + +prompt_aereal_setup "$@" diff --git a/.zsh.d/functions/prompt_aereal_unicode_setup b/.zsh.d/functions/prompt_aereal_unicode_setup new file mode 100644 index 0000000..208fe17 --- /dev/null +++ b/.zsh.d/functions/prompt_aereal_unicode_setup @@ -0,0 +1,81 @@ +# vim:set ft=zsh foldmethod=marker: + +function prompt_aereal_unicode_setup() { # {{{ + if ! (which add-zsh-hook > /dev/null); then + autoload -Uz add-zsh-hooks + fi + add-zsh-hook precmd aereal_unicode_update_prompt +} # }}} + +function detect_ruby_version() { # {{{ + which rbenv > /dev/null 2>&1 + if [ $? -ne 0 ]; then + return + fi + echo "ruby-$(rbenv version-name)" +} # }}} + +function detect_perl_version() { # {{{ + which plenv > /dev/null 2>&1 + if [ $? -ne 0 ]; then + return + fi + echo "perl-$(plenv version-name)" +} # }}} + +function detect_python_version() { # {{{ + which pyenv > /dev/null 2>&1 + if [ $? -ne 0 ]; then + return + fi + echo "python-$(pyenv version-name)" +} # }}} + +function git_repository_relative_dir() { # {{{ + if ! git rev-parse --is-inside-work-tree 1>/dev/null 2>&1; then + return + fi + + local project repository_dir prefix + repository_dir=${${$(git rev-parse --show-cdup 2>/dev/null):-"."}:a} + project=${repository_dir:t} + prefix=$(git rev-parse --show-prefix 2>/dev/null) + echo "${project}${prefix:+":$prefix"}" +} # }}} + +function aereal_unicode_update_prompt() { # {{{ + local \ + ruby_version \ + perl_version \ + additional_info \ + current_working_directory \ + git_info \ + top_line \ + command_line + + ruby_version="%{${fg[red]}%}$(detect_ruby_version)%{${reset_color}%}" + perl_version="%{${fg[blue]}%}$(detect_perl_version)%{${reset_color}%}" + python_version="%{${fg[green]}%}$(detect_python_version)%{${reset_color}%}" + + git_info=$(git_info) + git_info=${git_info:+" [$git_info]"} + + if git rev-parse --is-inside-work-tree 1>/dev/null 2>&1; then + current_working_directory="%{${fg[yellow]}%}$(git_repository_relative_dir)%{${reset_color}%}" + else + current_working_directory="%{${fg[magenta]}%}%~%{${reset_color}%}" + fi + + additional_info="${ruby_version} ${perl_version} ${python_version}" + + top_line="${current_working_directory:+"(${current_working_directory})"}${git_info}" + + ok_prompt=" %{${fg[yellow]}%}✘╹◡╹✘%{${reset_color}%} < " + ng_prompt=" %{${fg[red]}%}✘>﹏<✘%{${reset_color}%} < " + command_line="%(?,$ok_prompt,$ng_prompt)" + + PROMPT="$(echo -n "${top_line}\n${command_line}")" + RPROMPT=${additional_info:+"($additional_info)"} +} + +prompt_aereal_unicode_setup "$@" diff --git a/.zsh.d/functions/prompt_lambda_setup b/.zsh.d/functions/prompt_lambda_setup new file mode 100644 index 0000000..ced2265 --- /dev/null +++ b/.zsh.d/functions/prompt_lambda_setup @@ -0,0 +1,79 @@ +function prompt_lambda_setup() { # {{{ + if ! (whence add-zsh-hook >/dev/null); then + autoload -Uz add-zsh-hooks + fi + add-zsh-hook precmd __prompt_lambda_update + + # vcs_info configuration {{{ + autoload -Uz vcs_info + zstyle ':vcs_info:*' max-exports 3 + zstyle ':vcs_info:*' enable git + zstyle ':vcs_info:git:*' formats '[%b]' '%c%u %m' + zstyle ':vcs_info:git:*' actionformats '[%b]' '%c%u %m' '<!%a>' + zstyle ':vcs_info:git:*' check-for-changes true + zstyle ':vcs_info:git:*' stagedstr '+' + zstyle ':vcs_info:git:*' unstagedstr '-' + # }}} + + autoload -Uz llenv_version_origin +} # }}} + +function __prompt_lambda_update() { # {{{ + # components {{{ + local ok_lambda="%F{cyan}λ%f" + local bad_lambda="%F{red}λ%f" + local command_line="%(?.${ok_lambda}.${bad_lambda}) ... " + local working_directory="%F{cyan}%~%f" + local accessory_info="${working_directory}" + local git_msg + + # Git info {{{ + LANG=C vcs_info + local -a git_msgs + [[ -n "$vcs_info_msg_0_" ]] && git_msgs+=("%F{green}${vcs_info_msg_0_}%f") + [[ -n "$vcs_info_msg_1_" ]] && git_msgs+=("%F{yellow}${vcs_info_msg_1_}%f") + [[ -n "$vcs_info_msg_2_" ]] && git_msgs+=("%F{red}${vcs_info_msg_2_}%f") + git_msg="${(j: :)git_msgs}" + # }}} + # Perl version {{{ + local perl_version_source=$(llenv_version_origin plenv) + case "$perl_version_source" in + "local"|shell) + accessory_info="%F{blue}Perl-$(plenv version-name)%f ${accessory_info}" + ;; + *) + ;; + esac + # }}} + # Ruby version {{{ + local ruby_version_source=$(llenv_version_origin rbenv) + case "$ruby_version_source" in + "local"|shell) + accessory_info="%F{red}Ruby-$(rbenv version-name)%f ${accessory_info}" + ;; + *) + ;; + esac + # }}} + # }}} + + # join by newline + local -a left_prompt_lines + left_prompt_lines=( + ${accessory_info} + ${command_line} + ) + + # join by whitespace + local -a right_prompt_components + right_prompt_components=( + ${git_msg} + ) + + PROMPT="${(F)left_prompt_lines}" + RPROMPT="${(j: :)right_prompt_components}" +} # }}} + +prompt_lambda_setup "$@" + +# vim:set ft=zsh foldmethod=marker: diff --git a/.zsh.d/functions/prompt_yuno_setup b/.zsh.d/functions/prompt_yuno_setup new file mode 100644 index 0000000..8925c79 --- /dev/null +++ b/.zsh.d/functions/prompt_yuno_setup @@ -0,0 +1,81 @@ +function prompt_yuno_setup() { # {{{ + if ! (whence add-zsh-hook >/dev/null); then + autoload -Uz add-zsh-hooks + fi + add-zsh-hook precmd __prompt_yuno_update + + # zsh-git-prompt + export ZSH_GIT_PROMPT_ROOT="$ZSH_HOME/plugins/zsh-git-prompt" + if [[ -f "$ZSH_GIT_PROMPT_ROOT/zshrc.sh" ]]; then + export ZSH_THEME_GIT_PROMPT_CACHE=1 + source "$ZSH_GIT_PROMPT_ROOT/zshrc.sh" + fi + if [[ -f "$ZSH_GIT_PROMPT_ROOT/dist/build/gitstatus/gitstatus" ]]; then + export GIT_PROMPT_EXECUTABLE='haskell' + fi + + export ZSH_THEME_GIT_PROMPT_PREFIX="" + export ZSH_THEME_GIT_PROMPT_SUFFIX="" + export ZSH_THEME_GIT_PROMPT_SEPARATOR="|" + export ZSH_THEME_GIT_PROMPT_BRANCH="%{$fg_bold[magenta]%}" + export ZSH_THEME_GIT_PROMPT_STAGED="%{$fg[blue]%}%{.%G%}" + export ZSH_THEME_GIT_PROMPT_CONFLICTS="%{$fg[red]%}%{!%G%}" + export ZSH_THEME_GIT_PROMPT_CHANGED="%{$fg[yellow]%}%{!%G%}" + export ZSH_THEME_GIT_PROMPT_BEHIND="%{<%G%}" + export ZSH_THEME_GIT_PROMPT_AHEAD="%{$fg[green]%}%{>%G%}" + export ZSH_THEME_GIT_PROMPT_UNTRACKED="%{?%G%}" + export ZSH_THEME_GIT_PROMPT_CLEAN="%{$fg_bold[green]%}%{*%G%}" + + autoload -Uz llenv_version_origin +} # }}} + +function __prompt_yuno_update() { # {{{ + # components {{{ + local ok_yuno="%F{yellow}✘╹◡╹✘%f" + local bad_yuno="%F{red}✘>﹏<✘%f" + local command_line="%(?.${ok_yuno}.${bad_yuno}) < " + local working_directory="%F{cyan}%~%f" + local accessory_info="${working_directory}" + + # Perl version {{{ + local perl_version_source=$(llenv_version_origin plenv) + case "$perl_version_source" in + "local"|shell) + accessory_info="%F{blue}Perl-$(plenv version-name)%f ${accessory_info}" + ;; + *) + ;; + esac + # }}} + # Ruby version {{{ + local ruby_version_source=$(llenv_version_origin rbenv) + case "$ruby_version_source" in + "local"|shell) + accessory_info="%F{red}Ruby-$(rbenv version-name)%f ${accessory_info}" + ;; + *) + ;; + esac + # }}} + # }}} + + # join by newline + local -a left_prompt_lines + left_prompt_lines=( + ${accessory_info} + ${command_line} + ) + + # join by whitespace + local -a right_prompt_components + right_prompt_components=( + $(git_super_status) + ) + + PROMPT="${(F)left_prompt_lines}" + RPROMPT="${(j: :)right_prompt_components}" +} # }}} + +prompt_yuno_setup "$@" + +# vim:set ft=zsh foldmethod=marker: diff --git a/.zshenv b/.zshenv new file mode 100644 index 0000000..1550939 --- /dev/null +++ b/.zshenv @@ -0,0 +1,53 @@ +# environment +export HOMEBREW_PATH=/usr/local +export DEVEL_PATH=$HOME/devel +export GOPATH=$DEVEL_PATH +export EDITOR=vim + +path=( + $HOME/bin(N-/) + $DEVEL_PATH/bin(N-/) + $HOME/.mysqlenv/bin(N-/) + $HOME/.mysqlenv/shims(N-/) + $HOME/.pyenv/bin(N-/) + $HOME/.pyenv/shims(N-/) + $HOME/.rbenv/bin(N-/) + $HOME/.rbenv/shims(N-/) + $HOME/.plenv/bin(N-/) + $HOME/.plenv/shims(N-/) + $HOME/.ndenv/bin(N-/) + $HOME/.ndenv/shims(N-/) + $GOPATH/bin(N-/) + $HOMEBREW_PATH/opt/coreutils/libexec/gnubin(N-/) + $HOMEBREW_PATH/bin(N-/) + /usr/bin(N-/) + /usr/sbin(N-/) + /bin(N-/) + /sbin(N-/) +) + +typeset -U manpath +manpath=( + $HOMEBREW_PATH/share/man(N-/) + $HOMEBREW_PATH/opt/coreutils/libexec/gnuman(N-/) + /usr/share/man(N-/) +) + +export PAGER=less +export LESS='--LONG-PROMPT --RAW-CONTROL-CHARS' + +if whence nvim 2>&1 >/dev/null; then + EDITOR=nvim +fi + +MACVIM_APP= +local -a macvim_app_candidates=( + /opt/homebrew-cask/Caskroom/macvim-kaoriya/*/MacVim.app(N-/) + $HOMEBREW_PATH/opt/macvim/MacVim.app(N-/) + $HOME/Applications/MacVim.app(N-/) + /Applications/MacVim.app(N-/) +) +if (( $#macvim_app_candidates > 0 )); then + MACVIM_APP="$macvim_app_candidates[1]" +fi +export MACVIM_APP diff --git a/.zshrc b/.zshrc new file mode 100644 index 0000000..ade4208 --- /dev/null +++ b/.zshrc @@ -0,0 +1,360 @@ +bindkey -v + +# function load path {{{ +typeset -Ua fpath +fpath=( + $HOME/.zsh.d/functions(N-/) + $HOMEBREW_PATH/share/zsh-completions(N-/) + $HOMEBREW_PATH/share/zsh/site-functions(N-/) + $HOMEBREW_PATH/share/zsh/functions(N-/) + $HOMEBREW_PATH/opt/docker-completion/share/zsh/site-functions(N-/) + $HOMEBREW_PATH/opt/docker-compose-completion/share/zsh/site-functions(N-/) + $fpath +) +# }}} + +# fundamental options {{{ +export REPORTTIME=1 + +setopt extended_glob +# }}} + +# history {{{ +HISTFILE=$HOME/.zsh_history +HISTSIZE=10000000 +SAVEHIST=$HISTSIZE +set \ + extended_history \ + hist_ignore_dups \ + hist_ignore_space \ + inc_append_history \ + share_history \ + no_flow_control \ + hist_save_no_dups \ + hist_ignore_all_dups +autoload history-search-end +zle -N history-beginning-search-backward-end history-search-end +zle -N history-beginning-search-forward-end history-search-end +bindkey -v "^N" history-beginning-search-forward-end +bindkey -v "^P" history-beginning-search-backward-end +bindkey -v "^R" history-incremental-pattern-search-backward +bindkey -v "^S" history-incremental-pattern-search-forward +# }}} + +# color {{{ +autoload -Uz colors; colors +[[ -f "$HOME/.dircolors" ]] && source "$HOME/.dircolors" +# }}} + +# completion {{{ +zmodload -i zsh/complist +autoload -U compinit && compinit -C +setopt \ + complete_in_word \ + glob_complete \ + hist_expand \ + no_beep \ + numeric_glob_sort + +# Format {{{ +zstyle ':completion:*' format '%F{magenta}-- %d --%f' +zstyle ':completion:*' group-name '' +zstyle ':completion:*:options' description yes +zstyle ':completion:*:options' auto-description '%d' +zstyle ':completion:*:corrections' format ' %F{yellow}-- %d (errors: %e) --%f' +zstyle ':completion:*:descriptions' format ' %F{magenta}-- %d --%f' +zstyle ':completion:*:messages' format ' %F{blue}-- %d --%f' +zstyle ':completion:*:warnings' format ' %F{red}-- no matches found --%f' +zstyle ':completion:*:default' list-prompt '%S%M matches%s' + +# Show selected candidate +zstyle ':completion:*:default' menu select=2 + +zstyle ':completion:*:default' list-colors "${(s.:.)LS_COLORS}" + +# Fuzzy match +zstyle ':completion:*' matcher-list 'm:{a-z}={A-Z} r:|[._-]=*' +zstyle ':completion:*' completer _oldlist _complete _match _ignored _approximate _prefix + +# sudo +zstyle ':completion:sudo:*' environ PATH="$SUDO_PATH:$PATH" + +# Directory candidates order +zstyle ':completion:*:cd:*' tag-order local-directories path-directories + +# Ignore current directory from directory candidates +zstyle ':completion:*' ignore-parents parent pwd + +# Process candidates +zstyle ':completion:*:*:*:*:processes' command 'ps -u $USER -o pid,user,comm -w' +zstyle ':completion:*:*:kill:*:processes' list-colors '=(#b) #([0-9]#) ([0-9a-z-]#)*=01;36=0=01' +zstyle ':completion:*:*:kill:*' menu yes select +zstyle ':completion:*:*:kill:*' force-list always +zstyle ':completion:*:*:kill:*' insert-ids single + +# Show man candidates with section +zstyle ':completion:*:manuals' separate-sections true +# }}} + +# key mapping {{{ +bindkey -M menuselect 'h' vi-backward-char +bindkey -M menuselect 'l' vi-forward-char +bindkey -M menuselect 'j' vi-down-line-or-history +bindkey -M menuselect 'k' vi-up-line-or-history +# }}} + +# }}} + +# url-quote-magic {{{ +autoload -Uz url-quote-magic +zle -N self-insert url-quote-magic +# }}} + +# expand backslash to tilde {{{ +# Originally from: https://github.com/cho45/dotfiles/blob/64ea90d17aaf6c46a2cb090f2e12a6e3d7df6034/.zshrc#L245 +expand-to-home-or-complete() { # {{{ + if [ "$LBUFFER" = "" -o "$LBUFFER[-1]" = " " ]; then + LBUFFER+="~/" + else + zle self-insert + fi +} # }}} + +zle -N expand-to-home-or-complete +bindkey -v "\\" expand-to-home-or-complete +# }}} + +# ghq {{{ +__widget_cd_repo() { + local selected_repo=$( ghq list | peco ) + if [[ -n "$selected_repo" ]]; then + BUFFER="ghq look ${selected_repo}" + zle accept-line + fi + zle -R -c +} +zle -N __widget_cd_repo +bindkey -v "^]^G" __widget_cd_repo +# }}} + +# git {{{ +__widget_git_recent_branches() { + local selected_branch=$( \ + git for-each-ref --sort=-committerdate --format="%(refname) %(committerdate:relative)" -- refs/heads \ + | sed -E 's/refs\/heads\///' \ + | peco --query "$LBUFFER" \ + | cut -f1 \ + ) + if [[ -n "$selected_branch" ]]; then + BUFFER="git checkout ${selected_branch}" + zle accept-line + fi + zle -R -c +} +zle -N __widget_git_recent_branches +bindkey -v "^]gr" __widget_git_recent_branches +# }}} + +# tmux: split window with vim-like key mappings {{{ +# vertical split {{{ +tmux_vsplit() { + BUFFER="tmux split-window -d -p 50 -h '$BUFFER'" # TODO: escape + zle accept-line +} +zle -N tmux_vsplit +bindkey -v "^Wv" tmux_vsplit +# }}} + +# horizontal split {{{ +tmux_split() { + BUFFER="tmux split-window -d -p 50 -v '$BUFFER'" # TODO: escape + zle accept-line +} +zle -N tmux_split +bindkey -v "^Ws" tmux_split +# }}} +# }}} + +# alias {{{ +alias :q=exit +if whence exa >/dev/null 2>&1; then + alias l='exa -aF' + alias ls='exa -aF' + alias ll='exa -alF' +else + if whence gls >/dev/null; then + alias l='gls --color=auto -AF' + alias ls='gls --color=auto -AF' + alias ll='gls --color=auto -AFl' + else + alias l='ls -GAF' + alias ls='ls -GAF' + alias ll='ls -GAFl' + fi +fi +whence hub >/dev/null 2>&1 && alias git=hub +# }}} + +# abbrev {{{ +setopt extended_glob +typeset -A abbreviations +abbreviations=( + 'Ig' '| rg' + 'It' '| tail' + 'Ij' '| jq' + 'DC' 'docker-compose' +) + +magic-abbrev-expand() { + local MATCH + LBUFFER=${LBUFFER%%(#m)[-_a-zA-Z0-9]#} + LBUFFER+=${abbreviations[$MATCH]:-$MATCH} + zle self-insert +} + +no-magic-abbrev-expand() { + LBUFFER+=' ' +} + +zle -N magic-abbrev-expand +zle -N no-magic-abbrev-expand +bindkey -v " " magic-abbrev-expand +bindkey -v "^x " no-magic-abbrev-expand +# }}} + +# prompt {{{ +setopt \ + prompt_subst \ + prompt_percent \ + transient_rprompt +autoload -U promptinit && promptinit + +autoload -Uz vcs_info +zstyle ':vcs_info:*' max-exports 4 +zstyle ':vcs_info:(git|svn):*' formats '%R' '%S' '%b' '%s' +zstyle ':vcs_info:(git|svn):*' actionformats '%R' '%S' '%b|%a' '%s' +zstyle ':vcs_info:*' formats '%R' '%S' '%s:%b' '%s' +zstyle ':vcs_info:*' actionformats '%R' '%S' '%s:%b|%a' '%s' + +__configure_prompt() { + local ok_yuno="%F{yellow}✘╹◡╹✘%f" + local bad_yuno="%F{red}✘>﹏<✘%f" + local command_line="%(?.${ok_yuno}.${bad_yuno}) < " + + psvar=() + STY= LANG=en_US.UTF-8 vcs_info + repos=`print -nD "$vcs_info_msg_0_"` + if [[ -n "$vcs_info_msg_1_" ]]; then + vcs="$vcs_info_msg_3_" + else + vcs='' + fi + [[ -n "$repos" ]] && psvar[2]="$repos" + [[ -n "$vcs_info_msg_1_" ]] && psvar[3]="$vcs_info_msg_1_" + [[ -n "$vcs_info_msg_2_" ]] && psvar[1]="$vcs_info_msg_2_" + + local psdirs='[%F{yellow}%3(v|%32<..<%3v%<<|%60<..<%~%<<)%f]' + local psvcs='%3(v|[%25<\<<%F{yellow}%2v%f@%F{blue}%1v%f%<<]|)' + + local git_is_dirty git_local_changes git_upstream_changes + if git rev-parse --is-inside-work-tree &>/dev/null; then + command git diff --no-ext-diff --quiet --exit-code || git_is_dirty='%F{yellow}*%f' + local git_upstream_status=$(command git rev-list --left-right --count ...@{u} 2>/dev/null) + git_upstream_status=(${(ps:\t:)git_upstream_status}) + local left=${git_upstream_status[1]} right=${git_upstream_status[2]} + (( ${left:-0} > 0 )) && git_local_changes='%F{green}⇡%f' + (( ${right:-0} > 0 )) && git_upstream_changes='%F{red}⇣%f' + fi + + export PROMPT="${command_line}" + + export RPROMPT="${psdirs}${git_is_dirty}${git_local_changes}${git_upstream_changes}${psvcs}" +} +autoload -Uz add-zsh-hooks +add-zsh-hook precmd __configure_prompt +# }}} + +# Show anyenv version {{{ +notify_llenv_version() { + for llenv in rbenv plenv ndenv pyenv; do + llenv_root="${HOME}/.${llenv}" # XXX + if whence $llenv >/dev/null && [[ "$(${llenv} version-origin)" != "$llenv_root/version" ]]; then + echo "$fg[yellow]${llenv} changed version: $(${llenv} version-name)$reset_color" + fi + done +} +add-zsh-hook chpwd notify_llenv_version +# }}} + +# Update current window name {{{ +update_window_title() { # {{{ + emulate -L zsh + local -a cmd + cmd=(${(z)2}) + + case $cmd[1] in + *=*) # PLENV_VERSION=5.14.2 plenv exec perl -v => plenv + echo -n "k$cmd[2]:t\\" + return + ;; + ls|gls|clear|pwd) + echo -n "k$ZSH_NAME\\" + return + ;; + sudo|cd) + echo -n "k$cmd[1] $cmd[2]:t\\" + return + ;; + *) + echo -n "k$cmd[1]:t\\" + return + ;; + esac + + local -A jt + jt=(${(kv)jobtexts}) + $cmd >>(read num rest cmd=(${(z)${(e):-\$jt$num}}) echo -n "k$cmd[1]:t\\") 2>/dev/null +} # }}} + +if [ "$TMUX" ]; then + add-zsh-hook preexec update_window_title +fi +# }}} + +# direnv {{{ +if whence direnv >/dev/null; then + eval "$(direnv hook zsh)" +fi +# }}} + +# syntax highlight {{{ +if [[ -f "$HOMEBREW_PATH/share/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh" ]]; then + source $HOMEBREW_PATH/share/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh +fi +# }}} + +# substring-search {{{ +if [[ -f "$HOMEBREW_PATH/opt/zsh-history-substring-search/zsh-history-substring-search.zsh" ]]; then + source $HOMEBREW_PATH/opt/zsh-history-substring-search/zsh-history-substring-search.zsh + + bindkey -M vicmd "k" history-substring-search-up + bindkey -M vicmd "j" history-substring-search-down +fi +# }}} + +if ! ssh-add -l 2>/dev/null; then + echo '---> Add SSH private key' + ssh-add +fi + +# tmux {{{ +if whence tmux >/dev/null && [ -z "$TMUX" ]; then + if $(tmux has-session 2>/dev/null); then + tmux attach-session -t "${HOST%%.*}" + else + tmux new-session -s "${HOST%%.*}" + fi +fi +# }}} + +# vim:set foldmethod=marker: diff --git a/README.md b/README.md new file mode 100644 index 0000000..00a6937 --- /dev/null +++ b/README.md @@ -0,0 +1,48 @@ +# dotfiles + +![Build Status](https://travis-ci.org/aereal/dotfiles.png?branch=master) + +This repository includes a lot of configuration file is used and optimized for me. + +You can clone or fork them freely, but I don't guarantee that they fit you. + +## Tools configured + + * Git + * Vim + * tmux + * Zsh + * OS X (Preferences) + * Ruby tools + * Capistrano + * Pow + * Pry + * Preferred gems + +## Tools included + +These tools are included as submodule. + + * [cdd](https://github.com/m4i/cdd) - The utility to change working directory over the terminal multiplexor's window + +## Policies + + * Automatation + * Vim is the editor + * Maximize the performance in loved environment + +### Automation + +The setup process should be automated to keep syncing environment easy. + +### Vim is the editor + +Using the tools as over the their domain is painful. + +### Maximize the performance in loved environment + +It is stupid to spoil the performance to keep portability. + +## Installation + +to be documented ... diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..4ec6968 --- /dev/null +++ b/Rakefile @@ -0,0 +1,67 @@ +require 'pathname' + +# methods +def env_or_default(env: nil, default: nil) + ENV.fetch(env, default) +end + +def ensure_pathname(maybe_pathname) + maybe_pathname === Pathname ? maybe_pathname : Pathname.new(maybe_pathname) +end + +class Recipe + include FileUtils::Verbose + + attr_reader :name, :source, :destination + + def initialize(name: nil, source: nil, destination: nil) + @name = name + @source = ensure_pathname(source) + @destination = ensure_pathname(destination) + end + + def install + if self.destination.exist? + puts "Skip #{self.name}" + return + end + ln_s self.source.to_s, self.destination.to_s + end + + def clean + unless self.destination.exist? && self.destination.symlink? + puts "Skip #{self.destination}; the destination seems not to be installed with the Rake task" + return + end + rm self.destination.to_s + end +end + +# constants +INSTALL_DIRECTORY = ensure_pathname(env_or_default(env: 'INSTALL_DIRECTORY', default: '~')).expand_path +SOURCE_DIRECTORY = ensure_pathname(env_or_default(env: 'SOURCE_DIRECTORY', default: Dir.pwd)).expand_path +DOTFILES_IGNORE_FILE = ensure_pathname(env_or_default(env: 'DOTFILES_IGNORE_FILE', default: SOURCE_DIRECTORY + '.dotfiles.ignore')).expand_path + +IGNORED_DOTFILES = DOTFILES_IGNORE_FILE.each_line.map {|f| SOURCE_DIRECTORY.join(f.strip) } +DOTFILES = SOURCE_DIRECTORY.each_child.select {|e| e.basename.to_s.start_with?(?.) } +INSTALLABLE_DOTFILES = DOTFILES - IGNORED_DOTFILES +INSTALL_NAMES = INSTALLABLE_DOTFILES.map {|f| f.relative_path_from(SOURCE_DIRECTORY) } +INSTALL_RECIPES = INSTALL_NAMES.map {|name| + Recipe.new(name: name, source: SOURCE_DIRECTORY.join(name), destination: INSTALL_DIRECTORY.join(name)) +} + +task :default => :install + +desc "Install dotfiles into #{INSTALL_DIRECTORY}" +task :install do + INSTALL_RECIPES.each do |recipe| + recipe.install + end +end + +desc "Cleanup dotfiles that installed into #{INSTALL_DIRECTORY}" +task :clean do + INSTALL_RECIPES.each do |recipe| + recipe.clean + end +end diff --git a/bin/abbrev-cwd.go b/bin/abbrev-cwd.go new file mode 100644 index 0000000..a79b32e --- /dev/null +++ b/bin/abbrev-cwd.go @@ -0,0 +1,35 @@ +package main + +import ( + "os" + "os/user" + "path/filepath" + "strings" +) + +func main() { + var err error + cwd, err := os.Getwd() + if err != nil { + panic(err) + } + currentUser, err := user.Current() + if err != nil { + panic(err) + } + homeDir := currentUser.HomeDir + cwdWithTilde := strings.Replace(cwd, homeDir, "~/", 1) + hiers := strings.Split(cwdWithTilde, "/") + hiersLen := len(hiers) + var abbreved []string + for idx, h := range hiers { + var formatted string + if (idx == hiersLen-1) || h == "" { + formatted = h + } else { + formatted = string(h[0]) + } + abbreved = append(abbreved, formatted) + } + println(filepath.Join(abbreved...)) +} diff --git a/bin/diff-highlight-wrapper b/bin/diff-highlight-wrapper new file mode 100755 index 0000000..da1765a --- /dev/null +++ b/bin/diff-highlight-wrapper @@ -0,0 +1,14 @@ +#!/bin/sh + +if test -x brew; then + git_prefix=`brew --prefix git` +else + git_prefix='/usr/local' +fi +diff_highlight_command=$git_prefix/share/git-core/contrib/diff-highlight/diff-highlight + +if test -x $diff_highlight_command; then + $diff_highlight_command | less +else + less +fi diff --git a/bin/generate-typable-words b/bin/generate-typable-words new file mode 100755 index 0000000..b44207d --- /dev/null +++ b/bin/generate-typable-words @@ -0,0 +1,28 @@ +#!/usr/bin/env ruby + +LEFT_CHARS = %w( a s d f g w e r v 3 4 5 ) +LEFT_CANDIDATES = LEFT_CHARS.flat_map {|c| [c, c.upcase] } +RIGHT_CHARS = %w( h j k l i o p n 8 9 0 ) +RIGHT_CANDIDATES = RIGHT_CHARS.flat_map {|c| [c, c.upcase] } +CANDIDATES = LEFT_CANDIDATES.shuffle.zip(RIGHT_CANDIDATES.shuffle).flatten +MAX_RETRY_COUNT = 3 + +def generate_typable_words(candidates, length) + candidates.take(length) +end + +def generate_strong_typable_words(candidates, length, retry_count = 0) + chars = generate_typable_words(candidates, length) + if (retry_count <= MAX_RETRY_COUNT) && !(chars.grep(/[0-9]/).any? && chars.grep(/[a-z]/).any? && chars.grep(/[A-Z]/).any?) + generate_strong_typable_words(candidates, length, retry_count + 1) + else + chars + end +end + +length = ARGV.grep(/[0-9]+/).first || 8 +should_strong = ARGV.include?('--strong') +strategy = should_strong ? :generate_strong_typable_words : :generate_typable_words +word = self.__send__(strategy, CANDIDATES, length.to_i) + +print word.join('') diff --git a/bin/git-authors.go b/bin/git-authors.go new file mode 100644 index 0000000..8768fb3 --- /dev/null +++ b/bin/git-authors.go @@ -0,0 +1,111 @@ +package main + +// original: https://github.com/dann/dotfiles/blob/master/devbin/git-authors + +import ( + "fmt" + "log" + "os/exec" + "regexp" + "sort" + "strconv" + "strings" +) + +type Commit struct { + Author string + Commits int + Insertions int + Deletions int +} +func (c Commit) Ratio(total int) float64 { + return float64(c.Commits) / float64(total) * 100.0 +} + +type CommitsSummary []*Commit + +func (cs CommitsSummary) Len() int { + return len(cs) +} + +func (cs CommitsSummary) Swap(i, j int) { + cs[i], cs[j] = cs[j], cs[i] +} + +type ByCommitsCount struct { + CommitsSummary +} + +func (bcc ByCommitsCount) Less(i, j int) bool { + return bcc.CommitsSummary[i].Commits < bcc.CommitsSummary[j].Commits +} + +func String2Int(s string) int { + var ( + i int64 + e error + ) + if i, e = strconv.ParseInt(s, 0, 0); e != nil { + log.Fatal(e) + return -1 + } + return int(i) +} + +func CreateCommit(author string, commits int, ins int, del int) *Commit { + c := new(Commit) + c.Author = author + c.Commits = commits + c.Insertions = ins + c.Deletions = del + return c +} + +func main() { + out, err := exec.Command("git", "--no-pager", "log", "--format=%H %aN <%aE>", "--no-merges", "--shortstat").Output() + if err != nil { + log.Fatal(err) + } + + commitPattern := regexp.MustCompile(`^([0-9a-f]{40}) (.*)$`) + statsPattern := regexp.MustCompile(`(\d+) insert.* (\d+) delet*`) + + var currentAuthor string + commitCounts := map[string]int{} + inserts := map[string]int{} + deletes := map[string]int{} + totalCommits := 0 + for _, l := range(strings.Split(string(out), "\n")) { + if commitPattern.MatchString(l) { + totalCommits += 1 + m := commitPattern.FindStringSubmatch(l) + if len(m) == 0 { continue } + currentAuthor = m[2] + } else if statsPattern.MatchString(l) { + m := statsPattern.FindStringSubmatch(l) + if len(m) == 0 { continue } + ins := String2Int(m[1]) + del := String2Int(m[2]) + commitCounts[currentAuthor] += 1 + inserts[currentAuthor] += ins + deletes[currentAuthor] += del + } + } + + var commits CommitsSummary + for author, commitCount := range(commitCounts) { + c := CreateCommit(author, commitCount, inserts[author], deletes[author]) + commits = append(commits, c) + } + sort.Sort(sort.Reverse(ByCommitsCount{commits})) + + fmt.Printf("%10s %10s %10s %10s\n", "%", "commits", "+++", "---") + for _, c := range(commits) { + fmt.Printf("%9.2f%% %10d %10d %10d %s\n", + c.Ratio(totalCommits), + c.Commits, + c.Insertions, + c.Deletions, + c.Author) + } +} diff --git a/bin/git-catchup b/bin/git-catchup new file mode 100755 index 0000000..cd636f8 --- /dev/null +++ b/bin/git-catchup @@ -0,0 +1,16 @@ +#!/bin/bash + +# Catching up with upstream + +set -e + +command git fetch -q + +develop_branch='staging/master' +upstream_ref=$develop_branch\@\{u\} + +if git rev-parse @{u} 2>/dev/null; then + command git merge --no-ff $upstream_ref +else + git rebase $upstream_ref +fi diff --git a/bin/git-git b/bin/git-git new file mode 100755 index 0000000..5425b12 --- /dev/null +++ b/bin/git-git @@ -0,0 +1,3 @@ +#!/bin/sh + +exec git $@ diff --git a/bin/git-issue-checkout b/bin/git-issue-checkout new file mode 100755 index 0000000..12f5b69 --- /dev/null +++ b/bin/git-issue-checkout @@ -0,0 +1,16 @@ +#!/usr/bin/env zsh + +local matched=$( + git for-each-ref \ + --sort=committerdate \ + --format='%(refname)' \ + refs/heads | \ + grep "$1" +) + +if [[ -z $matched ]]; then + echo "Issue tracking branch is not found" > /dev/stderr + exit 1 +fi + +git checkout ${matched#refs/heads/} diff --git a/bin/git-normalize-url b/bin/git-normalize-url new file mode 100755 index 0000000..241b363 --- /dev/null +++ b/bin/git-normalize-url @@ -0,0 +1,18 @@ +#!/usr/bin/env ruby + +ORIGIN = 'origin' + +def run(argv) + remote, * = ARGV + remote ||= ORIGIN + prev_remote_url = `git remote get-url #{remote}`.strip + if prev_remote_url.start_with?('ssh://') + require 'uri' + prev_remote_url = URI.parse(prev_remote_url) + new_remote_url = '%s@%s:%s' % [prev_remote_url.user, prev_remote_url.host, prev_remote_url.path[1..-1]] + system 'git', 'remote', 'set-url', remote, new_remote_url + puts "#{prev_remote_url} => #{new_remote_url}" + end +end + +run(ARGV) diff --git a/bin/git-recent-branches b/bin/git-recent-branches new file mode 100755 index 0000000..da822c9 --- /dev/null +++ b/bin/git-recent-branches @@ -0,0 +1,13 @@ +#!/usr/bin/env zsh + +function __git-recent-branches() { + local count=${1:-10} + git for-each-ref \ + --sort=-committerdate \ + --format="%(objectname:short) %(committerdate:relative) %(refname)" \ + refs/heads \ + | head -n $count \ + | sed -e 's/refs\/heads\///' +} + +__git-recent-branches $@ diff --git a/bin/git-refresh-branch b/bin/git-refresh-branch new file mode 100755 index 0000000..b0ecb80 --- /dev/null +++ b/bin/git-refresh-branch @@ -0,0 +1,43 @@ +#!/usr/bin/env perl + +use Carp (); +use List::Util qw(reduce); + +sub main { + my ($rollback_ref) = @_; + + Carp::croak 'rollback_ref must be given' unless $rollback_ref; + + my $current_branch = do { + my $out = `git symbolic-ref --short HEAD`; + chomp $out; + $out; + }; + my $old_branch_name = old_branch_name($current_branch); + seq_run( + ['git', 'branch', '-m', $current_branch, $old_branch_name], + ['git', 'checkout', '-b', $current_branch, $rollback_ref], + ); +} + +sub old_branch_name { + my ($name) = @_; + my $time = time(); + return "prev-$time-$name"; +} + +sub seq_run { + return List::Util::reduce { + my ($last_result, $cmd) = ($a, $b); + $last_result == 0 ? run($cmd) : $last_result; + } 0, @_; +} + +sub run { + my ($cmd) = @_; + my $line = join ' ', @$cmd; + Carp::carp $line; + return system @$cmd; +} + +main(@ARGV); diff --git a/bin/git-topic-rebase b/bin/git-topic-rebase new file mode 100755 index 0000000..b3efeba --- /dev/null +++ b/bin/git-topic-rebase @@ -0,0 +1,7 @@ +#!/usr/bin/env zsh + +# $1: merge base + +set -e + +git rebase --interactive $(git merge-base ${1:-master} HEAD) diff --git a/bin/git-up b/bin/git-up new file mode 100755 index 0000000..249f257 --- /dev/null +++ b/bin/git-up @@ -0,0 +1,8 @@ +#!/usr/bin/env zsh + +# $1: remote name (default: origin) +# $2: branch name (default: HEAD) + +set -e + +git push --set-upstream "${1:-origin}" $(git symbolic-ref --short ${2:-HEAD}) diff --git a/bin/macvim b/bin/macvim new file mode 100755 index 0000000..bc6de5c --- /dev/null +++ b/bin/macvim @@ -0,0 +1,13 @@ +#!/bin/bash + +set -ue + +macvim_wrapper_cmd='reattach-to-user-namespace -l' +macvim_app="${MACVIM_APP-/Applications/MacVim.app}" + +if [[ ! -e $macvim_app ]]; then + echo "! MACVIM_APP (${MACVIM_APP} not found)" >/dev/stderr + exit 1 +fi + +reattach-to-user-namespace -l "$macvim_app/Contents/MacOS/Vim" "$@" diff --git a/bin/man b/bin/man new file mode 100755 index 0000000..6830382 --- /dev/null +++ b/bin/man @@ -0,0 +1,11 @@ +#!/bin/sh + +env \ + LESS_TERMCAP_mb=$'\E[01;31m' \ + LESS_TERMCAP_md=$'\E[01;38;5;74m' \ + LESS_TERMCAP_me=$'\E[0m' \ + LESS_TERMCAP_se=$'\E[0m' \ + LESS_TERMCAP_so=$'\E[38;5;246m' \ + LESS_TERMCAP_ue=$'\E[0m' \ + LESS_TERMCAP_us=$'\E[04;38;5;146m' \ + /usr/bin/man "$@" diff --git a/bin/metacpan b/bin/metacpan new file mode 100755 index 0000000..7c2ff38 --- /dev/null +++ b/bin/metacpan @@ -0,0 +1,16 @@ +#!/usr/bin/env zsh + +open_command='' +open_args='' + +if /usr/bin/which -s open; then + open_command='open' + open_args='' +fi + +if [[ ! -x =$open_command ]]; then + echo "open-able command is not found." > /dev/stderr + exit 1 +fi + +$open_command $open_args "http://metacpan.org/module/$1" diff --git a/bin/mkproj b/bin/mkproj new file mode 100755 index 0000000..6780458 --- /dev/null +++ b/bin/mkproj @@ -0,0 +1,87 @@ +#!/usr/bin/env zsh + +set -ue + +_script_name=$(basename $0) +usage() { + cat <<DOC + ${_script_name} [--help] [--host REPO_HOST] [--owner OWNER_NAME] [--design] [--no-peek] +DOC +} + +die() { + echo "! $@" >/dev/stderr + exit 1 +} + +info() { + echo "---> $@" >/dev/stderr +} + +repos_root="$(ghq root)" +repo_host="github.com" +owner="$USER" +name='' +create=1 +peek=1 + +while [[ $# > 0 ]]; do + case "$1" in + --help,-h) + usage + exit 0 + ;; + --host) + shift + repo_host="$1" + ;; + --owner) + shift + owner="$1" + ;; + --design) + create=0 + ;; + --no-peek) + peek=0 + ;; + -*) + echo "Unknown args: $1" + exit 1 + ;; + *) + name="$1" + ;; + esac + shift +done + +owner_path="${repos_root}/${repo_host}/${owner}" +repo_path="${owner_path}/${name}" + +if [[ -z "$name" ]]; then + die 'Repository name cannot be empty' +fi + + +if [[ $create -eq 1 ]]; then + if [[ -e $repo_path ]]; then + die "Already exists: $repo_path" + fi + + info "Create $repo_path" + mkdir -p $repo_path +fi + +cd $repo_path + +if [[ ! -d "${repo_path}/.git" ]]; then + info 'Try to git init ...' + git init + git commit --allow-empty --message ':sunrise:' +fi + +if [[ $peek -eq 1 ]]; then + info "cd $repo_path ..." + exec $SHELL +fi diff --git a/bin/os-version b/bin/os-version new file mode 100755 index 0000000..7ff993e --- /dev/null +++ b/bin/os-version @@ -0,0 +1,18 @@ +#!/bin/bash + +case "$(uname)" in + Darwin*) + sw_vers -productVersion + ;; + Linux*) + if which lsb_release >/dev/null 2>&1; then + lsb_release --release | cut -f2 + fi + if [[ -f /etc/redhat-release ]]; then + cat /etc/redhat-release | cut -d' ' -f3 + fi + ;; + *) + echo "Unknown OS" >/dev/stderr + exit 1 +esac diff --git a/bin/paginate b/bin/paginate new file mode 100755 index 0000000..b3e1563 --- /dev/null +++ b/bin/paginate @@ -0,0 +1,3 @@ +#!/bin/bash + +${PAGER-less} diff --git a/bin/pm-version b/bin/pm-version new file mode 100755 index 0000000..08a875a --- /dev/null +++ b/bin/pm-version @@ -0,0 +1,3 @@ +#!/bin/sh + +perl -M"$1" -e "print qq|\$$1::VERSION\n|" diff --git a/bin/screenshot2slack b/bin/screenshot2slack new file mode 100755 index 0000000..e3291c0 --- /dev/null +++ b/bin/screenshot2slack @@ -0,0 +1,9 @@ +#!/bin/bash + +set -e + +tmp_dir='/tmp' +format='png' +file_name="${tmp_dir}/$(date +%s).${format}" +screencapture -i "${file_name}" +slackcat $@ "${file_name}" diff --git a/bin/ts-project b/bin/ts-project new file mode 100755 index 0000000..0324aa2 --- /dev/null +++ b/bin/ts-project @@ -0,0 +1,120 @@ +#!/bin/bash + +set -e + +usage() { + _script_name=$(basename $0) + cat <<DOC + ${_script_name} [--help|--with-mocha|--with-espower-babel] +DOC +} + +root_dir=. +npm_test_command='' +with_mocha=0 +with_espower_babel=0 +while [[ $# > 0 ]]; do + case "$1" in + --help) + usage + exit 0 + ;; + --with-mocha) + with_mocha=1 + ;; + --with-espower-babel) + with_espower_babel=1 + ;; + esac + shift +done + +json_satisfy() { + jq --exit-status "$2" < $1 >/dev/null +} + +pkg_satisfy() { + json_satisfy ${root_dir}/package.json "$1" +} + +update_json() { + cat "$1" | jq --unbuffered "$2" | tee "$1" +} + +if [[ ! -d "${root_dir}/.git" ]]; then + echo '---> Not Git repository' + echo '---> Try to git init ...' + git init + git commit --allow-empty --message ':sunrise:' +fi + +if [[ ! -f "${root_dir}/package.json" ]]; then + echo '---> npm init ...' + npm init --yes +fi + +if ! git check-ignore --quiet 'node_modules'; then + echo '---> Ignore node_modules ...' + echo 'node_modules' >> .gitignore +fi + +if ! pkg_satisfy '.devDependencies | has("typescript")'; then + echo '---> Install TypeScript ...' + npm install --save-dev typescript +fi + +if [[ $with_mocha -eq 1 ]]; then + if ! pkg_satisfy '.devDependencies | has("mocha")'; then + echo '---> Install mocha ...' + npm install --save-dev mocha + fi + npm_test_command='mocha' + + if [[ $with_espower_babel -eq 1 ]]; then + if ! pkg_satisfy '.devDependencies | has("espower-babel")'; then + echo '---> Install espower-babel ...' + npm install --save-dev espower-babel + fi + npm_test_command='mocha --compilers js:espower-babel/guess' + fi + + if ! pkg_satisfy ".scripts.test == \"${npm_test_command}\""; then + echo '---> configure `npm test` ...' + update_json "${root_dir}/package.json" "map_values(if type == \"object\" and has(\"test\") then .test = \"${npm_test_command}\" else . end)" + fi +fi + +if [[ ! -f "${root_dir}/tsconfig.json" ]]; then + echo '---> Create tsconfig.json ...' + $(npm bin)/tsc --init +fi + +if ! json_satisfy ${root_dir}/tsconfig.json '.compilerOptions.target == "es5"'; then + echo '---> Set target version to ES5 ...' + update_json "${root_dir}/tsconfig.json" 'map_values(if type == "object" and has("target") then .target = "es5" else . end)' +fi + +if ! json_satisfy ${root_dir}/tsconfig.json '.compilerOptions.noImplicitAny == true'; then + echo '---> Refuse implicit any ...' + update_json "${root_dir}/tsconfig.json" 'map_values(if type == "object" and has("noImplicitAny") then .noImplicitAny = true else . end)' +fi + +if ! pkg_satisfy '.scripts.build == "tsc"'; then + echo '---> Configure npm run build' + update_json "${root_dir}/package.json" 'map_values(if type == "object" and has("test") then .build = "tsc" else . end)' +fi + +if ! pkg_satisfy '.devDependencies | has("dtsm")'; then + echo '---> Install dtsm ...' + npm install --save-dev dtsm +fi + +if [[ ! -f "${root_dir}/dtsm.json" ]]; then + echo '---> Generate dtsm.json' + $(npm bin)/dtsm --insight false init +fi + +if ! git check-ignore --quiet 'typings'; then + echo '---> Ignore typings ...' + echo 'typings' >> .gitignore +fi diff --git a/bin/vim b/bin/vim new file mode 120000 index 0000000..30797f6 --- /dev/null +++ b/bin/vim @@ -0,0 +1 @@ +/Users/aereal/repos/github.com/aereal/dotfiles/bin/macvim \ No newline at end of file diff --git a/brew.bash b/brew.bash new file mode 100644 index 0000000..77f6eca --- /dev/null +++ b/brew.bash @@ -0,0 +1,58 @@ +#!/bin/bash + +set -e + +brew update + +# essentials +brew install awscli +brew install colordiff +brew install coreutils +brew install curl +brew install direnv +brew install docker-completion +brew install docker-compose-completion +brew install envchain +brew install exa +brew install --HEAD motemen/furoshiki2/furoshiki2 +brew install git --with-curl +brew install tar +brew install go +brew install hub +brew install jq +brew install mackerelio/mackerel-agent/mackerel-agent +brew install mackerelio/mackerel-agent/mkr +brew install neovim +brew install peco +brew install proctools +brew install pstree +brew install reattach-to-user-namespace +brew install ripgrep +brew install slackcat +brew install sshutltle +brew install telnet +brew install tig +brew install tmux +brew install tree +brew install zsh --without-etcdir +brew install zsh-completions +brew install zsh-history-substring-search +brew install zsh-syntax-highlighting + +# extra +brew install graphviz +brew install mysql-client +brew install openssl +brew install itchyny/rexdep/rexdep +brew install sbt + +# casks +brew cask install alfred +brew cask install docker +brew cask install dropbox +brew cask install google-chrome-dev +brew cask install gyazo +brew cask install iterm2 +brew cask install karabiner-elements +brew cask install slack +brew cask install visual-studio-code diff --git a/colors/Japanesque/Japanesque.itermcolors b/colors/Japanesque/Japanesque.itermcolors new file mode 100644 index 0000000..0f93979 --- /dev/null +++ b/colors/Japanesque/Japanesque.itermcolors @@ -0,0 +1,213 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> +<plist version="1.0"> +<dict> + <key>Ansi 0 Color</key> + <dict> + <key>Blue Component</key> + <real>0.20856963098049164</real> + <key>Green Component</key> + <real>0.22283002734184265</real> + <key>Red Component</key> + <real>0.20568123459815979</real> + </dict> + <key>Ansi 1 Color</key> + <dict> + <key>Blue Component</key> + <real>0.38021323084831238</real> + <key>Green Component</key> + <real>0.24660280346870422</real> + <key>Red Component</key> + <real>0.81089001893997192</real> + </dict> + <key>Ansi 10 Color</key> + <dict> + <key>Blue Component</key> + <real>0.17100538313388824</real> + <key>Green Component</key> + <real>0.49610027670860291</real> + <key>Red Component</key> + <real>0.46425256133079529</real> + </dict> + <key>Ansi 11 Color</key> + <dict> + <key>Blue Component</key> + <real>0.1833186000585556</real> + <key>Green Component</key> + <real>0.35025951266288757</real> + <key>Red Component</key> + <real>0.46875584125518799</real> + </dict> + <key>Ansi 12 Color</key> + <dict> + <key>Blue Component</key> + <real>0.47479093074798584</real> + <key>Green Component</key> + <real>0.34725069999694824</real> + <key>Red Component</key> + <real>0.074933364987373352</real> + </dict> + <key>Ansi 13 Color</key> + <dict> + <key>Blue Component</key> + <real>0.56739711761474609</real> + <key>Green Component</key> + <real>0.25756442546844482</real> + <key>Red Component</key> + <real>0.37626489996910095</real> + </dict> + <key>Ansi 14 Color</key> + <dict> + <key>Blue Component</key> + <real>0.79221165180206299</real> + <key>Green Component</key> + <real>0.73511248826980591</real> + <key>Red Component</key> + <real>0.46331635117530823</real> + </dict> + <key>Ansi 15 Color</key> + <dict> + <key>Blue Component</key> + <real>0.68263441324234009</real> + <key>Green Component</key> + <real>0.71090340614318848</real> + <key>Red Component</key> + <real>0.6965288519859314</real> + </dict> + <key>Ansi 2 Color</key> + <dict> + <key>Blue Component</key> + <real>0.35710996389389038</real> + <key>Green Component</key> + <real>0.71854472160339355</real> + <key>Red Component</key> + <real>0.48304364085197449</real> + </dict> + <key>Ansi 3 Color</key> + <dict> + <key>Blue Component</key> + <real>0.16496320068836212</real> + <key>Green Component</key> + <real>0.70341014862060547</real> + <key>Red Component</key> + <real>0.91225624084472656</real> + </dict> + <key>Ansi 4 Color</key> + <dict> + <key>Blue Component</key> + <real>0.82943236827850342</real> + <key>Green Component</key> + <real>0.60329484939575195</real> + <key>Red Component</key> + <real>0.29914027452468872</real> + </dict> + <key>Ansi 5 Color</key> + <dict> + <key>Blue Component</key> + <real>0.76894307136535645</real> + <key>Green Component</key> + <real>0.49908417463302612</real> + <key>Red Component</key> + <real>0.64749133586883545</real> + </dict> + <key>Ansi 6 Color</key> + <dict> + <key>Blue Component</key> + <real>0.67739421129226685</real> + <key>Green Component</key> + <real>0.60572487115859985</real> + <key>Red Component</key> + <real>0.22138151526451111</real> + </dict> + <key>Ansi 7 Color</key> + <dict> + <key>Blue Component</key> + <real>0.96549803018569946</real> + <key>Green Component</key> + <real>0.98070180416107178</real> + <key>Red Component</key> + <real>0.98026049137115479</real> + </dict> + <key>Ansi 8 Color</key> + <dict> + <key>Blue Component</key> + <real>0.34851333498954773</real> + <key>Green Component</key> + <real>0.3565424382686615</real> + <key>Red Component</key> + <real>0.34871619939804077</real> + </dict> + <key>Ansi 9 Color</key> + <dict> + <key>Blue Component</key> + <real>0.651419997215271</real> + <key>Green Component</key> + <real>0.55888265371322632</real> + <key>Red Component</key> + <real>0.81987529993057251</real> + </dict> + <key>Background Color</key> + <dict> + <key>Blue Component</key> + <real>0.11759774386882782</real> + <key>Green Component</key> + <real>0.11759574711322784</real> + <key>Red Component</key> + <real>0.11759926378726959</real> + </dict> + <key>Bold Color</key> + <dict> + <key>Blue Component</key> + <real>0.98028081655502319</real> + <key>Green Component</key> + <real>1</real> + <key>Red Component</key> + <real>1</real> + </dict> + <key>Cursor Color</key> + <dict> + <key>Blue Component</key> + <real>0.31030187010765076</real> + <key>Green Component</key> + <real>0.81186991930007935</real> + <key>Red Component</key> + <real>0.92885816097259521</real> + </dict> + <key>Cursor Text Color</key> + <dict> + <key>Blue Component</key> + <real>0.20856963098049164</real> + <key>Green Component</key> + <real>0.22283002734184265</real> + <key>Red Component</key> + <real>0.20568123459815979</real> + </dict> + <key>Foreground Color</key> + <dict> + <key>Blue Component</key> + <real>0.9264865517616272</real> + <key>Green Component</key> + <real>0.96665072441101074</real> + <key>Red Component</key> + <real>0.97033727169036865</real> + </dict> + <key>Selected Text Color</key> + <dict> + <key>Blue Component</key> + <real>0.9264865517616272</real> + <key>Green Component</key> + <real>0.96665072441101074</real> + <key>Red Component</key> + <real>0.97033727169036865</real> + </dict> + <key>Selection Color</key> + <dict> + <key>Blue Component</key> + <real>0.46659797430038452</real> + <key>Green Component</key> + <real>0.34349527955055237</real> + <key>Red Component</key> + <real>0.089366093277931213</real> + </dict> +</dict> +</plist> diff --git a/colors/Japanesque/README.markdown b/colors/Japanesque/README.markdown new file mode 100644 index 0000000..07926d3 --- /dev/null +++ b/colors/Japanesque/README.markdown @@ -0,0 +1,24 @@ +# Japanesque + +![The image of Japanesque on iTerm 2](http://cdn-ak.f.st-hatena.com/images/fotolife/a/aereal/20130102/20130102224938.png) + +Japanesque is colorscheme featured Japanese traditional colors. + +## Supported Applications + + * [iTerm 2](http://iterm2.com/) + +## Author + +aereal ([email protected]) + +## License + +The MIT License (MIT) +Copyright © 2013 aereal, aereal.org + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/colors/dircolors-solarized b/colors/dircolors-solarized new file mode 160000 index 0000000..c1779cd --- /dev/null +++ b/colors/dircolors-solarized @@ -0,0 +1 @@ +Subproject commit c1779cd7274eb4ad29d94193a4d859a93c5ee2cb diff --git a/osx/defaults/alfred.bash b/osx/defaults/alfred.bash new file mode 100755 index 0000000..75eb5e8 --- /dev/null +++ b/osx/defaults/alfred.bash @@ -0,0 +1,6 @@ +#!/usr/bin/env bash + +defaults write com.alfredapp.Alfred appearance.hideStatusBarIcon -bool true +defaults write com.alfredapp.Alfred appearance.hidePreferencesCogIcon -bool true +defaults write com.alfredapp.Alfred appearance.hideHat -bool true +defaults write com.alfredapp.Alfred system.eject -bool true diff --git a/osx/defaults/config.bash b/osx/defaults/config.bash new file mode 100755 index 0000000..deb0d1d --- /dev/null +++ b/osx/defaults/config.bash @@ -0,0 +1,79 @@ +#!/usr/bin/env bash + +# Dock {{{ +defaults write com.apple.dock autohide -bool true +defaults write com.apple.dock autohide-delay -float 0 +defaults write com.apple.dock mineffect scale +defaults write com.apple.dock minimize-to-application -bool true +defaults write com.apple.dock showhidden -bool true +defaults write com.apple.dock no-glass -bool true +defaults write com.apple.dock magnification -bool true +defaults write com.apple.dock mouse-over-hilite-stack -bool true +defaults write com.apple.dock show-process-indicator -bool false +defaults write com.apple.dock dashboard-in-overlay -bool true +defaults write com.apple.dock expose-animation-duration -float 0.1 +defaults write com.apple.dashboard mcx-disabled -bool true +# }}} +# Time Machine {{{ +defaults write com.apple.TimeMachine DoNotOfferNewDisksForBackup -bool true +sudo tmutil disablelocal +# }}} +# Appearance {{{ +defaults write -g AppleAquaColorVariant -int 6 # Graphite +defaults write -g AppleEnableMenuBarTransparency -bool false +defaults write -g AppleShowScrollBars -string 'Automatic' +# }}} +# Finder {{{ +defaults write -g AppleShowAllExtensions -bool true +defaults write com.apple.finder FXDefaultSearchScope -string 'SCcf' +defaults write com.apple.finder QLEnableXRayFolders -bool true +defaults write com.apple.finder DisableAllAnimations -bool true +defaults write com.apple.finder AppleShowAllFiles -bool true +defaults write com.apple.finder ShowStatusBar -bool true +defaults write com.apple.finder ShowPathbar -bool true +defaults write com.apple.finder FXPreferredViewStyle -string "Nslv" +defaults write -g NSNavPanelExpandedStateForSaveMode -bool true +defaults write com.apple.LaunchServices LSQuarantine -bool false +defaults write com.apple.finder FXEnableExtensionChangeWarning -bool true +# }}} +# Screen Saver {{{ +defaults write com.apple.screensaver askForPassword -int 1 +defaults write com.apple.screensaver askForPasswordDelay -int 0 +# }}} +# Trackpad {{{ +defaults write com.apple.driver.AppleBluetoothMultitouch.trackpad Clicking -bool true +defaults write com.apple.driver.AppleBluetoothMultitouch.trackpad DragLock -bool true +# }}} +# Activity Monitor.app {{{ +defaults write com.apple.ActivityMonitor IconType -int 4 +# }}} +# App Store {{{ +defaults write com.apple.appstore ShowDebugMenu -bool true +# }}} + +defaults write -g NSAutomaticSpellingCorrectionEnabled -bool false + +defaults write com.apple.frameworks.diskimages skip-verify -bool true +defaults write com.apple.frameworks.diskimages skip-verify-locked -bool true +defaults write com.apple.frameworks.diskimages skip-verify-remote -bool true + +defaults write com.apple.desktopservices DSDontWriteNetworkStores -bool true + +# Enable full-keyboard access (enable tab-key to focus all UI control items) +defaults write -g AppleKeyboardUIMode -int 3 + +defaults write -g com.apple.keyboard.fnState -bool true + +defaults write -g NSQuitAlwaysKeepsWindows -bool false + +# Huge moust pointer +defaults write com.apple.universalaccess mouseDriverCursorSize -int 4 + +# http://www.defaults-write.com/increase-the-speed-of-os-x-dialogs-boxes/#.UfSW3GSsgy4 +defaults write -g NSWindowResizeTime -float 0.001 + +# Save to disk (not to iCloud) +defaults write -g NSDocumentSaveNewDocumentsToCloud -bool false + +# Disable standby mode +sudo pmset -a standbydelay 86400 # 24 hours diff --git a/osx/keyremap4macbook/config.sh b/osx/keyremap4macbook/config.sh new file mode 100644 index 0000000..015eaf5 --- /dev/null +++ b/osx/keyremap4macbook/config.sh @@ -0,0 +1,25 @@ +#!/bin/sh + +cli=/Applications/KeyRemap4MacBook.app/Contents/Applications/KeyRemap4MacBook_cli.app/Contents/MacOS/KeyRemap4MacBook_cli + +$cli set org.aereal.sequel-pro.remap-c-h-to-delete 1 +/bin/echo -n . +$cli set repeat.initial_wait 200 +/bin/echo -n . +$cli set org.aereal.limechat.move-to-previous-unread-channel 1 +/bin/echo -n . +$cli set remap.space2shiftL_space_keyrepeat 1 +/bin/echo -n . +$cli set org.aereal.limechat.move-down-channel 1 +/bin/echo -n . +$cli set option.emacsmode_controlM 1 +/bin/echo -n . +$cli set repeat.wait 35 +/bin/echo -n . +$cli set org.aereal.limechat.move-up-channel 1 +/bin/echo -n . +$cli set remap.swapcolons 1 +/bin/echo -n . +$cli set org.aereal.limechat.move-to-next-unread-channel 1 +/bin/echo -n . +/bin/echo diff --git a/osx/keyremap4macbook/private.xml b/osx/keyremap4macbook/private.xml new file mode 100644 index 0000000..04bce03 --- /dev/null +++ b/osx/keyremap4macbook/private.xml @@ -0,0 +1,106 @@ +<?xml version="1.0"?> +<root> + <appdef> + <appname>TERMINAL</appname> + <equal>com.googlecode.iterm2</equal> + </appdef> + + <appdef> + <appname>SEQUELPRO</appname> + <equal>com.sequelpro.SequelPro</equal> + </appdef> + + <appdef> + <appname>LIMECHAT</appname> + <equal>net.limechat.LimeChat</equal> + <equal>net.limechat.LimeChat-AppStore</equal> + </appdef> + + <item> + <name>LimeChat</name> + <item> + <name>Move up active channel</name> + <identifier>org.aereal.limechat.move-up-channel</identifier> + <only>LIMECHAT</only> + <autogen>--KeyToKey-- KeyCode::K, VK_COMMAND, KeyCode::CURSOR_UP, VK_COMMAND</autogen> + </item> + <item> + <name>Move down active channel</name> + <identifier>org.aereal.limechat.move-down-channel</identifier> + <only>LIMECHAT</only> + <autogen>--KeyToKey-- KeyCode::J, VK_COMMAND, KeyCode::CURSOR_DOWN, VK_COMMAND</autogen> + </item> + <item> + <name>Move to previous unread channel</name> + <identifier>org.aereal.limechat.move-to-previous-unread-channel</identifier> + <only>LIMECHAT</only> + <autogen>--KeyToKey-- KeyCode::J, VK_COMMAND | VK_SHIFT, KeyCode::CURSOR_UP, VK_CONTROL | VK_SHIFT</autogen> + </item> + <item> + <name>Move to next unread channel</name> + <identifier>org.aereal.limechat.move-to-next-unread-channel</identifier> + <only>LIMECHAT</only> + <autogen>--KeyToKey-- KeyCode::K, VK_COMMAND | VK_SHIFT, KeyCode::CURSOR_DOWN, VK_CONTROL | VK_SHIFT</autogen> + </item> + </item> + + <item> + <name>Sequal Pro</name> + <item> + <name>Remap C-h to DELETE</name> + <identifier>org.aereal.sequel-pro.remap-c-h-to-delete</identifier> + <only>SEQUELPRO</only> + <autogen>--KeyToKey-- KeyCode::H, VK_CONTROL, KeyCode::DELETE</autogen> + </item> + </item> + + <item> + <name>Japanese IME</name> + <item> + <name>Option_L to EISUU</name> + <identifier>org.aereal.remap-option-l-to-kana-eisuu</identifier> + <autogen>--KeyOverlaidModifier-- KeyCode::OPTION_L, KeyCode::OPTION_L, KeyCode::JIS_EISUU</autogen> + </item> + <item> + <name>Option_R to KANA</name> + <identifier>org.aereal.remap-option-r-to-kana-eisuu</identifier> + <autogen>--KeyOverlaidModifier-- KeyCode::OPTION_R, KeyCode::OPTION_R, KeyCode::JIS_KANA</autogen> + </item> + </item> + + <item> + <name>tmux integration</name> + <item> + <name>Double-tap Command_R to tmux prefix key on Terminal application</name> + <identifier>org.aereal.double-tap-command-r-to-tmux-prefix-key</identifier> + <only>TERMINAL</only> + <autogen>--DoublePressModifier-- KeyCode::COMMAND_R, KeyCode::COMMAND_R, KeyCode::K, ModifierFlag::CONTROL_L</autogen> + </item> + <item> + <name>Cmd-T to [prefix]-c</name> + <appendix>Create a new window</appendix> + <only>TERMINAL</only> + <identifier>org.aereal.command-t-to-prefix-c</identifier> + <autogen>--KeyToKey-- KeyCode::T, VK_COMMAND, KeyCode::K, VK_CONTROL, KeyCode::C</autogen> + </item> + <item> + <name>Cmd-W to [prefix]-k</name> + <appendix>Kill the window</appendix> + <only>TERMINAL</only> + <identifier>org.aereal.tmux.command-w-to-prefix-k</identifier> + <autogen>--KeyToKey-- KeyCode::W, VK_COMMAND, KeyCode::K, VK_CONTROL, KeyCode::K</autogen> + </item> + <item> + <name>Move the window (Next)</name> + <only>TERMINAL</only> + <identifier>org.aereal.tmux.move-the-window-next</identifier> + <autogen>--KeyToKey-- KeyCode::BRACKET_RIGHT, VK_COMMAND | VK_SHIFT, KeyCode::K, VK_CONTROL, KeyCode::N</autogen> + </item> + <item> + <name>Move the window (Previous)</name> + <only>TERMINAL</only> + <identifier>org.aereal.tmux.move-the-window-previous</identifier> + <autogen>--KeyToKey-- KeyCode::BRACKET_LEFT, VK_COMMAND | VK_SHIFT, KeyCode::K, VK_CONTROL, KeyCode::P</autogen> + </item> + </item> +</root> diff --git a/test/Gemfile b/test/Gemfile new file mode 100644 index 0000000..f8fc0f7 --- /dev/null +++ b/test/Gemfile @@ -0,0 +1,4 @@ +source 'https://rubygems.org/' + +gem 'minitest-spec' +gem 'rake' diff --git a/test/dotfiles_test.rb b/test/dotfiles_test.rb new file mode 100644 index 0000000..628339e --- /dev/null +++ b/test/dotfiles_test.rb @@ -0,0 +1,26 @@ +require 'pathname' +require 'minitest/autorun' +require 'minitest/spec' +require 'yaml' + +HOME = Pathname.new(ENV.fetch('HOME')) +PROJECT_DIR = Pathname.new(__FILE__).expand_path.parent.parent +SOURCE_DIR = PROJECT_DIR +DEST_DIR = Pathname.new(ENV.fetch('DOTFILES_INSTALL_DIR', HOME)) +CONFIG = YAML.load_file(PROJECT_DIR + '.dotfiles.yml') +DOTFILES = CONFIG['dotfiles'] +DOTFILES_MAP = DOTFILES.map {|f| + { basename: f, source: SOURCE_DIR + f, dest: DEST_DIR + f } +} + +DOTFILES_MAP.each do |dotfile| + describe dotfile[:basename] do + it "is symlink to source" do + source = dotfile[:source] + dest = dotfile[:dest] + + dest.symlink?.must_equal(true) + dest.readlink.must_equal(source) + end + end +end
vilterp/VMLang
574ba343ad18bd8d179ff7cfd7455ee9ac8fcd65
fixed callgraph, added timing code to VM: runs at 10 million instructions per second
diff --git a/bugs.txt b/bugs.txt index a42a63b..ddb93fd 100644 --- a/bugs.txt +++ b/bugs.txt @@ -1,20 +1,24 @@ COMPILER Overall - what about overloading (typeclasses, abstract classes, oh my!) - doesn't give error if user tries to define "true" or any other root function Parser - can't parse floats or chars - use RegexParsers to make custom scanner - error messages will be hard - give location info to tokens, if possible - maybe use scala.io.Source (has fromString method) - then use custom scanner in existing parser - unary "not"s aren't parsed right Simplifier - - turns definition of fac into IfExpr(Call(==,List(Call(n,List()), IntLit(1))),Call(==,List(Call(n,List()), IntLit(1))),Call(==,List(Call(n,List()), IntLit(1)))) \ No newline at end of file + - turns definition of fac into IfExpr(Call(==,List(Call(n,List()), IntLit(1))),Call(==,List(Call(n,List()), IntLit(1))),Call(==,List(Call(n,List()), IntLit(1)))) + +Callgraph + + - calls TypeCheck.apply(List[Def]), which doesn't exist. Don't know why Scala compiler didn't catch this. diff --git a/examples/fac.output b/examples/fac.output deleted file mode 100644 index 9ff7d83..0000000 --- a/examples/fac.output +++ /dev/null @@ -1,130 +0,0 @@ - STACK_START - MOVE_A_SP - MOVE_A_FP -wExpr: Call(main,List()) s: List() -call prelude - MOVE_FP_A - I_STORE_A_SP - MOVE_SP_FP - INC_SP_INT - I_CONST_A - I_STORE_A_SP - INC_SP_INT - GOTO -call postlude - DEC_SP_INT - I_LOAD_SP_FP - DEC_SP_BY - STOP -wExpr: Call(printInt,List(Call(fac,List(IntLit(5))))) s: List() -wExpr: Call(fac,List(IntLit(5))) s: List() -wExpr: IntLit(5) s: List() - I_CONST_A - I_STORE_A_SP - INC_SP_INT -call prelude - MOVE_FP_A - I_STORE_A_SP - MOVE_SP_FP - INC_SP_INT - I_CONST_A - I_STORE_A_SP - INC_SP_INT - GOTO -call postlude - DEC_SP_INT - I_LOAD_SP_FP - DEC_SP_BY - I_STORE_A_SP - INC_SP_INT - DEC_SP_INT - I_LOAD_SP_A - PRINT_INT_A -def postlude - DEC_SP_INT - GOTO_SP -wExpr: IfExpr(Call(==,List(Call(n,List()), IntLit(1))),IntLit(1),Call(*,List(Call(n,List()), Call(fac,List(Call(-,List(Call(n,List()), IntLit(1)))))))) s: List((n,4)) -wExpr: Call(==,List(Call(n,List()), IntLit(1))) s: List((n,4)) -cmpOp: a: Call(n,List()) b: IntLit(1) s: List((n,4)) -intOpNoPush a: Call(n,List()) b: IntLit(1) s: List((n,4)) -wExpr: Call(n,List()) s: List((n,4)) - MOVE_FP_A - I_CONST_B - I_SUB - I_LOAD_A_A - I_STORE_A_SP - INC_SP_INT -wExpr: IntLit(1) s: List((n,4)) - I_CONST_A - I_STORE_A_SP - INC_SP_INT - DEC_SP_INT - I_LOAD_SP_B - DEC_SP_INT - I_LOAD_SP_A -hello from cmpOp's anon func - I_SUB -hello from =='s anon func - EQ_A - GOTO_IF_NOT_A -wExpr: IntLit(1) s: List((n,4)) - I_CONST_A - I_STORE_A_SP - INC_SP_INT - GOTO -wExpr: Call(*,List(Call(n,List()), Call(fac,List(Call(-,List(Call(n,List()), IntLit(1))))))) s: List((n,4)) -intOpNoPush a: Call(n,List()) b: Call(fac,List(Call(-,List(Call(n,List()), IntLit(1))))) s: List((n,4)) -wExpr: Call(n,List()) s: List((n,4)) - MOVE_FP_A - I_CONST_B - I_SUB - I_LOAD_A_A - I_STORE_A_SP - INC_SP_INT -wExpr: Call(fac,List(Call(-,List(Call(n,List()), IntLit(1))))) s: List((n,4)) -wExpr: Call(-,List(Call(n,List()), IntLit(1))) s: List((n,4)) -intOpNoPush a: Call(n,List()) b: IntLit(1) s: List((n,4)) -wExpr: Call(n,List()) s: List((n,4)) - MOVE_FP_A - I_CONST_B - I_SUB - I_LOAD_A_A - I_STORE_A_SP - INC_SP_INT -wExpr: IntLit(1) s: List((n,4)) - I_CONST_A - I_STORE_A_SP - INC_SP_INT - DEC_SP_INT - I_LOAD_SP_B - DEC_SP_INT - I_LOAD_SP_A - I_SUB - I_STORE_A_SP - INC_SP_INT -call prelude - MOVE_FP_A - I_STORE_A_SP - MOVE_SP_FP - INC_SP_INT - I_CONST_A - I_STORE_A_SP - INC_SP_INT - GOTO -call postlude - DEC_SP_INT - I_LOAD_SP_FP - DEC_SP_BY - I_STORE_A_SP - INC_SP_INT - DEC_SP_INT - I_LOAD_SP_B - DEC_SP_INT - I_LOAD_SP_A - I_MUL - I_STORE_A_SP - INC_SP_INT -def postlude - DEC_SP_INT - DEC_SP_INT - GOTO_SP diff --git a/examples/fac.vmlbc b/examples/fac.vmlbc deleted file mode 100644 index 3c33235..0000000 --- a/examples/fac.vmlbc +++ /dev/null @@ -1,100 +0,0 @@ -0 STACK_START -1 MOVE_A_SP -2 MOVE_A_FP -3 MOVE_FP_A -4 I_STORE_A_SP -5 MOVE_SP_FP -6 INC_SP_INT -7 I_CONST_A 19 -12 I_STORE_A_SP -13 INC_SP_INT -14 GOTO 27 -19 DEC_SP_INT -20 I_LOAD_SP_FP -21 DEC_SP_BY 0 -26 STOP -27 I_CONST_A 5 -32 I_STORE_A_SP -33 INC_SP_INT -34 MOVE_FP_A -35 I_STORE_A_SP -36 MOVE_SP_FP -37 INC_SP_INT -38 I_CONST_A 50 -43 I_STORE_A_SP -44 INC_SP_INT -45 GOTO 64 -50 DEC_SP_INT -51 I_LOAD_SP_FP -52 DEC_SP_BY 4 -57 I_STORE_A_SP -58 INC_SP_INT -59 DEC_SP_INT -60 I_LOAD_SP_A -61 PRINT_INT_A -62 DEC_SP_INT -63 GOTO_SP -64 MOVE_FP_A -65 I_CONST_B 4 -70 I_SUB -71 I_LOAD_A_A -72 I_STORE_A_SP -73 INC_SP_INT -74 I_CONST_A 1 -79 I_STORE_A_SP -80 INC_SP_INT -81 DEC_SP_INT -82 I_LOAD_SP_B -83 DEC_SP_INT -84 I_LOAD_SP_A -85 I_SUB -86 GOTO_IF_NOT_A 103 -91 I_CONST_A 1 -96 I_STORE_A_SP -97 INC_SP_INT -98 GOTO 169 -103 MOVE_FP_A -104 I_CONST_B 4 -109 I_SUB -110 I_LOAD_A_A -111 I_STORE_A_SP -112 INC_SP_INT -113 MOVE_FP_A -114 I_CONST_B 4 -119 I_SUB -120 I_LOAD_A_A -121 I_STORE_A_SP -122 INC_SP_INT -123 I_CONST_A 1 -128 I_STORE_A_SP -129 INC_SP_INT -130 DEC_SP_INT -131 I_LOAD_SP_B -132 DEC_SP_INT -133 I_LOAD_SP_A -134 I_SUB -135 I_STORE_A_SP -136 INC_SP_INT -137 MOVE_FP_A -138 I_STORE_A_SP -139 MOVE_SP_FP -140 INC_SP_INT -141 I_CONST_A 153 -146 I_STORE_A_SP -147 INC_SP_INT -148 GOTO 64 -153 DEC_SP_INT -154 I_LOAD_SP_FP -155 DEC_SP_BY 4 -160 I_STORE_A_SP -161 INC_SP_INT -162 DEC_SP_INT -163 I_LOAD_SP_B -164 DEC_SP_INT -165 I_LOAD_SP_A -166 I_MUL -167 I_STORE_A_SP -168 INC_SP_INT -169 DEC_SP_INT -170 DEC_SP_INT -171 GOTO_SP diff --git a/examples/test2.bytecode b/examples/test2.bytecode deleted file mode 100644 index b5245a0..0000000 --- a/examples/test2.bytecode +++ /dev/null @@ -1,65 +0,0 @@ -0 MOVE_BP_A -1 I_STORE_A_SP -2 MOVE_SP_BP -3 INC_SP_INT -4 MOVE_COUNTER_A -5 I_CONST_B 13 -10 I_ADD -11 I_STORE_A_SP -12 INC_SP_INT -13 GOTO 47 -18 INC_SP_INT -19 I_LOAD_BP_SP -20 MOVE_SP_A -21 I_CONST_B 8 -26 I_SUB -27 MOVE_A_SP -28 I_STORE_BP_SP -29 MOVE_SP_A -30 I_CONST_B 0 -35 I_ADD -36 MOVE_A_SP -37 I_LOAD_BP_SP -38 MOVE_SP_A -39 I_CONST_B 0 -44 I_SUB -45 MOVE_A_SP -46 STOP -47 MOVE_BP_A -48 I_STORE_A_SP -49 MOVE_SP_BP -50 INC_SP_INT -51 MOVE_COUNTER_A -52 I_CONST_B 13 -57 I_ADD -58 I_STORE_A_SP -59 INC_SP_INT -60 GOTO 99 -65 INC_SP_INT -66 I_LOAD_BP_SP -67 MOVE_SP_A -68 I_CONST_B 8 -73 I_SUB -74 MOVE_A_SP -75 I_STORE_BP_SP -76 MOVE_SP_A -77 I_CONST_B 0 -82 I_ADD -83 MOVE_A_SP -84 I_LOAD_BP_SP -85 MOVE_SP_A -86 I_CONST_B 0 -91 I_SUB -92 MOVE_A_SP -93 DEC_SP_INT -94 I_LOAD_A_SP -95 PRINT_INT_A -96 DEC_SP_INT -97 I_LOAD_A_SP -98 GOTO_A -99 I_CONST_A 2 -104 I_STORE_A_SP -105 INC_SP_INT -106 DEC_SP_INT -107 I_LOAD_A_SP -108 GOTO_A diff --git a/examples/test2.vml b/examples/test2.vml deleted file mode 100644 index 4ab5091..0000000 --- a/examples/test2.vml +++ /dev/null @@ -1,2 +0,0 @@ -main:Null = printInt(a) -a:Int = 2 diff --git a/examples/test2.vmla b/examples/test2.vmla deleted file mode 100644 index 43085fd..0000000 --- a/examples/test2.vmla +++ /dev/null @@ -1,65 +0,0 @@ -MOVE_FP_A -I_STORE_A_SP -MOVE_SP_FP -INC_SP_INT -MOVE_COUNTER_A -I_CONST_B 13 -I_ADD -I_STORE_A_SP -INC_SP_INT -GOTO 47 -INC_SP_INT -I_LOAD_FP_SP -MOVE_SP_A -I_CONST_B 8 -I_SUB -MOVE_A_SP -I_STORE_FP_SP -MOVE_SP_A -I_CONST_B 0 -I_ADD -MOVE_A_SP -I_LOAD_FP_SP -MOVE_SP_A -I_CONST_B 0 -I_SUB -MOVE_A_SP -STOP -MOVE_FP_A -I_STORE_A_SP -MOVE_SP_FP -INC_SP_INT -MOVE_COUNTER_A -I_CONST_B 13 -I_ADD -I_STORE_A_SP -INC_SP_INT -GOTO 99 -INC_SP_INT -I_LOAD_FP_SP -MOVE_SP_A -I_CONST_B 8 -I_SUB -MOVE_A_SP -I_STORE_FP_SP -MOVE_SP_A -I_CONST_B 0 -I_ADD -MOVE_A_SP -I_LOAD_FP_SP -MOVE_SP_A -I_CONST_B 0 -I_SUB -MOVE_A_SP -DEC_SP_INT -I_LOAD_A_SP -PRINT_INT_A -DEC_SP_INT -I_LOAD_A_SP -GOTO_A -I_CONST_A 2 -I_STORE_A_SP -INC_SP_INT -DEC_SP_INT -I_LOAD_A_SP -GOTO_A diff --git a/examples/test2.vmlc b/examples/test2.vmlc deleted file mode 100644 index 76f369e..0000000 Binary files a/examples/test2.vmlc and /dev/null differ diff --git a/examples/test2.vmlcg b/examples/test2.vmlcg deleted file mode 100644 index 781b164..0000000 --- a/examples/test2.vmlcg +++ /dev/null @@ -1,2 +0,0 @@ -main printInt -main a diff --git a/examples/test3.vml b/examples/test3.vml deleted file mode 100644 index 8a3756d..0000000 --- a/examples/test3.vml +++ /dev/null @@ -1 +0,0 @@ -main:Int = 2 diff --git a/src/vmlang/callgraph/Main.scala b/src/vmlang/callgraph/Main.scala index 0f03fe6..9c882d2 100644 --- a/src/vmlang/callgraph/Main.scala +++ b/src/vmlang/callgraph/Main.scala @@ -1,37 +1,47 @@ package vmlang.callgraph import vmlang.common.optparser._ import vmlang.compiler._ import vmlang.compiler.typecheck._ import vmlang.compiler.ast._ object Main extends OptParser { def numArgs(n:Int) = n == 1 val argErrorMsg = "supply 1 file to show callgraph for" val knownFlags = List() val defaultOpts = Map[String,String]() val help = "usage: vmlcg <file to show call graph for>" def run(args:List[String], flags:List[String], opts:Map[String,String]):Unit = try { - val callTuples = extractCalls(TypeCheck(Parse(loadFile(args.head))).defs) flatMap { - case (n, cs) => cs map { c => (n, c) } } + val callTuples = extractCalls( + TypeCheck( + MakeEnv( + Parse( + loadFile( + args.head + ) + ), + TypeCheck.rootFuncTypes, + TypeCheck.typeTree + ) + ).defs) flatMap { case (n, cs) => cs map { c => (n, c) } } callTuples foreach { case (caller, callee) => println(caller + "\t" + callee) } } catch { case e:CompilerError => println(e.repr) } def extractCalls(defs:Map[String,Def]):Map[String,List[String]] = Map() ++ (defs map { case (n,d) => (n, calls(d.body) filter { c => !d.params.exists { _.name == c } }) }) def calls(e:Expr):List[String] = e match { case a:Atom => Nil case IfExpr(c, i, e) => calls(c) ::: calls(i) ::: calls(e) case Call(name, args) => name :: (args flatMap (calls _)) } } diff --git a/src/vmlang/vm/Main.scala b/src/vmlang/vm/Main.scala index e33b20b..752a138 100644 --- a/src/vmlang/vm/Main.scala +++ b/src/vmlang/vm/Main.scala @@ -1,37 +1,49 @@ package vmlang.vm import vmlang.common.optparser._ object Main extends OptParser { def numArgs(n:Int) = n == 1 val argErrorMsg = "supply 1 bytecode file to run" - val knownFlags = List("d") + val knownFlags = List("d", "t") val defaultOpts = Map("heap_size" -> "1024", "stack_size" -> "1024") val help = "usage: vml <bytecode file> <options>\n" + "-heap_size=<num bytes> heap size in bytes\n" + "-stack_size=<num bytes> stack size in bytes\n" + - "-d debug" + "-d debug\n" + + "-t time" def run(args:List[String], flags:List[String], opts:Map[String,String]):Unit = { val heapSize = try { opts("heap_size").toInt } catch { case e:NumberFormatException => throw FatalError("Invalid heap size argument") } val stackSize = try { opts("stack_size").toInt } catch { case e:NumberFormatException => throw FatalError("Invalid stack size argument") } // business time try { - new VM(loadFileBytes(args(0)), heapSize, stackSize, flags contains "d").run + val start = System.currentTimeMillis + val cycles = new VM(loadFileBytes(args(0)), heapSize, stackSize, flags contains "d").run + if(flags contains "t") printStats(System.currentTimeMillis - start, cycles) } catch { case e:InitError => throw FatalError("Couldn't start VM: " + e.message) case e:MalformedProgramError => throw FatalError("VM error: malformed program") case e:StackOverflowError => throw FatalError("VM error: stack overflow") } } + def printStats(elapsedTime:Long, cycles:Long):Unit = { + println + val secs = elapsedTime.asInstanceOf[Float] / 1000 + println(secs + " seconds elapsed") + println(cycles + " instructions run") + val instsPerSec = cycles.asInstanceOf[Float] / secs + println(instsPerSec + " instructions/sec (" + instsPerSec / 1e6 + " MHz)") + } + } diff --git a/src/vmlang/vm/VM.java b/src/vmlang/vm/VM.java index ee13ae5..5c30610 100644 --- a/src/vmlang/vm/VM.java +++ b/src/vmlang/vm/VM.java @@ -1,471 +1,473 @@ package vmlang.vm; import java.io.IOException; import java.io.PrintStream; import java.io.InputStream; import vmlang.common.Opcodes; public class VM { // registers private int A, B, SP, FP; private int counter; // memory private byte[] program; private byte[] memory; // io private InputStream in; private PrintStream out; private int stackStart; boolean debug; private static final Opcodes[] opcodes = Opcodes.values(); // inefficient? public VM(byte[] prog, int heapSize, int stackSize, boolean d) throws InitError { this(prog, heapSize, stackSize, System.in, System.out, d); } public VM(byte[] prog, int heapSize, int stackSize, InputStream is, PrintStream os, boolean d) throws InitError { if(heapSize % 8 != 0) throw new InitError("Heap size must be divisible by 8 (for malloc)"); program = prog; memory = new byte[heapSize + stackSize]; stackStart = heapSize; in = is; out = os; debug = d; } - public void run() throws VMError { + public long run() throws VMError { int nextAddr; + long cycles = 0; while(true) { Opcodes opcode; try { opcode = opcodes[progReadByte()]; } catch(ArrayIndexOutOfBoundsException e) { throw getMalfProgEx(); } + cycles++; if(debug) System.out.print(opcode); switch(opcode) { // FLOW CONTROL // basic case STOP: - return; + return cycles; case GOTO: counter = progReadInt(); break; case GOTO_A: counter = A; break; case GOTO_SP: counter = memReadInt(SP); break; case GOTO_IF_NOT_A: nextAddr = progReadInt(); if(A == 0) counter = nextAddr; break; // LOAD & STORE (Von-Neumann bottleneck) // constants case I_CONST_A: A = progReadInt(); break; case I_CONST_B: B = progReadInt(); break; case B_CONST_A: A = progReadByte(); break; case B_CONST_B: B = progReadByte(); break; // load case I_LOAD_A_B: B = memReadInt(A); break; case I_LOAD_A_SP: SP = memReadInt(A); break; case I_LOAD_A_FP: FP = memReadInt(A); break; case I_LOAD_A_A: A = memReadInt(A); break; case I_LOAD_B_A: A = memReadInt(B); break; case I_LOAD_B_SP: SP = memReadInt(B); break; case I_LOAD_B_FP: FP = memReadInt(B); break; case I_LOAD_SP_A: A = memReadInt(SP); break; case I_LOAD_SP_B: B = memReadInt(SP); break; case I_LOAD_SP_FP: FP = memReadInt(SP); break; case I_LOAD_FP_A: A = memReadInt(FP); break; case I_LOAD_FP_B: B = memReadInt(FP); break; case I_LOAD_FP_SP: SP = memReadInt(FP); break; case B_LOAD_A_B: B = memReadByte(A); break; case B_LOAD_A_SP: SP = memReadByte(A); break; case B_LOAD_A_FP: FP = memReadByte(A); break; case B_LOAD_B_A: A = memReadByte(B); break; case B_LOAD_B_SP: SP = memReadByte(B); break; case B_LOAD_B_FP: FP = memReadByte(B); break; case B_LOAD_SP_A: A = memReadByte(SP); break; case B_LOAD_SP_B: B = memReadByte(SP); break; case B_LOAD_SP_FP: FP = memReadByte(SP); break; case B_LOAD_FP_A: A = memReadByte(FP); break; case B_LOAD_FP_B: B = memReadByte(FP); break; case B_LOAD_FP_SP: SP = memReadByte(FP); break; // store case I_STORE_A_B: memWriteInt(B,A); break; case I_STORE_A_SP: memWriteInt(SP,A); break; case I_STORE_A_FP: memWriteInt(FP,A); break; case I_STORE_B_A: memWriteInt(A,B); break; case I_STORE_B_SP: memWriteInt(SP,B); break; case I_STORE_B_FP: memWriteInt(FP,B); break; case I_STORE_SP_A: memWriteInt(A,SP); break; case I_STORE_SP_B: memWriteInt(B,SP); break; case I_STORE_SP_FP: memWriteInt(FP,SP); break; case I_STORE_FP_A: memWriteInt(A,FP); break; case I_STORE_FP_B: memWriteInt(B,FP); break; case I_STORE_FP_SP: memWriteInt(SP,FP); break; case B_STORE_A_B: memWriteByte(B,(byte)A); break; case B_STORE_A_SP: memWriteByte(SP,(byte)A); break; case B_STORE_A_FP: memWriteByte(FP,(byte)A); break; case B_STORE_B_A: memWriteByte(A,(byte)B); break; case B_STORE_B_SP: memWriteByte(SP,(byte)B); break; case B_STORE_B_FP: memWriteByte(FP,(byte)B); break; case B_STORE_SP_A: memWriteByte(A,(byte)SP); break; case B_STORE_SP_B: memWriteByte(B,(byte)SP); break; case B_STORE_SP_FP: memWriteByte(FP,(byte)SP); break; case B_STORE_FP_A: memWriteByte(A,(byte)FP); break; case B_STORE_FP_B: memWriteByte(B,(byte)FP); break; case B_STORE_FP_SP: memWriteByte(SP,(byte)FP); break; // moves case MOVE_COUNTER_A: A = counter; break; case MOVE_A_B: B = A; break; case MOVE_A_SP: SP = A; break; case MOVE_A_FP: FP = A; break; case MOVE_B_A: A = B; break; case MOVE_B_SP: SP = B; break; case MOVE_B_FP: FP = B; break; case MOVE_SP_A: A = SP; break; case MOVE_SP_B: B = SP; break; case MOVE_SP_FP: FP = SP; break; case MOVE_FP_A: A = FP; break; case MOVE_FP_B: B = FP; break; case MOVE_FP_SP: SP = FP; break; // REGISTER OPERATIONS // int arithmetic case I_ADD: A = A + B; break; case I_SUB: A = A - B; break; case I_MUL: A = A * B; break; case I_DIV: A = A / B; break; case I_MOD: A = A % B; break; case INC_A: A++; break; // float arithmetic case F_ADD: A = Float.floatToIntBits(Float.intBitsToFloat(A) + Float.intBitsToFloat(B)); break; case F_SUB: A = Float.floatToIntBits(Float.intBitsToFloat(A) - Float.intBitsToFloat(B)); break; case F_MUL: A = A = Float.floatToIntBits(Float.intBitsToFloat(A) * Float.intBitsToFloat(B)); break; case F_DIV: A = Float.floatToIntBits(Float.intBitsToFloat(A) / Float.intBitsToFloat(B)); break; case F_MOD: A = Float.floatToIntBits(Float.intBitsToFloat(A) % Float.intBitsToFloat(B)); break; // inc/dec case INC_B: B++; break; case INC_SP: SP++; break; case INC_SP_INT: SP += 4; break; case DEC_A: A--; break; case DEC_B: B--; break; case DEC_SP: SP--; break; case DEC_SP_INT: SP -= 4; break; case DEC_SP_BY: SP -= progReadInt(); break; // logic (0: false; non-0: true) case NEG_A: if(A == 0) A = 1; else A = 0; break; case EQ_A: if(A == 0) A = 1; else A = 0; break; case LT_A: if(A < 0) A = 1; else A = 0; break; case GT_A: if(A > 0) A = 1; else A = 0; break; case AND: if(A != 0 && B != 0) A = 1; else A = 0; break; case OR: if(A != 0 || B != 0) A = 1; else A = 0; break; case STACK_START: A = stackStart; break; // io case PRINT_CHAR_A: out.print((char)A); break; case PRINT_INT_A: out.println(A); break; case READ_CHAR_A: try { A = in.read(); } catch(IOException e) { out.println(e.getMessage()); } break; } if(debug) System.out.println(" => [A: "+A+" B: "+ B+" FP: " + FP + " SP: " + SP + "]"); } } // PROGRAM READERS private byte progReadByte() throws MalformedProgramError { byte result; try { result = program[counter]; } catch(ArrayIndexOutOfBoundsException e) { throw getMalfProgEx(); } counter++; return result; } private int progReadInt() throws MalformedProgramError { return ((progReadByte() & 0xff) << 24) | ((progReadByte() & 0xff) << 16) | ((progReadByte() & 0xff) << 8) | (progReadByte() & 0xff); } // MEMORY READERS & WRITERS private byte memReadByte(int addr) throws StackOverflowError { try { return memory[addr]; } catch(ArrayIndexOutOfBoundsException e) { throw new StackOverflowError(); } } private int memReadInt(int addr) throws StackOverflowError { return ((memReadByte(addr) & 0xff) << 24) | ((memReadByte(addr+1) & 0xff) << 16) | ((memReadByte(addr+2) & 0xff) << 8) | (memReadByte(addr+3) & 0xff); } private void memWriteByte(int addr, byte val) throws StackOverflowError { try { memory[addr] = val; } catch(ArrayIndexOutOfBoundsException e) { throw new StackOverflowError(); } } private void memWriteInt(int addr, int val) throws StackOverflowError { memWriteByte(addr ,(byte)(0xff & (val >> 24))); memWriteByte(addr+1,(byte)(0xff & (val >> 16))); memWriteByte(addr+2,(byte)(0xff & (val >> 8))); memWriteByte(addr+3,(byte)(0xff & val)); } private MalformedProgramError getMalfProgEx() { return new MalformedProgramError(); } } \ No newline at end of file
vilterp/VMLang
89aad577ce78b59c47ba1b97e1f95fe820b39d4c
fixed and and or; fib compiles. I wish bash would let me put exclaimation points in here
diff --git a/bugs.txt b/bugs.txt index 5b7122d..a42a63b 100644 --- a/bugs.txt +++ b/bugs.txt @@ -1,25 +1,20 @@ COMPILER Overall - what about overloading (typeclasses, abstract classes, oh my!) - doesn't give error if user tries to define "true" or any other root function Parser - can't parse floats or chars - use RegexParsers to make custom scanner - error messages will be hard - give location info to tokens, if possible - maybe use scala.io.Source (has fromString method) - then use custom scanner in existing parser - unary "not"s aren't parsed right -Linearizer - - - if statements aren't implemented - - uses Type#size to compute instructions, but defs that take parameters with abstract types don't know what they will be called with! this computation must take place on a per-call basis, when argument types are known (note this makes CheckedDef useless) - Simplifier - turns definition of fac into IfExpr(Call(==,List(Call(n,List()), IntLit(1))),Call(==,List(Call(n,List()), IntLit(1))),Call(==,List(Call(n,List()), IntLit(1)))) \ No newline at end of file diff --git a/examples/fib.vml b/examples/fib.vml index 4da6a19..9eeb064 100644 --- a/examples/fib.vml +++ b/examples/fib.vml @@ -1,2 +1,2 @@ -main:Null = printInt(fib(20)) +main:Null = printInt(fib(30)) fib(n:Int):Int = if n == 0 or n == 1 then 1 else fib(n-1) + fib(n-2) diff --git a/examples/fib.vmlc b/examples/fib.vmlc index 0846164..f61217d 100644 Binary files a/examples/fib.vmlc and b/examples/fib.vmlc differ diff --git a/src/vmlang/compiler/Linearize.scala b/src/vmlang/compiler/Linearize.scala index ccc77ff..7c145fc 100644 --- a/src/vmlang/compiler/Linearize.scala +++ b/src/vmlang/compiler/Linearize.scala @@ -1,241 +1,242 @@ package vmlang.compiler import collection.mutable.ArrayBuffer import collection.mutable.HashMap import vmlang.common.Opcodes import vmlang.common.Opcodes._ import vmlang.compiler.ast._ // shameful imperative code... object Linearize { def apply(e:Env):Array[Byte] = new Linearizer(e).run } class Linearizer(e:Env) { type Scope = List[(String, Int)] val out = new ArrayBuffer[Byte] val refs = new HashMap[Int,String] val startingPoints = new HashMap[String,Int] val rtSizes = Map[String,Int]() ++ (e.defs map { case (n, d) => (n, e.tt getSize d.returnType) }) val scopes = Map[String,Scope]() ++ (e.defs map { case (na, d) => (na, d.params map { case ParamSpec(n, at) => (n, e.tt.getSize(at)) } ) }) def run:Array[Byte] = { // initialize SP to stack start (given by command line argument) w(STACK_START) w(MOVE_A_SP) w(MOVE_A_FP) // write call to main wExpr(Call("main", Nil), Nil) w(STOP) // write definitions for((n, d) <- e.defs) { startingPoints += (n -> out.length) // write def body expr wExpr(d.body, scopes(n)) wDefPostlude(rtSizes(n)) } resolveGotos } def resolveGotos:Array[Byte] = { for((ind, ref) <- refs) { val refInd = startingPoints(ref) // write program index (integer) to result array overWriteInt(ind + 1, refInd) } out.toArray } def wExpr(e:Expr, s:Scope):Unit = { println("wExpr: " + e + " s: " + s); e match { case IntLit(i) => w(I_CONST_A, i); wPushInt case CharLit(c) => w(B_CONST_A, c.toByte); wPushByte case FloatLit(f) => w(I_CONST_A, java.lang.Float.floatToIntBits(f)); wPushInt case Call("+", List(a, b)) => intOp(a, b, s, ()=>{ w(I_ADD) }) case Call("-", List(a, b)) => intOp(a, b, s, ()=>{ w(I_SUB) }) case Call("*", List(a, b)) => intOp(a, b, s, ()=>{ w(I_MUL) }) case Call("/", List(a, b)) => intOp(a, b, s, ()=>{ w(I_DIV) }) case Call("%", List(a, b)) => intOp(a, b, s, ()=>{ w(I_MOD) }) case Call("==", List(a, b)) => cmpOp(a, b, s, ()=>{ println("hello from =='s anon func"); w(EQ_A); }) case Call(">" , List(a, b)) => cmpOp(a, b, s, ()=>{ w(GT_A) }) case Call("<" , List(a, b)) => cmpOp(a, b, s, ()=>{ w(LT_A) }) case Call(">=", List(a, b)) => cmpOp(a, b, s, ()=>{ w(LT_A); w(NEG_A) }) case Call("<=", List(a, b)) => cmpOp(a, b, s, ()=>{ w(GT_A); w(NEG_A) }) case Call("and", List(a, b)) => byteOp(a, b, s, ()=>{ w(AND) }) case Call("or" , List(a, b)) => byteOp(a, b, s, ()=>{ w(OR) }) case Call("not", List(a)) => wExpr(a, s); wPopByteA; w(NEG_A); wPushByte() case Call("true" , Nil) => w(B_CONST_A, 1:Byte); wPushByte case Call("false", Nil) => w(B_CONST_A, 0:Byte); wPushByte case Call("null" , Nil) => // do nothing case Call("printInt", List(a)) => wExpr(a, s); wPopIntA; w(PRINT_INT_A) case Call(name, args) => argOffset(name, s) match { case Some(offset) => // is parameter w(MOVE_FP_A) w(I_CONST_B, offset) w(I_SUB) w(I_LOAD_A_A) w(I_STORE_A_SP) w(INC_SP_INT) case None => // is call (args foreach { wExpr(_, s) }) wCallPrelude wGoto(name) wCallPostlude(scopes(name).foldLeft(0){ _ + _._2 }, rtSizes(name)) // retrieve returned value } case IfExpr(c, i, e) => { // write condition wExpr(c, s) + wPopByteA // write conditional goto val condGotoInd = out.length w(GOTO_IF_NOT_A, 0) // write if expr wExpr(i, s) // write goto to after end of else expr val ifGotoInd = out.length w(GOTO, 0) // write else expr wExpr(e, s) val afterElseInd = out.length // overwrite conditional goto addr overWriteInt(condGotoInd + 1, ifGotoInd + 5) // overwrite after-if goto addr overWriteInt(ifGotoInd + 1, afterElseInd) } } } def argOffset(name:String, scope:Scope):Option[Int] = (scope findIndexOf { _._1 == name }) match { case -1 => None case index => Some((scope drop index).foldLeft(0){ _ + _._2 }) } def wCallPrelude = { println("call prelude") // push base pointer w(MOVE_FP_A) w(I_STORE_A_SP) w(MOVE_SP_FP) w(INC_SP_INT) // push (program address+13) // so it will return to the instruction right after the GOTO w(I_CONST_A, out.length + 12) w(I_STORE_A_SP) w(INC_SP_INT) } def wGoto(ref:String) { refs += (out.length -> ref) w(GOTO, 0) // the 0 will be replaced in resolveGotos } def wDefPostlude(rtSize:Int) = { println("def postlude") // decrement SP to point at return value for(i <- (1 to (rtSize / 4))) w(DEC_SP_INT) for(i <- (1 to (rtSize % 4))) w(DEC_SP) // dec sp to return address w(DEC_SP_INT) // goto return address w(GOTO_SP) } def wCallPostlude(argSize:Int, rtSize:Int) = { println("call postlude") // dec sp to stored fp w(DEC_SP_INT) // load stored fp into fp w(I_LOAD_SP_FP) // dec sp past args w(DEC_SP_BY, argSize) // push answer (still in a) if(rtSize == 4) wPushInt else if(rtSize == 1) wPushByte else if(rtSize == 0) () else throw new IllegalArgumentException("rtSize must be either 1 or 4") // this should never be thrown... } def cmpOp(a:Expr, b:Expr, s:Scope, cmp:()=>Unit) = { println("cmpOp: a: " + a + " b: " + b + " s: " + s) - intOpNoPush(a, b, s, () => { println("hello from cmpOp's anon func"); w(I_SUB); cmp(); }) + intOpNoPush(a, b, s, () => { println("hello from cmpOp's anon func"); w(I_SUB); cmp(); wPushByte() }) } def intOp(a:Expr, b:Expr, s:Scope, ops:()=>Unit) = { intOpNoPush(a, b, s, ops) wPushInt } def intOpNoPush(a:Expr, b:Expr, s:Scope, ops:()=>Unit) = { println("intOpNoPush a: " + a + " b: " + b + " s: " + s) wExpr(a, s) wExpr(b, s) wPopIntB wPopIntA ops() } def byteOp(a:Expr, b:Expr, s:Scope, ops:()=>Unit) = { println(" byteOp: a: " + a + " b: " + b + " s: " + s) byteOpNoPush(a, b, s, ops) wPushByte } def byteOpNoPush(a:Expr, b:Expr, s:Scope, ops:()=>Unit) = { println("byteOpNoPush: a: " + a + " b: " + b + " s: " + s) wExpr(a, s) wExpr(b, s) wPopByteB wPopByteA ops() } def wPopIntA = { w(DEC_SP_INT); w(I_LOAD_SP_A) } def wPopIntB = { w(DEC_SP_INT); w(I_LOAD_SP_B) } def wPushInt = { w(I_STORE_A_SP); w(INC_SP_INT) } def wPopByteA = { w(DEC_SP); w(B_LOAD_SP_A) } def wPopByteB = { w(DEC_SP); w(B_LOAD_SP_B) } def wPushByte() = { w(B_STORE_A_SP); w(INC_SP) } def w(oc:Opcodes):Unit = { println(" " + oc); out += oc.toByte } def w(oc:Opcodes, arg:Int):Unit = { w(oc); wInt(arg) } def w(oc:Opcodes, arg:Float):Unit = { w(oc); wInt(java.lang.Float.floatToIntBits(arg)) } def w(oc:Opcodes, arg:Byte):Unit = { w(oc); out += arg } def wInt(i:Int) = { out += (0xff & (i >> 24)).asInstanceOf[Byte] out += (0xff & (i >> 16)).asInstanceOf[Byte] out += (0xff & (i >> 8)).asInstanceOf[Byte] out += (0xff & i).asInstanceOf[Byte] } def overWriteInt(addr:Int, i:Int) = { out(addr ) = (0xff & (i >> 24)).asInstanceOf[Byte] out(addr+1) = (0xff & (i >> 16)).asInstanceOf[Byte] out(addr+2) = (0xff & (i >> 8)).asInstanceOf[Byte] out(addr+3) = (0xff & i).asInstanceOf[Byte] } }
vilterp/VMLang
2b0f8e3c366772f0dcfa92a566000b2098e8352d
FINALLY got the factorial function to compile. recursion works. ors and ands don't, but this is major progress
diff --git a/bugs.txt b/bugs.txt index 4afacdd..5b7122d 100644 --- a/bugs.txt +++ b/bugs.txt @@ -1,27 +1,25 @@ COMPILER Overall - what about overloading (typeclasses, abstract classes, oh my!) - doesn't give error if user tries to define "true" or any other root function Parser - can't parse floats or chars - use RegexParsers to make custom scanner - error messages will be hard - give location info to tokens, if possible - maybe use scala.io.Source (has fromString method) - then use custom scanner in existing parser - unary "not"s aren't parsed right Linearizer - - function calls don't work - if statements aren't implemented - uses Type#size to compute instructions, but defs that take parameters with abstract types don't know what they will be called with! this computation must take place on a per-call basis, when argument types are known (note this makes CheckedDef useless) -INTERACTIVE PROMPT +Simplifier -- can't define recursive functions, because it says the function you're defining doesn't exist - - fix: add function's type sig to env before checking + - turns definition of fac into IfExpr(Call(==,List(Call(n,List()), IntLit(1))),Call(==,List(Call(n,List()), IntLit(1))),Call(==,List(Call(n,List()), IntLit(1)))) \ No newline at end of file diff --git a/examples/fac.output b/examples/fac.output new file mode 100644 index 0000000..9ff7d83 --- /dev/null +++ b/examples/fac.output @@ -0,0 +1,130 @@ + STACK_START + MOVE_A_SP + MOVE_A_FP +wExpr: Call(main,List()) s: List() +call prelude + MOVE_FP_A + I_STORE_A_SP + MOVE_SP_FP + INC_SP_INT + I_CONST_A + I_STORE_A_SP + INC_SP_INT + GOTO +call postlude + DEC_SP_INT + I_LOAD_SP_FP + DEC_SP_BY + STOP +wExpr: Call(printInt,List(Call(fac,List(IntLit(5))))) s: List() +wExpr: Call(fac,List(IntLit(5))) s: List() +wExpr: IntLit(5) s: List() + I_CONST_A + I_STORE_A_SP + INC_SP_INT +call prelude + MOVE_FP_A + I_STORE_A_SP + MOVE_SP_FP + INC_SP_INT + I_CONST_A + I_STORE_A_SP + INC_SP_INT + GOTO +call postlude + DEC_SP_INT + I_LOAD_SP_FP + DEC_SP_BY + I_STORE_A_SP + INC_SP_INT + DEC_SP_INT + I_LOAD_SP_A + PRINT_INT_A +def postlude + DEC_SP_INT + GOTO_SP +wExpr: IfExpr(Call(==,List(Call(n,List()), IntLit(1))),IntLit(1),Call(*,List(Call(n,List()), Call(fac,List(Call(-,List(Call(n,List()), IntLit(1)))))))) s: List((n,4)) +wExpr: Call(==,List(Call(n,List()), IntLit(1))) s: List((n,4)) +cmpOp: a: Call(n,List()) b: IntLit(1) s: List((n,4)) +intOpNoPush a: Call(n,List()) b: IntLit(1) s: List((n,4)) +wExpr: Call(n,List()) s: List((n,4)) + MOVE_FP_A + I_CONST_B + I_SUB + I_LOAD_A_A + I_STORE_A_SP + INC_SP_INT +wExpr: IntLit(1) s: List((n,4)) + I_CONST_A + I_STORE_A_SP + INC_SP_INT + DEC_SP_INT + I_LOAD_SP_B + DEC_SP_INT + I_LOAD_SP_A +hello from cmpOp's anon func + I_SUB +hello from =='s anon func + EQ_A + GOTO_IF_NOT_A +wExpr: IntLit(1) s: List((n,4)) + I_CONST_A + I_STORE_A_SP + INC_SP_INT + GOTO +wExpr: Call(*,List(Call(n,List()), Call(fac,List(Call(-,List(Call(n,List()), IntLit(1))))))) s: List((n,4)) +intOpNoPush a: Call(n,List()) b: Call(fac,List(Call(-,List(Call(n,List()), IntLit(1))))) s: List((n,4)) +wExpr: Call(n,List()) s: List((n,4)) + MOVE_FP_A + I_CONST_B + I_SUB + I_LOAD_A_A + I_STORE_A_SP + INC_SP_INT +wExpr: Call(fac,List(Call(-,List(Call(n,List()), IntLit(1))))) s: List((n,4)) +wExpr: Call(-,List(Call(n,List()), IntLit(1))) s: List((n,4)) +intOpNoPush a: Call(n,List()) b: IntLit(1) s: List((n,4)) +wExpr: Call(n,List()) s: List((n,4)) + MOVE_FP_A + I_CONST_B + I_SUB + I_LOAD_A_A + I_STORE_A_SP + INC_SP_INT +wExpr: IntLit(1) s: List((n,4)) + I_CONST_A + I_STORE_A_SP + INC_SP_INT + DEC_SP_INT + I_LOAD_SP_B + DEC_SP_INT + I_LOAD_SP_A + I_SUB + I_STORE_A_SP + INC_SP_INT +call prelude + MOVE_FP_A + I_STORE_A_SP + MOVE_SP_FP + INC_SP_INT + I_CONST_A + I_STORE_A_SP + INC_SP_INT + GOTO +call postlude + DEC_SP_INT + I_LOAD_SP_FP + DEC_SP_BY + I_STORE_A_SP + INC_SP_INT + DEC_SP_INT + I_LOAD_SP_B + DEC_SP_INT + I_LOAD_SP_A + I_MUL + I_STORE_A_SP + INC_SP_INT +def postlude + DEC_SP_INT + DEC_SP_INT + GOTO_SP diff --git a/examples/fac.vml b/examples/fac.vml new file mode 100644 index 0000000..09f58bf --- /dev/null +++ b/examples/fac.vml @@ -0,0 +1,2 @@ +main:Null = printInt(fac(12)) +fac(n:Int):Int = if n == 1 then 1 else n * fac(n-1) diff --git a/examples/fac.vmlbc b/examples/fac.vmlbc new file mode 100644 index 0000000..3c33235 --- /dev/null +++ b/examples/fac.vmlbc @@ -0,0 +1,100 @@ +0 STACK_START +1 MOVE_A_SP +2 MOVE_A_FP +3 MOVE_FP_A +4 I_STORE_A_SP +5 MOVE_SP_FP +6 INC_SP_INT +7 I_CONST_A 19 +12 I_STORE_A_SP +13 INC_SP_INT +14 GOTO 27 +19 DEC_SP_INT +20 I_LOAD_SP_FP +21 DEC_SP_BY 0 +26 STOP +27 I_CONST_A 5 +32 I_STORE_A_SP +33 INC_SP_INT +34 MOVE_FP_A +35 I_STORE_A_SP +36 MOVE_SP_FP +37 INC_SP_INT +38 I_CONST_A 50 +43 I_STORE_A_SP +44 INC_SP_INT +45 GOTO 64 +50 DEC_SP_INT +51 I_LOAD_SP_FP +52 DEC_SP_BY 4 +57 I_STORE_A_SP +58 INC_SP_INT +59 DEC_SP_INT +60 I_LOAD_SP_A +61 PRINT_INT_A +62 DEC_SP_INT +63 GOTO_SP +64 MOVE_FP_A +65 I_CONST_B 4 +70 I_SUB +71 I_LOAD_A_A +72 I_STORE_A_SP +73 INC_SP_INT +74 I_CONST_A 1 +79 I_STORE_A_SP +80 INC_SP_INT +81 DEC_SP_INT +82 I_LOAD_SP_B +83 DEC_SP_INT +84 I_LOAD_SP_A +85 I_SUB +86 GOTO_IF_NOT_A 103 +91 I_CONST_A 1 +96 I_STORE_A_SP +97 INC_SP_INT +98 GOTO 169 +103 MOVE_FP_A +104 I_CONST_B 4 +109 I_SUB +110 I_LOAD_A_A +111 I_STORE_A_SP +112 INC_SP_INT +113 MOVE_FP_A +114 I_CONST_B 4 +119 I_SUB +120 I_LOAD_A_A +121 I_STORE_A_SP +122 INC_SP_INT +123 I_CONST_A 1 +128 I_STORE_A_SP +129 INC_SP_INT +130 DEC_SP_INT +131 I_LOAD_SP_B +132 DEC_SP_INT +133 I_LOAD_SP_A +134 I_SUB +135 I_STORE_A_SP +136 INC_SP_INT +137 MOVE_FP_A +138 I_STORE_A_SP +139 MOVE_SP_FP +140 INC_SP_INT +141 I_CONST_A 153 +146 I_STORE_A_SP +147 INC_SP_INT +148 GOTO 64 +153 DEC_SP_INT +154 I_LOAD_SP_FP +155 DEC_SP_BY 4 +160 I_STORE_A_SP +161 INC_SP_INT +162 DEC_SP_INT +163 I_LOAD_SP_B +164 DEC_SP_INT +165 I_LOAD_SP_A +166 I_MUL +167 I_STORE_A_SP +168 INC_SP_INT +169 DEC_SP_INT +170 DEC_SP_INT +171 GOTO_SP diff --git a/examples/fac.vmlc b/examples/fac.vmlc new file mode 100644 index 0000000..b62eecb Binary files /dev/null and b/examples/fac.vmlc differ diff --git a/examples/fib.vmlc b/examples/fib.vmlc new file mode 100644 index 0000000..0846164 Binary files /dev/null and b/examples/fib.vmlc differ diff --git a/examples/test.vml b/examples/test.vml index 5750c02..b7741fd 100644 --- a/examples/test.vml +++ b/examples/test.vml @@ -1 +1,3 @@ -main:Null = printInt(2+3) +main:Null = printInt(add3(1,2,3)) +add(x:Int, y:Int):Int = x + y +add3(x:Int, y:Int, z:Int):Int = add(add(x,y),z) diff --git a/examples/test.vmlc b/examples/test.vmlc index 09e3a58..cdac340 100644 Binary files a/examples/test.vmlc and b/examples/test.vmlc differ diff --git a/src/vmlang/compiler/Compile.scala b/src/vmlang/compiler/Compile.scala index 066154d..712efb5 100644 --- a/src/vmlang/compiler/Compile.scala +++ b/src/vmlang/compiler/Compile.scala @@ -1,20 +1,20 @@ package vmlang.compiler import vmlang.compiler.typecheck.TypeCheck object Compile { def apply(prog:String):Array[Byte] = Linearize( - Simplify( +// Simplify( TypeCheck( MakeEnv( Parse(prog), TypeCheck.rootFuncTypes, TypeCheck.typeTree ) ) - ) +// ) ) } diff --git a/src/vmlang/compiler/Linearize.scala b/src/vmlang/compiler/Linearize.scala index acbf600..ccc77ff 100644 --- a/src/vmlang/compiler/Linearize.scala +++ b/src/vmlang/compiler/Linearize.scala @@ -1,209 +1,241 @@ package vmlang.compiler import collection.mutable.ArrayBuffer import collection.mutable.HashMap import vmlang.common.Opcodes import vmlang.common.Opcodes._ import vmlang.compiler.ast._ // shameful imperative code... object Linearize { def apply(e:Env):Array[Byte] = new Linearizer(e).run } class Linearizer(e:Env) { type Scope = List[(String, Int)] val out = new ArrayBuffer[Byte] val refs = new HashMap[Int,String] val startingPoints = new HashMap[String,Int] val rtSizes = Map[String,Int]() ++ (e.defs map { case (n, d) => (n, e.tt getSize d.returnType) }) val scopes = Map[String,Scope]() ++ (e.defs map { case (na, d) => (na, d.params map { case ParamSpec(n, at) => (n, e.tt.getSize(at)) } ) }) def run:Array[Byte] = { // initialize SP to stack start (given by command line argument) w(STACK_START) w(MOVE_A_SP) w(MOVE_A_FP) // write call to main wExpr(Call("main", Nil), Nil) w(STOP) // write definitions for((n, d) <- e.defs) { startingPoints += (n -> out.length) // write def body expr wExpr(d.body, scopes(n)) wDefPostlude(rtSizes(n)) } resolveGotos } def resolveGotos:Array[Byte] = { for((ind, ref) <- refs) { val refInd = startingPoints(ref) // write program index (integer) to result array - out(ind+1) = (0xff & (refInd >> 24)).asInstanceOf[Byte] - out(ind+2) = (0xff & (refInd >> 16)).asInstanceOf[Byte] - out(ind+3) = (0xff & (refInd >> 8)).asInstanceOf[Byte] - out(ind+4) = (0xff & refInd).asInstanceOf[Byte] + overWriteInt(ind + 1, refInd) } out.toArray } - def wExpr(e:Expr, s:Scope):Unit = e match { + def wExpr(e:Expr, s:Scope):Unit = { println("wExpr: " + e + " s: " + s); e match { case IntLit(i) => w(I_CONST_A, i); wPushInt case CharLit(c) => w(B_CONST_A, c.toByte); wPushByte case FloatLit(f) => w(I_CONST_A, java.lang.Float.floatToIntBits(f)); wPushInt case Call("+", List(a, b)) => intOp(a, b, s, ()=>{ w(I_ADD) }) case Call("-", List(a, b)) => intOp(a, b, s, ()=>{ w(I_SUB) }) case Call("*", List(a, b)) => intOp(a, b, s, ()=>{ w(I_MUL) }) case Call("/", List(a, b)) => intOp(a, b, s, ()=>{ w(I_DIV) }) case Call("%", List(a, b)) => intOp(a, b, s, ()=>{ w(I_MOD) }) - case Call("==", List(a, b)) => cmpOp(a, b, s, ()=>{ w(EQ_A) }) + case Call("==", List(a, b)) => cmpOp(a, b, s, ()=>{ println("hello from =='s anon func"); w(EQ_A); }) case Call(">" , List(a, b)) => cmpOp(a, b, s, ()=>{ w(GT_A) }) case Call("<" , List(a, b)) => cmpOp(a, b, s, ()=>{ w(LT_A) }) case Call(">=", List(a, b)) => cmpOp(a, b, s, ()=>{ w(LT_A); w(NEG_A) }) case Call("<=", List(a, b)) => cmpOp(a, b, s, ()=>{ w(GT_A); w(NEG_A) }) case Call("and", List(a, b)) => byteOp(a, b, s, ()=>{ w(AND) }) case Call("or" , List(a, b)) => byteOp(a, b, s, ()=>{ w(OR) }) case Call("not", List(a)) => wExpr(a, s); wPopByteA; w(NEG_A); wPushByte() case Call("true" , Nil) => w(B_CONST_A, 1:Byte); wPushByte case Call("false", Nil) => w(B_CONST_A, 0:Byte); wPushByte case Call("null" , Nil) => // do nothing case Call("printInt", List(a)) => wExpr(a, s); wPopIntA; w(PRINT_INT_A) case Call(name, args) => argOffset(name, s) match { case Some(offset) => // is parameter w(MOVE_FP_A) w(I_CONST_B, offset) w(I_SUB) w(I_LOAD_A_A) w(I_STORE_A_SP) w(INC_SP_INT) case None => // is call (args foreach { wExpr(_, s) }) wCallPrelude wGoto(name) wCallPostlude(scopes(name).foldLeft(0){ _ + _._2 }, rtSizes(name)) // retrieve returned value } - } + case IfExpr(c, i, e) => { + // write condition + wExpr(c, s) + // write conditional goto + val condGotoInd = out.length + w(GOTO_IF_NOT_A, 0) + // write if expr + wExpr(i, s) + // write goto to after end of else expr + val ifGotoInd = out.length + w(GOTO, 0) + // write else expr + wExpr(e, s) + val afterElseInd = out.length + // overwrite conditional goto addr + overWriteInt(condGotoInd + 1, ifGotoInd + 5) + // overwrite after-if goto addr + overWriteInt(ifGotoInd + 1, afterElseInd) + } + + } } def argOffset(name:String, scope:Scope):Option[Int] = (scope findIndexOf { _._1 == name }) match { case -1 => None case index => Some((scope drop index).foldLeft(0){ _ + _._2 }) } def wCallPrelude = { + println("call prelude") // push base pointer w(MOVE_FP_A) w(I_STORE_A_SP) w(MOVE_SP_FP) w(INC_SP_INT) // push (program address+13) // so it will return to the instruction right after the GOTO w(I_CONST_A, out.length + 12) w(I_STORE_A_SP) w(INC_SP_INT) } def wGoto(ref:String) { refs += (out.length -> ref) w(GOTO, 0) // the 0 will be replaced in resolveGotos } def wDefPostlude(rtSize:Int) = { + println("def postlude") // decrement SP to point at return value for(i <- (1 to (rtSize / 4))) w(DEC_SP_INT) for(i <- (1 to (rtSize % 4))) w(DEC_SP) // dec sp to return address w(DEC_SP_INT) // goto return address w(GOTO_SP) } def wCallPostlude(argSize:Int, rtSize:Int) = { + println("call postlude") // dec sp to stored fp w(DEC_SP_INT) // load stored fp into fp w(I_LOAD_SP_FP) // dec sp past args w(DEC_SP_BY, argSize) // push answer (still in a) if(rtSize == 4) wPushInt else if(rtSize == 1) wPushByte else if(rtSize == 0) () else throw new IllegalArgumentException("rtSize must be either 1 or 4") // this should never be thrown... } - def cmpOp(a:Expr, b:Expr, s:Scope, cmp:()=>Unit) = - intOp(a, b, s, { w(I_SUB); cmp(); wPushByte }) + def cmpOp(a:Expr, b:Expr, s:Scope, cmp:()=>Unit) = { + println("cmpOp: a: " + a + " b: " + b + " s: " + s) + intOpNoPush(a, b, s, () => { println("hello from cmpOp's anon func"); w(I_SUB); cmp(); }) + } def intOp(a:Expr, b:Expr, s:Scope, ops:()=>Unit) = { intOpNoPush(a, b, s, ops) wPushInt } def intOpNoPush(a:Expr, b:Expr, s:Scope, ops:()=>Unit) = { + println("intOpNoPush a: " + a + " b: " + b + " s: " + s) wExpr(a, s) wExpr(b, s) wPopIntB wPopIntA ops() } def byteOp(a:Expr, b:Expr, s:Scope, ops:()=>Unit) = { + println(" byteOp: a: " + a + " b: " + b + " s: " + s) byteOpNoPush(a, b, s, ops) wPushByte } def byteOpNoPush(a:Expr, b:Expr, s:Scope, ops:()=>Unit) = { + println("byteOpNoPush: a: " + a + " b: " + b + " s: " + s) wExpr(a, s) wExpr(b, s) wPopByteB wPopByteA ops() } def wPopIntA = { w(DEC_SP_INT); w(I_LOAD_SP_A) } - def wPopIntB = { w(DEC_SP_INT); w(I_LOAD_SP_A) } + def wPopIntB = { w(DEC_SP_INT); w(I_LOAD_SP_B) } def wPushInt = { w(I_STORE_A_SP); w(INC_SP_INT) } def wPopByteA = { w(DEC_SP); w(B_LOAD_SP_A) } def wPopByteB = { w(DEC_SP); w(B_LOAD_SP_B) } def wPushByte() = { w(B_STORE_A_SP); w(INC_SP) } - def w(oc:Opcodes):Unit = out += oc.toByte + def w(oc:Opcodes):Unit = { println(" " + oc); out += oc.toByte } def w(oc:Opcodes, arg:Int):Unit = { w(oc); wInt(arg) } def w(oc:Opcodes, arg:Float):Unit = { w(oc); wInt(java.lang.Float.floatToIntBits(arg)) } def w(oc:Opcodes, arg:Byte):Unit = { w(oc); out += arg } def wInt(i:Int) = { out += (0xff & (i >> 24)).asInstanceOf[Byte] out += (0xff & (i >> 16)).asInstanceOf[Byte] out += (0xff & (i >> 8)).asInstanceOf[Byte] out += (0xff & i).asInstanceOf[Byte] } + def overWriteInt(addr:Int, i:Int) = { + out(addr ) = (0xff & (i >> 24)).asInstanceOf[Byte] + out(addr+1) = (0xff & (i >> 16)).asInstanceOf[Byte] + out(addr+2) = (0xff & (i >> 8)).asInstanceOf[Byte] + out(addr+3) = (0xff & i).asInstanceOf[Byte] + } + } diff --git a/src/vmlang/repl/Main.scala b/src/vmlang/repl/Main.scala index 1d33e58..7335e16 100644 --- a/src/vmlang/repl/Main.scala +++ b/src/vmlang/repl/Main.scala @@ -1,62 +1,63 @@ package vmlang.repl import java.util.Scanner import vmlang.common.optparser._ import vmlang.compiler._ import vmlang.compiler.typecheck._ import vmlang.compiler.ast._ import vmlang.vm.{ VM, VMError } object Main extends OptParser { def numArgs(n:Int) = n == 0 val argErrorMsg = "run with no args for interactive prompt" val knownFlags = List("h") val defaultOpts = Map[String,String]() val help = "usage: vmli" def run(args:List[String], flags:List[String], opts:Map[String,String]):Unit = { flags match { case "h" :: fs => println(argErrorMsg) case Nil => runREPL } } def runREPL = { val s = new Scanner(System.in) var resCounter = 0 var env = Env(Map[String,Def](), TypeCheck.rootFuncTypes, TypeCheck.typeTree) while(true) { print(">> ") try { val input = s.nextLine if(input startsWith ":t ") { println(TypeCheck.inferType(Parse.parseExpr(input substring 3), env)) } else { Parse.parseREPLStmt(input) match { case e:Expr => env = env.addDef(Def("res" + resCounter, Nil, TypeCheck.inferType(e, env), e)) env = env.addDef(Def("main", Nil, TypeExpr("Null", Nil), Call("printInt",List(Call("res" + resCounter, Nil))))) + print("res" + resCounter + ": ") resCounter += 1 val code = Linearize(TypeCheck(env)) new VM(code, 1024, 1024, false).run case d:Def => val newEnv = env.addDef(d) env = TypeCheck.checkDef(d, newEnv) match { case Nil => newEnv case es => throw TypeErrors(es.removeDuplicates) } } } } catch { case e:CompilerError => println(e.repr) case e:VMError => println(e.getMessage) } } } }
vilterp/VMLang
a1f0b7b6645415c38500c08c8f6c8ee08661ca42
moved repl to separate package; FINALLY got function calls to compile, albiet with weird stuff going on with numbers
diff --git a/bugs.txt b/bugs.txt index c60dbcb..4afacdd 100644 --- a/bugs.txt +++ b/bugs.txt @@ -1,29 +1,27 @@ COMPILER Overall - what about overloading (typeclasses, abstract classes, oh my!) - doesn't give error if user tries to define "true" or any other root function Parser - can't parse floats or chars - use RegexParsers to make custom scanner - error messages will be hard - give location info to tokens, if possible - maybe use scala.io.Source (has fromString method) - then use custom scanner in existing parser - unary "not"s aren't parsed right Linearizer - function calls don't work - if statements aren't implemented - uses Type#size to compute instructions, but defs that take parameters with abstract types don't know what they will be called with! this computation must take place on a per-call basis, when argument types are known (note this makes CheckedDef useless) INTERACTIVE PROMPT -- ":t <expr>" doesn't take user-defined functions into account -- defining a function yields "No main function. (Must be () => Null)" -- ":t myFunction" should give myFunction's type signature, not parse it as an expression -- should save expressions typed in as "res{n}" +- can't define recursive functions, because it says the function you're defining doesn't exist + - fix: add function's type sig to env before checking diff --git a/build.xml b/build.xml index d5d4b7e..3a6d448 100644 --- a/build.xml +++ b/build.xml @@ -1,43 +1,47 @@ <?xml version="1.0" encoding="UTF-8"?> <project name="VMLang" default="compile_everything" basedir="."> <property name="base.dir" value="${basedir}" /> <property name="sources.dir" value="${base.dir}/src" /> <property name="build.dir" value="${base.dir}/bin" /> <!-- set up scala stuff --> <property name="scala.home" value="/Applications/scala-2.7.7"/> <property name="scala-library.jar" value="${scala.home}/lib/scala-library.jar"/> <path id="build.classpath"> <pathelement location="${scala-library.jar}"/> <pathelement location="${build.dir}"/> </path> <taskdef resource="scala/tools/ant/antlib.xml"> <classpath> <pathelement location="${scala.home}/lib/scala-compiler.jar"/> <pathelement location="${scala-library.jar}"/> </classpath> </taskdef> <!-- end scala setup --> <target name="compile_everything"> <antcall target="compile_vm"/> <antcall target="compile_compiler"/> </target> <target name="compile_vm"> <javac srcdir="${sources.dir}" destdir="${build.dir}" debug="true"/> </target> <target name="compile_compiler"> <scalac srcdir="${sources.dir}" destdir="${build.dir}" classpathref="build.classpath" scalacdebugging="true"> <include name="**/*.scala"/> <exclude name="**/*.java"/> </scalac> </target> + <target name="make_jar" depends="compile_everything"> + <jar basedir="${build.dir}" destfile="vmlang.jar"/> + </target> + </project> diff --git a/examples/test.vmlc b/examples/test.vmlc index 9c7d118..09e3a58 100644 Binary files a/examples/test.vmlc and b/examples/test.vmlc differ diff --git a/src/vmlang/common/Opcodes.java b/src/vmlang/common/Opcodes.java index ee84580..f7dbe68 100644 --- a/src/vmlang/common/Opcodes.java +++ b/src/vmlang/common/Opcodes.java @@ -1,122 +1,124 @@ package vmlang.common; /* I_LOAD_SP_A: A = memReadInt(SP) I_STORE_A_SP: memWriteInt(SP,A) MOVE_A_B: B = A */ public enum Opcodes { STOP, GOTO, GOTO_A, GOTO_SP, GOTO_IF_NOT_A, I_CONST_A, I_CONST_B, B_CONST_A, B_CONST_B, I_LOAD_A_B, I_LOAD_A_SP, I_LOAD_A_FP, + I_LOAD_A_A, I_LOAD_B_A, I_LOAD_B_SP, I_LOAD_B_FP, I_LOAD_SP_A, I_LOAD_SP_B, I_LOAD_SP_FP, I_LOAD_FP_A, I_LOAD_FP_B, I_LOAD_FP_SP, B_LOAD_A_B, B_LOAD_A_SP, B_LOAD_A_FP, B_LOAD_B_A, B_LOAD_B_SP, B_LOAD_B_FP, B_LOAD_SP_A, B_LOAD_SP_B, B_LOAD_SP_FP, B_LOAD_FP_A, B_LOAD_FP_B, B_LOAD_FP_SP, I_STORE_A_B, I_STORE_A_SP, I_STORE_A_FP, I_STORE_B_A, I_STORE_B_SP, I_STORE_B_FP, I_STORE_SP_A, I_STORE_SP_B, I_STORE_SP_FP, I_STORE_FP_A, I_STORE_FP_B, I_STORE_FP_SP, B_STORE_A_B, B_STORE_A_SP, B_STORE_A_FP, B_STORE_B_A, B_STORE_B_SP, B_STORE_B_FP, B_STORE_SP_A, B_STORE_SP_B, B_STORE_SP_FP, B_STORE_FP_A, B_STORE_FP_B, B_STORE_FP_SP, MOVE_COUNTER_A, MOVE_A_B, MOVE_A_SP, MOVE_A_FP, MOVE_B_A, MOVE_B_SP, MOVE_B_FP, MOVE_SP_A, MOVE_SP_B, MOVE_SP_FP, MOVE_FP_A, MOVE_FP_B, MOVE_FP_SP, I_ADD, I_SUB, I_MUL, I_DIV, I_MOD, F_ADD, F_SUB, F_MUL, F_DIV, F_MOD, INC_A, INC_B, INC_SP, INC_SP_INT, DEC_A, DEC_B, DEC_SP, DEC_SP_INT, + DEC_SP_BY, NEG_A, EQ_A, LT_A, GT_A, AND, OR, PRINT_CHAR_A, PRINT_INT_A, READ_CHAR_A, STACK_START; public byte toByte() { return (byte)ordinal(); } } diff --git a/src/vmlang/compiler/Env.scala b/src/vmlang/compiler/Env.scala index bdc7abf..87c657c 100644 --- a/src/vmlang/compiler/Env.scala +++ b/src/vmlang/compiler/Env.scala @@ -1,48 +1,52 @@ package vmlang.compiler import vmlang.compiler.ast.{ Def, TypeExpr } import vmlang.compiler.typecheck._ case class Env(defs:Map[String,Def], roots:Map[String,TypeExpr], tt:TypeTree) { lazy val ft = defs.foldLeft(roots){ (ft, d) => ft + (d._2.name -> d._2.typeExpr) } // for REPL only - def addDef(d:Def) = Env(defs + (d.name -> d), roots, tt) + def addDef(d:Def) = + if(roots contains d.name) + throw RootDefError(d.name) + else + Env(defs + (d.name -> d), roots, tt) } object MakeEnv { def apply(defs:List[Def], roots:Map[String,TypeExpr], tt:TypeTree):Env = (checkForDuplicates(defs) ::: checkForRoots(defs, roots)) match { case Nil => Env(Map[String,Def]() ++ (defs map { d => (d.name, d) }), roots, tt) case es => throw TypeErrors(es) } def checkForRoots(defs:List[Def], roots:Map[String,TypeExpr]):List[TypeError] = defs match { case Nil => Nil case first :: rest => if(roots contains first.name) RootDefError(first.name) :: checkForRoots(rest, roots) else checkForRoots(rest, roots) } def checkForDuplicates(defs:List[Def]):List[TypeError] = checkForDuplicates(Nil, defs) map { d => DuplicateDefError(d.name) } def checkForDuplicates(alreadyDefined:List[Def], defs:List[Def]):List[Def] = defs match { case Nil => Nil case first :: rest => { if(alreadyDefined exists { _.name == first.name }) first :: checkForDuplicates(alreadyDefined, rest) else checkForDuplicates(first :: alreadyDefined, rest) } } } diff --git a/src/vmlang/compiler/Linearize.scala b/src/vmlang/compiler/Linearize.scala index 9928ff2..acbf600 100644 --- a/src/vmlang/compiler/Linearize.scala +++ b/src/vmlang/compiler/Linearize.scala @@ -1,203 +1,209 @@ package vmlang.compiler -import java.io.{DataOutputStream, ByteArrayOutputStream} +import collection.mutable.ArrayBuffer import collection.mutable.HashMap - import vmlang.common.Opcodes import vmlang.common.Opcodes._ import vmlang.compiler.ast._ // shameful imperative code... object Linearize { def apply(e:Env):Array[Byte] = - null + new Linearizer(e).run + +} + +class Linearizer(e:Env) { + + type Scope = List[(String, Int)] + + val out = new ArrayBuffer[Byte] + val refs = new HashMap[Int,String] + val startingPoints = new HashMap[String,Int] + val rtSizes = Map[String,Int]() ++ (e.defs map { case (n, d) => (n, e.tt getSize d.returnType) }) + val scopes = Map[String,Scope]() ++ (e.defs map { case (na, d) => (na, d.params map { + case ParamSpec(n, at) => (n, e.tt.getSize(at)) } ) }) + + def run:Array[Byte] = { + // initialize SP to stack start (given by command line argument) + w(STACK_START) + w(MOVE_A_SP) + w(MOVE_A_FP) + // write call to main + wExpr(Call("main", Nil), Nil) + w(STOP) + // write definitions + for((n, d) <- e.defs) { + startingPoints += (n -> out.length) + // write def body expr + wExpr(d.body, scopes(n)) + wDefPostlude(rtSizes(n)) + } + resolveGotos + } + + def resolveGotos:Array[Byte] = { + for((ind, ref) <- refs) { + val refInd = startingPoints(ref) + // write program index (integer) to result array + out(ind+1) = (0xff & (refInd >> 24)).asInstanceOf[Byte] + out(ind+2) = (0xff & (refInd >> 16)).asInstanceOf[Byte] + out(ind+3) = (0xff & (refInd >> 8)).asInstanceOf[Byte] + out(ind+4) = (0xff & refInd).asInstanceOf[Byte] + } + out.toArray + } + + def wExpr(e:Expr, s:Scope):Unit = e match { + + case IntLit(i) => w(I_CONST_A, i); wPushInt + case CharLit(c) => w(B_CONST_A, c.toByte); wPushByte + case FloatLit(f) => w(I_CONST_A, java.lang.Float.floatToIntBits(f)); wPushInt + + case Call("+", List(a, b)) => intOp(a, b, s, ()=>{ w(I_ADD) }) + case Call("-", List(a, b)) => intOp(a, b, s, ()=>{ w(I_SUB) }) + case Call("*", List(a, b)) => intOp(a, b, s, ()=>{ w(I_MUL) }) + case Call("/", List(a, b)) => intOp(a, b, s, ()=>{ w(I_DIV) }) + case Call("%", List(a, b)) => intOp(a, b, s, ()=>{ w(I_MOD) }) + + case Call("==", List(a, b)) => cmpOp(a, b, s, ()=>{ w(EQ_A) }) + case Call(">" , List(a, b)) => cmpOp(a, b, s, ()=>{ w(GT_A) }) + case Call("<" , List(a, b)) => cmpOp(a, b, s, ()=>{ w(LT_A) }) + case Call(">=", List(a, b)) => cmpOp(a, b, s, ()=>{ w(LT_A); w(NEG_A) }) + case Call("<=", List(a, b)) => cmpOp(a, b, s, ()=>{ w(GT_A); w(NEG_A) }) + + case Call("and", List(a, b)) => byteOp(a, b, s, ()=>{ w(AND) }) + case Call("or" , List(a, b)) => byteOp(a, b, s, ()=>{ w(OR) }) + case Call("not", List(a)) => wExpr(a, s); wPopByteA; w(NEG_A); wPushByte() + + case Call("true" , Nil) => w(B_CONST_A, 1:Byte); wPushByte + case Call("false", Nil) => w(B_CONST_A, 0:Byte); wPushByte + case Call("null" , Nil) => // do nothing + + case Call("printInt", List(a)) => wExpr(a, s); wPopIntA; w(PRINT_INT_A) + + case Call(name, args) => argOffset(name, s) match { + case Some(offset) => // is parameter + w(MOVE_FP_A) + w(I_CONST_B, offset) + w(I_SUB) + w(I_LOAD_A_A) + w(I_STORE_A_SP) + w(INC_SP_INT) + case None => // is call + (args foreach { wExpr(_, s) }) + wCallPrelude + wGoto(name) + wCallPostlude(scopes(name).foldLeft(0){ _ + _._2 }, rtSizes(name)) // retrieve returned value + } + + } + + def argOffset(name:String, scope:Scope):Option[Int] = + (scope findIndexOf { _._1 == name }) match { + case -1 => None + case index => Some((scope drop index).foldLeft(0){ _ + _._2 }) + } + + def wCallPrelude = { + // push base pointer + w(MOVE_FP_A) + w(I_STORE_A_SP) + w(MOVE_SP_FP) + w(INC_SP_INT) + // push (program address+13) + // so it will return to the instruction right after the GOTO + w(I_CONST_A, out.length + 12) + w(I_STORE_A_SP) + w(INC_SP_INT) + } + + def wGoto(ref:String) { + refs += (out.length -> ref) + w(GOTO, 0) // the 0 will be replaced in resolveGotos + } + + def wDefPostlude(rtSize:Int) = { + // decrement SP to point at return value + for(i <- (1 to (rtSize / 4))) + w(DEC_SP_INT) + for(i <- (1 to (rtSize % 4))) + w(DEC_SP) + // dec sp to return address + w(DEC_SP_INT) + // goto return address + w(GOTO_SP) + } + + def wCallPostlude(argSize:Int, rtSize:Int) = { + // dec sp to stored fp + w(DEC_SP_INT) + // load stored fp into fp + w(I_LOAD_SP_FP) + // dec sp past args + w(DEC_SP_BY, argSize) + // push answer (still in a) + if(rtSize == 4) + wPushInt + else if(rtSize == 1) + wPushByte + else if(rtSize == 0) + () + else + throw new IllegalArgumentException("rtSize must be either 1 or 4") + // this should never be thrown... + } + + def cmpOp(a:Expr, b:Expr, s:Scope, cmp:()=>Unit) = + intOp(a, b, s, { w(I_SUB); cmp(); wPushByte }) + + def intOp(a:Expr, b:Expr, s:Scope, ops:()=>Unit) = { + intOpNoPush(a, b, s, ops) + wPushInt + } + + def intOpNoPush(a:Expr, b:Expr, s:Scope, ops:()=>Unit) = { + wExpr(a, s) + wExpr(b, s) + wPopIntB + wPopIntA + ops() + } + + def byteOp(a:Expr, b:Expr, s:Scope, ops:()=>Unit) = { + byteOpNoPush(a, b, s, ops) + wPushByte + } + + def byteOpNoPush(a:Expr, b:Expr, s:Scope, ops:()=>Unit) = { + wExpr(a, s) + wExpr(b, s) + wPopByteB + wPopByteA + ops() + } + + def wPopIntA = { w(DEC_SP_INT); w(I_LOAD_SP_A) } + def wPopIntB = { w(DEC_SP_INT); w(I_LOAD_SP_A) } + def wPushInt = { w(I_STORE_A_SP); w(INC_SP_INT) } + + def wPopByteA = { w(DEC_SP); w(B_LOAD_SP_A) } + def wPopByteB = { w(DEC_SP); w(B_LOAD_SP_B) } + def wPushByte() = { w(B_STORE_A_SP); w(INC_SP) } + + def w(oc:Opcodes):Unit = out += oc.toByte + def w(oc:Opcodes, arg:Int):Unit = { w(oc); wInt(arg) } + def w(oc:Opcodes, arg:Float):Unit = { w(oc); wInt(java.lang.Float.floatToIntBits(arg)) } + def w(oc:Opcodes, arg:Byte):Unit = { w(oc); out += arg } + + def wInt(i:Int) = { + out += (0xff & (i >> 24)).asInstanceOf[Byte] + out += (0xff & (i >> 16)).asInstanceOf[Byte] + out += (0xff & (i >> 8)).asInstanceOf[Byte] + out += (0xff & i).asInstanceOf[Byte] + } } -// -// class Linearizer(defs:List[Def], tt:TypeTree, ft:Map[String,TypeExpr]) { -// -// type Scope = List[(String, TypeExpr)] -// -// val baos = new ByteArrayOutputStream -// val out = new DataOutputStream(baos) -// val refs = new HashMap[Int,String] -// val startingPoints = new HashMap[String,Int] -// -// val rtSizes = Map[String,Int]() ++ (defs map { d => (d.name, tt getSize d.returnType) }) -// val scopes = Map[String,Int]() ++ -// (defs map { d => (d.name, d.params map { p => (p.name, tt getSize p.argType) }) }) -// -// def run:Array[Byte] = { -// wExpr(Call("main", Nil), Nil) -// w(STOP) -// for((n, d) <- defs) { -// startingPoints += (n -> out.size) -// // write def body expr -// val scope = scopes(n) -// wExpr(d.body, scope) -// wDefPostlude(scope.foldLeft(0){ _ + _._2 }, rtSizes(n)) -// } -// resolveGotos -// } -// -// def resolveGotos:Array[Byte] = { -// val result = baos.toByteArray -// for((ind, ref) <- refs) { -// val refInd = startingPoints(ref) -// // write program index (integer) to result array -// result(ind+1) = (0xff & (refInd << 24)).asInstanceOf[Byte] -// result(ind+2) = (0xff & (refInd << 16)).asInstanceOf[Byte] -// result(ind+3) = (0xff & (refInd << 8)).asInstanceOf[Byte] -// result(ind+4) = (0xff & refInd).asInstanceOf[Byte] -// } -// result -// } -// -// def wExpr(e:Expr, s:Scope):Unit = e match { -// -// case IntLit(i) => w(I_CONST_A, i); w(I_STORE_A_SP); w(INC_SP_INT) -// case CharLit(c) => w(B_CONST_A, c.toByte); w(B_STORE_A_SP); w(INC_SP) -// case FloatLit(f) => w(I_CONST_A, java.lang.Float.floatToIntBits(f)); w(I_STORE_A_SP); w(INC_SP_INT) -// -// case Call("+", List(a, b)) => intOp(a, b, s, ()=>{ w(I_ADD) }) -// case Call("-", List(a, b)) => intOp(a, b, s, ()=>{ w(I_SUB) }) -// case Call("*", List(a, b)) => intOp(a, b, s, ()=>{ w(I_MUL) }) -// case Call("/", List(a, b)) => intOp(a, b, s, ()=>{ w(I_DIV) }) -// case Call("%", List(a, b)) => intOp(a, b, s, ()=>{ w(I_MOD) }) -// -// case Call("==", List(a, b)) => cmpOp(a, b, s, ()=>{ w(EQ_A) }) -// case Call(">" , List(a, b)) => cmpOp(a, b, s, ()=>{ w(GT_A) }) -// case Call("<" , List(a, b)) => cmpOp(a, b, s, ()=>{ w(LT_A) }) -// case Call(">=", List(a, b)) => cmpOp(a, b, s, ()=>{ w(LT_A); w(NEG_A) }) -// case Call("<=", List(a, b)) => cmpOp(a, b, s, ()=>{ w(GT_A); w(NEG_A) }) -// -// case Call("and", List(a, b)) => byteOp(a, b, s, ()=>{ w(AND) }) -// case Call("or" , List(a, b)) => byteOp(a, b, s, ()=>{ w(OR) }) -// case Call("not", List(a)) => wExpr(a, s); wPopByteA; w(NEG_A); wPushByte() -// -// case Call("true" , Nil) => w(B_CONST_A, 1:Byte); wPushByte -// case Call("false", Nil) => w(B_CONST_A, 0:Byte); wPushByte -// case Call("null" , Nil) => // do nothing -// -// case Call("printInt", List(a)) => wExpr(a, s); wPopIntA; w(PRINT_INT_A) -// -// case Call(name, args) => argOffset(name, s) match { -// case Some(offset) => // is parameter -// w(MOVE_FP_A) -// w(I_CONST_B, offset) -// w(I_SUB) -// w(I_LOAD_A_A) -// w(I_STORE_A_SP) -// w(INC_SP_INT) -// case None => // is call -// (args foreach { wExpr(_, s) }) -// wCallPrelude -// wGoto(name) -// wCallPostlude(scopes(name).foldLeft(0){ _ + _._2 }) // retrieve returned value -// } -// -// } -// -// def argOffset(name:String, scope:Scope):Option[Int] = -// (scope findIndexOf { _._1 == name }) match { -// case -1 => None -// case index => Some((scope drop index).foldLeft(0){ _ + _._2 }) -// } -// -// def wCallPrelude = { -// // push base pointer -// w(MOVE_FP_A) -// w(I_STORE_A_SP) -// w(MOVE_SP_FP) -// w(INC_SP_INT) -// // push (program address+13) -// // so it will return to the instruction right after the GOTO -// w(MOVE_COUNTER_A) -// w(I_CONST_B, 13) -// w(I_ADD) -// w(I_STORE_A_SP) -// w(INC_SP_INT) -// } -// -// def wGoto(ref:String) { -// refs += (out.size -> ref) -// w(GOTO, 0) // the 0 will be replaced in resolveGotos -// } -// -// def wDefPostlude(paramSize:Int, rtSize:Int) = { -// // decrement SP to point at return value -// for(i <- (1 to (rtSize / 4))) -// w(DEC_SP_INT) -// for(i <- (1 to (rtSize % 4))) -// w(DEC_SP) -// // store answer on calling function's operand stack -// w(MOVE_FP_A) -// w(I_CONST_B, paramSize) // !!! what about functions w/ no params?! -// w(I_SUB) -// w(MOVE_A_B) -// w(I_LOAD_A_SP) -// w(I_STORE_A_B) -// // set FP to saved FP (on stack) -// w(DEC_SP_INT) -// w(DEC_SP_INT) -// w(I_LOAD_FP_SP) // load the value at addr SP into FP -// // goto return address (on stack) -// w(INC_SP_INT) -// w(I_LOAD_A_SP) -// w(GOTO_A) -// } -// -// def getSize(e:Expr) = -// tt.getSize(TypeCheck.inferType(e, tt, allFuncs)) -// -// def wCallPostlude(paramSize:Int, rtSize:Int) = { -// w(MOVE_SP_A) -// w(I_CONST_B, 4 + (paramSize - rtSize)) -// w(I_SUB) -// w(MOVE_A_SP) -// } -// -// def cmpOp(a:Expr, b:Expr, s:Scope, cmp:()=>Unit) = -// intOp(a, b, s, { w(I_SUB); cmp(); wPushByte }) -// -// def intOp(a:Expr, b:Expr, s:Scope, ops:()=>Unit) = { -// intOpNoPush(a, b, s, ops) -// wPushInt -// } -// def intOpNoPush(a:Expr, b:Expr, s:Scope, ops:()=>Unit) = { -// wExpr(a, s) -// wExpr(b, s) -// wPopIntB -// wPopIntA -// ops() -// } -// -// def byteOp(a:Expr, b:Expr, s:Scope, ops:()=>Unit) = { -// byteOpNoPush(a, b, s, ops) -// wPushByte -// } -// def byteOpNoPush(a:Expr, b:Expr, s:Scope, ops:()=>Unit) = { -// wExpr(a, s) -// wExpr(b, s) -// wPopByteB -// wPopByteA -// ops() -// } -// -// def wPopIntA = { w(DEC_SP_INT); w(I_LOAD_A_SP) } -// def wPopIntB = { w(DEC_SP_INT); w(I_LOAD_B_SP) } -// def wPushInt = { w(I_STORE_A_SP); w(INC_SP_INT) } -// -// def wPopByteA = { w(DEC_SP); w(B_LOAD_A_SP) } -// def wPopByteB = { w(DEC_SP); w(B_LOAD_B_SP) } -// def wPushByte() = { w(DEC_SP); w(B_STORE_A_SP); } -// -// def w(oc:Opcodes):Unit = out.write(oc.toByte) -// def w(oc:Opcodes, arg:Int):Unit = { w(oc); out.writeInt(arg) } -// def w(oc:Opcodes, arg:Float):Unit = { w(oc); out.writeFloat(arg) } -// def w(oc:Opcodes, arg:Byte):Unit = { w(oc); out.writeByte(arg) } -// -// } diff --git a/src/vmlang/compiler/Main.scala b/src/vmlang/compiler/Main.scala index 490a593..53f2222 100644 --- a/src/vmlang/compiler/Main.scala +++ b/src/vmlang/compiler/Main.scala @@ -1,63 +1,20 @@ package vmlang.compiler import vmlang.common.optparser._ -import vmlang.compiler.typecheck.TypeCheck -import vmlang.compiler.ast._ -import vmlang.vm.{VM, VMError} - -import java.util.Scanner - -import collection.mutable.HashMap - object Main extends OptParser { - def numArgs(n:Int) = n == 0 || n == 1 - val argErrorMsg = "supply 1 file to compile, or no argument for interactive prompt" - val knownFlags = List("v") + def numArgs(n:Int) = n == 1 + val argErrorMsg = "supply 1 file to compile" + val knownFlags = List() val defaultOpts = Map[String,String]() - val help = "usage: vmlc <optional source file> <options>\n" + - "-v print out messages about what the compiler is doing" + val help = "usage: vmlc <source file> <options>" def run(args:List[String], flags:List[String], opts:Map[String,String]):Unit = - args match { - case Nil => runREPL - case List(fn) => - try { - writeFile(Compile(loadFile(fn)), ( fn split '.')(0) + ".vmlc") - } catch { - case e:CompilerError => throw FatalError(e.repr) - } - } - - def runREPL = { - val s = new Scanner(System.in) - var resCounter = 0 - var env = Env(Map[String,Def](), TypeCheck.rootFuncTypes, TypeCheck.typeTree) - while(true) { - print(">> ") try { - val input = s.nextLine - if(input startsWith ":t ") { - println(TypeCheck.inferType(Parse.parseExpr(input substring 3), env)) - } else { - Parse.parseREPLStmt(input) match { - case e:Expr => - env = env.addDef(Def("res" + resCounter, Nil, TypeCheck.inferType(e, env), e)) - env = env.addDef(Def("main", Nil, TypeExpr("Null", Nil), - Call("printInt",List(Call("res" + resCounter, Nil))))) - resCounter += 1 - val code = Linearize(Simplify(TypeCheck(env))) - new VM(code, 1024, 1024).run - case d:Def => - env = env.addDef(d) - } - } + writeFile(Compile(loadFile(args.head)), (args.head split '.')(0) + ".vmlc") } catch { - case e:CompilerError => println(e.repr) - case e:VMError => println(e.getMessage) + case e:CompilerError => throw FatalError(e.repr) } - } - } } diff --git a/src/vmlang/compiler/Simplify.scala b/src/vmlang/compiler/Simplify.scala index 4bb4e8d..4d7201e 100644 --- a/src/vmlang/compiler/Simplify.scala +++ b/src/vmlang/compiler/Simplify.scala @@ -1,75 +1,77 @@ package vmlang.compiler import vmlang.compiler.ast._ import collection.Set object Simplify { type DefMap = Map[String,Def] type FuncTable = Map[String,TypeExpr] def apply(env:Env):Env = - Env(inlineAll(simplifyAll(env.defs), Set() ++ env.ft.keySet.toList -- env.defs.keySet.toList), - env.ft, env.tt) + Env(inlineAll(simplifyAll(env.defs), Set() ++ env.roots.keySet.toList -- env.defs.keySet.toList), + env.roots, env.tt) def simplifyAll(defs:DefMap) = - applyToAllDefs(defs, simplify _) + applyToAllDefs(defs, { d => simplify(d.body) }) def inlineAll(defs:DefMap, rootNames:Set[String]) = Map[String,Def]() ++ - (applyToAllDefs(defs, { e => inline(e,defs,rootNames) }) filter { + (applyToAllDefs(defs, { d => inline(d.body,d.params map { ps => ps.name },defs,rootNames) }) filter { case (_, d) => !d.body.isInstanceOf[Atom] }) - def applyToAllDefs(defs:DefMap, f:(Expr) => Expr):DefMap = - Map[String,Def]() ++ (defs map { case (na, Def(n, ps, rt, b)) => (na, Def(n, ps, rt, f(b))) }) + def applyToAllDefs(defs:DefMap, f:(Def) => Expr):DefMap = + Map[String,Def]() ++ (defs map { case (na, d:Def) => + (na, Def(d.name, d.params, d.returnType, f(d))) }) - def inline(e:Expr, defs:DefMap, rootNames:Set[String]):Expr = + def inline(e:Expr, s:List[String], defs:DefMap, rootNames:Set[String]):Expr = e match { case a:Atom => a case IfExpr(c, i, e) => - IfExpr(inline(c, defs, rootNames), inline(c, defs, rootNames), inline(c, defs, rootNames)) + IfExpr(inline(c, s, defs, rootNames), + inline(c, s, defs, rootNames), inline(c, s, defs, rootNames)) case Call(name, args) => - if(rootNames contains name) - Call(name, args map { e => inline(e, defs, rootNames) }) + if((rootNames contains name) || (s contains name)) + Call(name, args map { e => inline(e, s, defs, rootNames) }) else defs(name).body match { case a:Atom => a - case _ => Call(name, args map { e => inline(e, defs, rootNames) }) + case _ => Call(name, args map { e => inline(e, s, defs, rootNames) }) } } def simplify(e:Expr):Expr = e match { case a:Atom => a case IfExpr(c,i,e) => (simplify(c), simplify(i), simplify(e)) match { case (Call("true",Nil), i, e) => i case (Call("false",Nil), i, e) => e case (c, i, e) => IfExpr(c, i, e) } case Call(n,args) => (n, args map simplify) match { case ("+" , List(IntLit(a),IntLit(b))) => IntLit(a + b) case ("-" , List(IntLit(a),IntLit(b))) => IntLit(a - b) case ("*" , List(IntLit(a),IntLit(b))) => IntLit(a * b) case ("/" , List(IntLit(a),IntLit(b))) => IntLit(a / b) case (">" , List(IntLit(a),IntLit(b))) => Call(if(a > b) "true" else "false", Nil) case (">=", List(IntLit(a),IntLit(b))) => Call(if(a >= b) "true" else "false", Nil) case ("<" , List(IntLit(a),IntLit(b))) => Call(if(a < b) "true" else "false", Nil) case ("<=", List(IntLit(a),IntLit(b))) => Call(if(a <= b) "true" else "false", Nil) case ("==", List(IntLit(a),IntLit(b))) => Call(if(a == b) "true" else "false", Nil) case ("not", List(Call("true",Nil))) => Call("false", Nil) case ("not", List(Call("false",Nil))) => Call("true", Nil) case ("and", List(Call(a,Nil),Call(b,Nil))) => Call(if(a == "true" && b == "true") "true" else "false", Nil) case ("or", List(Call(a,Nil),Call(b,Nil))) => Call(if(a == "true" || b == "true") "true" else "false", Nil) case (n, args) => Call(n, args) } } } diff --git a/src/vmlang/compiler/typecheck/TypeCheck.scala b/src/vmlang/compiler/typecheck/TypeCheck.scala index 74a012a..312740f 100644 --- a/src/vmlang/compiler/typecheck/TypeCheck.scala +++ b/src/vmlang/compiler/typecheck/TypeCheck.scala @@ -1,131 +1,134 @@ package vmlang.compiler.typecheck import vmlang.compiler.ast._ import collection.immutable.{ Map, HashMap } object TypeCheck { val typeTree = TypeTree(AbsType("Value",0),List( TypeTree(AbsType("Function",0),List( TypeTree(RefType("Function0",1),Nil), TypeTree(RefType("Function1",2),Nil), TypeTree(RefType("Function2",3),Nil), TypeTree(RefType("Function3",4),Nil), TypeTree(RefType("Function4",5),Nil), TypeTree(RefType("Function5",6),Nil), TypeTree(RefType("Function6",7),Nil), TypeTree(RefType("Function7",8),Nil), TypeTree(RefType("Function8",9),Nil), TypeTree(RefType("Function9",10),Nil))), TypeTree(PrimType("Int",4),Nil), TypeTree(PrimType("Bool",1),Nil), TypeTree(PrimType("Null",0),Nil))) type FuncTable = Map[String,TypeExpr] type Scope = Map[String,TypeExpr] val rootFuncTypes = new HashMap[String, TypeExpr] ++ (List( ("+" , "(Int, Int) => Int" ), ("-" , "(Int, Int) => Int" ), ("*" , "(Int, Int) => Int" ), ("/" , "(Int, Int) => Int" ), ("==" , "(Int, Int) => Bool" ), ("!=" , "(Int, Int) => Bool" ), (">" , "(Int, Int) => Bool" ), (">=" , "(Int, Int) => Bool" ), ("<" , "(Int, Int) => Bool" ), ("<=" , "(Int, Int) => Bool" ), ("true" , "() => Bool" ), ("false" , "() => Bool" ), ("null" , "() => Null" ), ("and" , "(Bool, Bool) => Bool" ), ("or" , "(Bool, Bool) => Bool" ), ("not" , "(Bool) => Bool" ), ("printInt" , "(Int) => Null" ) ) map { tp => (tp._1, Parse.parseTypeExpr(tp._2)) }) def apply(e:Env):Env = (checkForValidMain(e) ::: checkCompliance(e)) match { case Nil => e case es => throw new TypeErrors(es.removeDuplicates) } def checkForValidMain(e:Env):List[TypeError] = // check that main exists and is () => Null (e.defs get "main") match { case Some(d) => (d.returnType == TypeExpr("Null", Nil) && d.params == Nil) match { case true => Nil case false => List(InvalidMainError(d.typeExpr)) } - case None => List(NoMainError) + case None => List(NoMainError()) } def checkCompliance(e:Env):List[TypeError] = e.defs.toList flatMap { case (name, d) => checkDef(d, e) } def checkDef(d:Def, e:Env):List[TypeError] = { val scope = Map() ++ (d.params map { ps => (ps.name, ps.argType) }) (d.params flatMap { ps => e.tt.checkValidTypeExpr(ps.argType) }) ::: (e.tt.checkValidTypeExpr(d.returnType)) ::: (e.tt.checkCompilableTypeExpr(d.returnType, { te => UncompilableTypeSpecError(te) })) ::: (checkCalls(d.body, scope, e) match { case Nil => e.tt.complies(d.returnType, inferType(d.body, scope, e)) case l => l }) } def checkCalls(ex:Expr, s:Scope, e:Env):List[TypeError] = ex match { case a:Atom => Nil case IfExpr(cond, i, el) => checkCalls(List(cond, i, el), s, e) case c:Call => checkCall(c, s, e) } def checkCalls(exprs:List[Expr], s:Scope, e:Env):List[TypeError] = exprs flatMap { expr => checkCalls(expr, s, e) } def checkCall(call:Call, scope:Scope, e:Env):List[TypeError] = { val giv = call.args (scope get call.name) match { case Some(_) => Nil case None => (e.ft get call.name) match { case Some(funcType) => { val exp = funcType.args.init (if(exp.length == giv.length) Nil else List(WrongNumCallArgs(call.name, exp.length, giv.length))) ::: checkArgCompliance(exp, giv, scope, e) } case None => NonexistentFuncError(call.name) :: checkCalls(call.args, scope, e) } } } def checkArgCompliance(expTypes:List[TypeExpr], args:List[Expr], s:Scope, e:Env):List[TypeError] = checkCalls(args.dropRight(expTypes.length - args.length), s, e) ::: ((expTypes zip args) flatMap { case (ext, ex) => checkCalls(ex, s, e) match { case Nil => val inferredTypeExpr = inferType(ex, s, e) e.tt.complies(ext, inferredTypeExpr) ::: e.tt.checkCompilableTypeExpr(inferredTypeExpr, { te => UncompilableArgTypeError(te) }) case l => l } }) def inferType(expr:Expr, e:Env):TypeExpr = - inferType(expr, Map[String,TypeExpr](), e) + checkCalls(expr, Map[String,TypeExpr](), e) match { + case Nil => inferType(expr, Map[String,TypeExpr](), e) + case es => throw TypeErrors(es) + } def inferType(expr:Expr, s:Scope, e:Env):TypeExpr = expr match { case IntLit(_) => TypeExpr("Int",Nil) case CharLit(_) => TypeExpr("Char",Nil) case FloatLit(_) => TypeExpr("Float",Nil) case IfExpr(_, i, t) => e.tt.deepestCommonAncestor(inferType(i, s, e), inferType(t, s, e)) case c:Call => if(isParam(c, s)) s(c.name) else e.ft(c.name).args.last } def isParam(call:Call, scope:Scope):Boolean = call.args.isEmpty && (scope isDefinedAt call.name) } diff --git a/src/vmlang/compiler/typecheck/TypeErrors.scala b/src/vmlang/compiler/typecheck/TypeErrors.scala index 2c17460..ff4ba7f 100644 --- a/src/vmlang/compiler/typecheck/TypeErrors.scala +++ b/src/vmlang/compiler/typecheck/TypeErrors.scala @@ -1,53 +1,53 @@ package vmlang.compiler.typecheck import vmlang.compiler.ast.TypeExpr case class TypeErrors(errors:List[CompilerError]) extends CompoundCompilerError(errors) abstract class TypeError extends NormalCompilerError case class NonexistentType(name:String) extends TypeError { val repr = "Nonexistent type: \"" + name + "\"" } case class Mismatch(expected:TypeExpr, given:TypeExpr) extends TypeError { val repr = "Type mismatch. Expected: " + expected.repr + "; given: " + given.repr } case class WrongNumTypeArgs(expected:Int, given:Int) extends TypeError { val repr = "Wrong number of type arguments. Expected: " + expected + "; given: " + given } case class WrongNumCallArgs(func:String, expected:Int, given:Int) extends TypeError { val repr = "Wrong number of arguments for " + func + ". Expected: " + expected + "; given: " + given } case class NonexistentFuncError(funcName:String) extends TypeError { val repr = "Call to nonexistent function " + funcName } case class DuplicateDefError(name:String) extends TypeError { val repr = "Function " + name + " already defined. Taking first definition." } case class RootDefError(name:String) extends TypeError { val repr = "\"" + name + "\" is a root function; cannot be redefined." } -case object NoMainError extends TypeError { +case class NoMainError extends TypeError { val repr = "No main function. (Must be () => Null)" } case class InvalidMainError(te:TypeExpr) extends TypeError { val repr = "Function main is " + te + "; must be () => Null" } case class UncompilableTypeSpecError(te:TypeExpr) extends TypeError { val repr = "Return type is " + te + "; must be a primitive type or an abstract type with all reference types as subtypes" } case class UncompilableArgTypeError(te:TypeExpr) extends TypeError { val repr = "Type of argument is " + te + "; must be a primitive type or an abstract type with all reference types as subtypes" } diff --git a/src/vmlang/disassembler/Main.scala b/src/vmlang/disassembler/Main.scala index 9c384c9..2862d07 100644 --- a/src/vmlang/disassembler/Main.scala +++ b/src/vmlang/disassembler/Main.scala @@ -1,48 +1,49 @@ package vmlang.disassembler import vmlang.common.optparser._ import vmlang.common.Opcodes import vmlang.common.Opcodes._ import java.io.{File, FileInputStream, DataInputStream, FileNotFoundException, IOException, EOFException} object Main extends OptParser { def numArgs(n:Int) = n == 1 val argErrorMsg = "supply 1 bytecode file to disassemble" val knownFlags = List() val defaultOpts = Map[String,String]() val help = "usage: vmld <bytecode file>\n" def run(args:List[String], flags:List[String], opts:Map[String,String]):Unit = disassemble(args.head) def disassemble(fileName:String) = try { var addr = 0 val in = new DataInputStream(new FileInputStream(new File(fileName))) val ocs = Opcodes.values while(in.available > 0) { print(addr + "\t") val oc = ocs(in.readByte) addr += 1 print(oc + "\t") oc match { case I_CONST_A => print(in.readInt); addr += 4 case I_CONST_B => print(in.readInt); addr += 4 case B_CONST_A => print(in.readByte); addr += 1 case B_CONST_B => print(in.readByte); addr += 1 case GOTO => print(in.readInt); addr += 4 case GOTO_IF_NOT_A => print(in.readInt); addr += 4 + case DEC_SP_BY => print(in.readInt); addr += 4 case _ => } println } } catch { case e:FileNotFoundException => throw FatalError("File not found: " + fileName) case e:EOFException => throw FatalError("malformed program") case e:ArrayIndexOutOfBoundsException => throw FatalError("malformed program") case e:IOException => throw FatalError("Error reading file " + fileName) } } diff --git a/src/vmlang/repl/Main.scala b/src/vmlang/repl/Main.scala new file mode 100644 index 0000000..1d33e58 --- /dev/null +++ b/src/vmlang/repl/Main.scala @@ -0,0 +1,62 @@ +package vmlang.repl + +import java.util.Scanner + +import vmlang.common.optparser._ + +import vmlang.compiler._ +import vmlang.compiler.typecheck._ +import vmlang.compiler.ast._ + +import vmlang.vm.{ VM, VMError } + +object Main extends OptParser { + + def numArgs(n:Int) = n == 0 + val argErrorMsg = "run with no args for interactive prompt" + val knownFlags = List("h") + val defaultOpts = Map[String,String]() + val help = "usage: vmli" + + def run(args:List[String], flags:List[String], opts:Map[String,String]):Unit = { + flags match { + case "h" :: fs => println(argErrorMsg) + case Nil => runREPL + } + } + + def runREPL = { + val s = new Scanner(System.in) + var resCounter = 0 + var env = Env(Map[String,Def](), TypeCheck.rootFuncTypes, TypeCheck.typeTree) + while(true) { + print(">> ") + try { + val input = s.nextLine + if(input startsWith ":t ") { + println(TypeCheck.inferType(Parse.parseExpr(input substring 3), env)) + } else { + Parse.parseREPLStmt(input) match { + case e:Expr => + env = env.addDef(Def("res" + resCounter, Nil, TypeCheck.inferType(e, env), e)) + env = env.addDef(Def("main", Nil, TypeExpr("Null", Nil), + Call("printInt",List(Call("res" + resCounter, Nil))))) + resCounter += 1 + val code = Linearize(TypeCheck(env)) + new VM(code, 1024, 1024, false).run + case d:Def => + val newEnv = env.addDef(d) + env = TypeCheck.checkDef(d, newEnv) match { + case Nil => newEnv + case es => throw TypeErrors(es.removeDuplicates) + } + } + } + } catch { + case e:CompilerError => println(e.repr) + case e:VMError => println(e.getMessage) + } + } + } + +} diff --git a/src/vmlang/vm/Main.scala b/src/vmlang/vm/Main.scala index 11d2aca..e33b20b 100644 --- a/src/vmlang/vm/Main.scala +++ b/src/vmlang/vm/Main.scala @@ -1,36 +1,37 @@ package vmlang.vm import vmlang.common.optparser._ object Main extends OptParser { def numArgs(n:Int) = n == 1 val argErrorMsg = "supply 1 bytecode file to run" - val knownFlags = List() + val knownFlags = List("d") val defaultOpts = Map("heap_size" -> "1024", "stack_size" -> "1024") val help = "usage: vml <bytecode file> <options>\n" + "-heap_size=<num bytes> heap size in bytes\n" + - "-stack_size=<num bytes> stack size in bytes" + "-stack_size=<num bytes> stack size in bytes\n" + + "-d debug" def run(args:List[String], flags:List[String], opts:Map[String,String]):Unit = { val heapSize = try { opts("heap_size").toInt } catch { case e:NumberFormatException => throw FatalError("Invalid heap size argument") } val stackSize = try { opts("stack_size").toInt } catch { case e:NumberFormatException => throw FatalError("Invalid stack size argument") } // business time try { - new VM(loadFileBytes(args(0)), heapSize, stackSize).run + new VM(loadFileBytes(args(0)), heapSize, stackSize, flags contains "d").run } catch { case e:InitError => throw FatalError("Couldn't start VM: " + e.message) case e:MalformedProgramError => throw FatalError("VM error: malformed program") case e:StackOverflowError => throw FatalError("VM error: stack overflow") } } } diff --git a/src/vmlang/vm/VM.java b/src/vmlang/vm/VM.java index 544f1ea..ee13ae5 100644 --- a/src/vmlang/vm/VM.java +++ b/src/vmlang/vm/VM.java @@ -1,459 +1,471 @@ package vmlang.vm; import java.io.IOException; import java.io.PrintStream; import java.io.InputStream; import vmlang.common.Opcodes; public class VM { // registers private int A, B, SP, FP; private int counter; // memory private byte[] program; private byte[] memory; // io private InputStream in; private PrintStream out; private int stackStart; + boolean debug; private static final Opcodes[] opcodes = Opcodes.values(); // inefficient? - public VM(byte[] prog, int heapSize, int stackSize) throws InitError { - this(prog, heapSize, stackSize, System.in, System.out); + public VM(byte[] prog, int heapSize, int stackSize, boolean d) throws InitError { + this(prog, heapSize, stackSize, System.in, System.out, d); } - public VM(byte[] prog, int heapSize, int stackSize, InputStream is, PrintStream os) + public VM(byte[] prog, int heapSize, int stackSize, InputStream is, PrintStream os, boolean d) throws InitError { if(heapSize % 8 != 0) throw new InitError("Heap size must be divisible by 8 (for malloc)"); program = prog; memory = new byte[heapSize + stackSize]; stackStart = heapSize; in = is; out = os; + debug = d; } public void run() throws VMError { int nextAddr; while(true) { Opcodes opcode; try { opcode = opcodes[progReadByte()]; } catch(ArrayIndexOutOfBoundsException e) { throw getMalfProgEx(); } + if(debug) + System.out.print(opcode); switch(opcode) { // FLOW CONTROL // basic case STOP: return; case GOTO: counter = progReadInt(); break; case GOTO_A: counter = A; break; case GOTO_SP: counter = memReadInt(SP); break; case GOTO_IF_NOT_A: nextAddr = progReadInt(); if(A == 0) counter = nextAddr; break; // LOAD & STORE (Von-Neumann bottleneck) // constants case I_CONST_A: A = progReadInt(); break; case I_CONST_B: B = progReadInt(); break; case B_CONST_A: A = progReadByte(); break; case B_CONST_B: B = progReadByte(); break; // load case I_LOAD_A_B: B = memReadInt(A); break; case I_LOAD_A_SP: SP = memReadInt(A); break; case I_LOAD_A_FP: FP = memReadInt(A); break; + case I_LOAD_A_A: + A = memReadInt(A); + break; case I_LOAD_B_A: A = memReadInt(B); break; case I_LOAD_B_SP: SP = memReadInt(B); break; case I_LOAD_B_FP: FP = memReadInt(B); break; case I_LOAD_SP_A: A = memReadInt(SP); break; case I_LOAD_SP_B: B = memReadInt(SP); break; case I_LOAD_SP_FP: FP = memReadInt(SP); break; case I_LOAD_FP_A: A = memReadInt(FP); break; case I_LOAD_FP_B: B = memReadInt(FP); break; case I_LOAD_FP_SP: SP = memReadInt(FP); break; case B_LOAD_A_B: B = memReadByte(A); break; case B_LOAD_A_SP: SP = memReadByte(A); break; case B_LOAD_A_FP: FP = memReadByte(A); break; case B_LOAD_B_A: A = memReadByte(B); break; case B_LOAD_B_SP: SP = memReadByte(B); break; case B_LOAD_B_FP: FP = memReadByte(B); break; case B_LOAD_SP_A: A = memReadByte(SP); break; case B_LOAD_SP_B: B = memReadByte(SP); break; case B_LOAD_SP_FP: FP = memReadByte(SP); break; case B_LOAD_FP_A: A = memReadByte(FP); break; case B_LOAD_FP_B: B = memReadByte(FP); break; case B_LOAD_FP_SP: SP = memReadByte(FP); break; // store case I_STORE_A_B: memWriteInt(B,A); break; case I_STORE_A_SP: memWriteInt(SP,A); break; case I_STORE_A_FP: memWriteInt(FP,A); break; case I_STORE_B_A: memWriteInt(A,B); break; case I_STORE_B_SP: memWriteInt(SP,B); break; case I_STORE_B_FP: memWriteInt(FP,B); break; case I_STORE_SP_A: memWriteInt(A,SP); break; case I_STORE_SP_B: memWriteInt(B,SP); break; case I_STORE_SP_FP: memWriteInt(FP,SP); break; case I_STORE_FP_A: memWriteInt(A,FP); break; case I_STORE_FP_B: memWriteInt(B,FP); break; case I_STORE_FP_SP: memWriteInt(SP,FP); break; case B_STORE_A_B: memWriteByte(B,(byte)A); break; case B_STORE_A_SP: memWriteByte(SP,(byte)A); break; case B_STORE_A_FP: memWriteByte(FP,(byte)A); break; case B_STORE_B_A: memWriteByte(A,(byte)B); break; case B_STORE_B_SP: memWriteByte(SP,(byte)B); break; case B_STORE_B_FP: memWriteByte(FP,(byte)B); break; case B_STORE_SP_A: memWriteByte(A,(byte)SP); break; case B_STORE_SP_B: memWriteByte(B,(byte)SP); break; case B_STORE_SP_FP: memWriteByte(FP,(byte)SP); break; case B_STORE_FP_A: memWriteByte(A,(byte)FP); break; case B_STORE_FP_B: memWriteByte(B,(byte)FP); break; case B_STORE_FP_SP: memWriteByte(SP,(byte)FP); break; // moves case MOVE_COUNTER_A: A = counter; break; case MOVE_A_B: B = A; break; case MOVE_A_SP: SP = A; break; case MOVE_A_FP: FP = A; break; case MOVE_B_A: A = B; break; case MOVE_B_SP: SP = B; break; case MOVE_B_FP: FP = B; break; case MOVE_SP_A: A = SP; break; case MOVE_SP_B: B = SP; break; case MOVE_SP_FP: FP = SP; break; case MOVE_FP_A: A = FP; break; case MOVE_FP_B: B = FP; break; case MOVE_FP_SP: SP = FP; break; // REGISTER OPERATIONS // int arithmetic case I_ADD: A = A + B; break; case I_SUB: A = A - B; break; case I_MUL: A = A * B; break; case I_DIV: A = A / B; break; case I_MOD: A = A % B; break; case INC_A: A++; break; // float arithmetic case F_ADD: A = Float.floatToIntBits(Float.intBitsToFloat(A) + Float.intBitsToFloat(B)); break; case F_SUB: A = Float.floatToIntBits(Float.intBitsToFloat(A) - Float.intBitsToFloat(B)); break; case F_MUL: A = A = Float.floatToIntBits(Float.intBitsToFloat(A) * Float.intBitsToFloat(B)); break; case F_DIV: A = Float.floatToIntBits(Float.intBitsToFloat(A) / Float.intBitsToFloat(B)); break; case F_MOD: A = Float.floatToIntBits(Float.intBitsToFloat(A) % Float.intBitsToFloat(B)); break; // inc/dec case INC_B: B++; break; case INC_SP: SP++; break; case INC_SP_INT: SP += 4; break; case DEC_A: A--; break; case DEC_B: B--; break; case DEC_SP: SP--; break; case DEC_SP_INT: SP -= 4; break; + case DEC_SP_BY: + SP -= progReadInt(); + break; // logic (0: false; non-0: true) case NEG_A: if(A == 0) A = 1; else A = 0; break; case EQ_A: if(A == 0) A = 1; else A = 0; break; case LT_A: if(A < 0) A = 1; else A = 0; break; case GT_A: if(A > 0) A = 1; else A = 0; break; case AND: if(A != 0 && B != 0) A = 1; else A = 0; break; case OR: if(A != 0 || B != 0) A = 1; else A = 0; break; case STACK_START: A = stackStart; break; // io case PRINT_CHAR_A: out.print((char)A); break; case PRINT_INT_A: out.println(A); break; case READ_CHAR_A: try { A = in.read(); } catch(IOException e) { out.println(e.getMessage()); } break; } + if(debug) + System.out.println(" => [A: "+A+" B: "+ B+" FP: " + FP + " SP: " + SP + "]"); } } // PROGRAM READERS private byte progReadByte() throws MalformedProgramError { byte result; try { result = program[counter]; } catch(ArrayIndexOutOfBoundsException e) { throw getMalfProgEx(); } counter++; return result; } private int progReadInt() throws MalformedProgramError { return ((progReadByte() & 0xff) << 24) | ((progReadByte() & 0xff) << 16) | ((progReadByte() & 0xff) << 8) | (progReadByte() & 0xff); } // MEMORY READERS & WRITERS private byte memReadByte(int addr) throws StackOverflowError { try { return memory[addr]; } catch(ArrayIndexOutOfBoundsException e) { throw new StackOverflowError(); } } private int memReadInt(int addr) throws StackOverflowError { return ((memReadByte(addr) & 0xff) << 24) | ((memReadByte(addr+1) & 0xff) << 16) | ((memReadByte(addr+2) & 0xff) << 8) | (memReadByte(addr+3) & 0xff); } private void memWriteByte(int addr, byte val) throws StackOverflowError { try { memory[addr] = val; } catch(ArrayIndexOutOfBoundsException e) { throw new StackOverflowError(); } } private void memWriteInt(int addr, int val) throws StackOverflowError { memWriteByte(addr ,(byte)(0xff & (val >> 24))); memWriteByte(addr+1,(byte)(0xff & (val >> 16))); memWriteByte(addr+2,(byte)(0xff & (val >> 8))); memWriteByte(addr+3,(byte)(0xff & val)); } private MalformedProgramError getMalfProgEx() { return new MalformedProgramError(); } } \ No newline at end of file
vilterp/VMLang
9063d8796acfc3556d4ba1f700a463547157f2dc
some restructuring of compiler. stage is finally set to get linearizer working fully.
diff --git a/src/vmlang/compiler/AST.scala b/src/vmlang/compiler/AST.scala index ba5855d..3aeb35a 100644 --- a/src/vmlang/compiler/AST.scala +++ b/src/vmlang/compiler/AST.scala @@ -1,32 +1,34 @@ package vmlang.compiler.ast import vmlang.compiler.typecheck.Type abstract class ASTNode case class Prog(defs:Map[String, Def]) extends ASTNode case class ParamSpec(name:String, argType:TypeExpr) extends ASTNode case class TypeExpr(name:String, args:List[TypeExpr]) extends ASTNode { val isFunctionType = (name startsWith "Function") && !(name endsWith("Function")) override val toString = if(isFunctionType) args.init.mkString("(",",",")") + " => " + args.last else name + (if(args.isEmpty) "" else args.mkString("[",",","]")) val repr = if(isFunctionType) toString else name } -abstract class IPromptStmt extends ASTNode +abstract class REPLStmt extends ASTNode -case class Def(name:String, params:List[ParamSpec], returnType:TypeExpr, body:Expr) extends IPromptStmt +case class Def(name:String, params:List[ParamSpec], returnType:TypeExpr, body:Expr) extends REPLStmt { + val typeExpr = TypeExpr("Function" + params.length, (params map { _.argType }) ::: List(returnType)) +} -abstract class Expr extends IPromptStmt +abstract class Expr extends REPLStmt case class IfExpr(condition:Expr, ifExpr:Expr, thenExpr:Expr) extends Expr case class Call(name:String, args:List[Expr]) extends Expr case class TypedCall(call:Call, types:List[Type]) abstract class Atom extends Expr case class IntLit(value:Int) extends Atom case class FloatLit(value:Float) extends Atom case class CharLit(value:Char) extends Atom diff --git a/src/vmlang/compiler/Compile.scala b/src/vmlang/compiler/Compile.scala index f6efac0..066154d 100644 --- a/src/vmlang/compiler/Compile.scala +++ b/src/vmlang/compiler/Compile.scala @@ -1,9 +1,20 @@ -// package vmlang.compiler -// -// import vmlang.compiler.typecheck.TypeCheck -// -// object Compile { -// -// def apply(prog:String):Array[Byte] = Linearize(Simplify(TypeCheck(Parse(prog)))) -// -// } +package vmlang.compiler + +import vmlang.compiler.typecheck.TypeCheck + +object Compile { + + def apply(prog:String):Array[Byte] = + Linearize( + Simplify( + TypeCheck( + MakeEnv( + Parse(prog), + TypeCheck.rootFuncTypes, + TypeCheck.typeTree + ) + ) + ) + ) + +} diff --git a/src/vmlang/compiler/Env.scala b/src/vmlang/compiler/Env.scala index 7e513b3..bdc7abf 100644 --- a/src/vmlang/compiler/Env.scala +++ b/src/vmlang/compiler/Env.scala @@ -1,6 +1,48 @@ package vmlang.compiler import vmlang.compiler.ast.{ Def, TypeExpr } -import vmlang.compiler.typecheck.TypeTree +import vmlang.compiler.typecheck._ + +case class Env(defs:Map[String,Def], roots:Map[String,TypeExpr], tt:TypeTree) { + + lazy val ft = defs.foldLeft(roots){ (ft, d) => ft + (d._2.name -> d._2.typeExpr) } + + // for REPL only + def addDef(d:Def) = Env(defs + (d.name -> d), roots, tt) + +} + +object MakeEnv { + + def apply(defs:List[Def], roots:Map[String,TypeExpr], tt:TypeTree):Env = + (checkForDuplicates(defs) ::: checkForRoots(defs, roots)) match { + case Nil => Env(Map[String,Def]() ++ (defs map { d => (d.name, d) }), roots, tt) + case es => throw TypeErrors(es) + } + + def checkForRoots(defs:List[Def], roots:Map[String,TypeExpr]):List[TypeError] = + defs match { + case Nil => Nil + case first :: rest => + if(roots contains first.name) + RootDefError(first.name) :: checkForRoots(rest, roots) + else + checkForRoots(rest, roots) + } + + def checkForDuplicates(defs:List[Def]):List[TypeError] = + checkForDuplicates(Nil, defs) map { d => DuplicateDefError(d.name) } + + def checkForDuplicates(alreadyDefined:List[Def], defs:List[Def]):List[Def] = + defs match { + case Nil => Nil + case first :: rest => { + if(alreadyDefined exists { _.name == first.name }) + first :: checkForDuplicates(alreadyDefined, rest) + else + checkForDuplicates(first :: alreadyDefined, rest) + } + } + +} -case class Env(defs:Map[String,Def], ft:Map[String,TypeExpr], tt:TypeTree) diff --git a/src/vmlang/compiler/Linearize.scala b/src/vmlang/compiler/Linearize.scala index 861bb8d..9928ff2 100644 --- a/src/vmlang/compiler/Linearize.scala +++ b/src/vmlang/compiler/Linearize.scala @@ -1,203 +1,203 @@ -// package vmlang.compiler -// -// import java.io.{DataOutputStream, ByteArrayOutputStream} -// import collection.mutable.HashMap -// -// -// import vmlang.common.Opcodes -// import vmlang.common.Opcodes._ -// import vmlang.compiler.ast._ -// -// // shameful imperative code... -// -// object Linearize { -// -// def apply(prog:List[Def], tt:TypeTree, ft:Map[String,TypeExpr]):Array[Byte] = -// new Linearizer(prog, tt).run -// -// } +package vmlang.compiler + +import java.io.{DataOutputStream, ByteArrayOutputStream} +import collection.mutable.HashMap + + +import vmlang.common.Opcodes +import vmlang.common.Opcodes._ +import vmlang.compiler.ast._ + +// shameful imperative code... + +object Linearize { + + def apply(e:Env):Array[Byte] = + null + +} // // class Linearizer(defs:List[Def], tt:TypeTree, ft:Map[String,TypeExpr]) { // // type Scope = List[(String, TypeExpr)] // // val baos = new ByteArrayOutputStream // val out = new DataOutputStream(baos) // val refs = new HashMap[Int,String] // val startingPoints = new HashMap[String,Int] // // val rtSizes = Map[String,Int]() ++ (defs map { d => (d.name, tt getSize d.returnType) }) // val scopes = Map[String,Int]() ++ // (defs map { d => (d.name, d.params map { p => (p.name, tt getSize p.argType) }) }) // // def run:Array[Byte] = { // wExpr(Call("main", Nil), Nil) // w(STOP) // for((n, d) <- defs) { // startingPoints += (n -> out.size) // // write def body expr // val scope = scopes(n) // wExpr(d.body, scope) // wDefPostlude(scope.foldLeft(0){ _ + _._2 }, rtSizes(n)) // } // resolveGotos // } // // def resolveGotos:Array[Byte] = { // val result = baos.toByteArray // for((ind, ref) <- refs) { // val refInd = startingPoints(ref) // // write program index (integer) to result array // result(ind+1) = (0xff & (refInd << 24)).asInstanceOf[Byte] // result(ind+2) = (0xff & (refInd << 16)).asInstanceOf[Byte] // result(ind+3) = (0xff & (refInd << 8)).asInstanceOf[Byte] // result(ind+4) = (0xff & refInd).asInstanceOf[Byte] // } // result // } // // def wExpr(e:Expr, s:Scope):Unit = e match { // // case IntLit(i) => w(I_CONST_A, i); w(I_STORE_A_SP); w(INC_SP_INT) // case CharLit(c) => w(B_CONST_A, c.toByte); w(B_STORE_A_SP); w(INC_SP) // case FloatLit(f) => w(I_CONST_A, java.lang.Float.floatToIntBits(f)); w(I_STORE_A_SP); w(INC_SP_INT) // // case Call("+", List(a, b)) => intOp(a, b, s, ()=>{ w(I_ADD) }) // case Call("-", List(a, b)) => intOp(a, b, s, ()=>{ w(I_SUB) }) // case Call("*", List(a, b)) => intOp(a, b, s, ()=>{ w(I_MUL) }) // case Call("/", List(a, b)) => intOp(a, b, s, ()=>{ w(I_DIV) }) // case Call("%", List(a, b)) => intOp(a, b, s, ()=>{ w(I_MOD) }) // // case Call("==", List(a, b)) => cmpOp(a, b, s, ()=>{ w(EQ_A) }) // case Call(">" , List(a, b)) => cmpOp(a, b, s, ()=>{ w(GT_A) }) // case Call("<" , List(a, b)) => cmpOp(a, b, s, ()=>{ w(LT_A) }) // case Call(">=", List(a, b)) => cmpOp(a, b, s, ()=>{ w(LT_A); w(NEG_A) }) // case Call("<=", List(a, b)) => cmpOp(a, b, s, ()=>{ w(GT_A); w(NEG_A) }) // // case Call("and", List(a, b)) => byteOp(a, b, s, ()=>{ w(AND) }) // case Call("or" , List(a, b)) => byteOp(a, b, s, ()=>{ w(OR) }) // case Call("not", List(a)) => wExpr(a, s); wPopByteA; w(NEG_A); wPushByte() // // case Call("true" , Nil) => w(B_CONST_A, 1:Byte); wPushByte // case Call("false", Nil) => w(B_CONST_A, 0:Byte); wPushByte // case Call("null" , Nil) => // do nothing // // case Call("printInt", List(a)) => wExpr(a, s); wPopIntA; w(PRINT_INT_A) // // case Call(name, args) => argOffset(name, s) match { // case Some(offset) => // is parameter // w(MOVE_FP_A) // w(I_CONST_B, offset) // w(I_SUB) // w(I_LOAD_A_A) // w(I_STORE_A_SP) // w(INC_SP_INT) // case None => // is call // (args foreach { wExpr(_, s) }) // wCallPrelude // wGoto(name) // wCallPostlude(scopes(name).foldLeft(0){ _ + _._2 }) // retrieve returned value // } // // } // // def argOffset(name:String, scope:Scope):Option[Int] = // (scope findIndexOf { _._1 == name }) match { // case -1 => None // case index => Some((scope drop index).foldLeft(0){ _ + _._2 }) // } // // def wCallPrelude = { // // push base pointer // w(MOVE_FP_A) // w(I_STORE_A_SP) // w(MOVE_SP_FP) // w(INC_SP_INT) // // push (program address+13) // // so it will return to the instruction right after the GOTO // w(MOVE_COUNTER_A) // w(I_CONST_B, 13) // w(I_ADD) // w(I_STORE_A_SP) // w(INC_SP_INT) // } // // def wGoto(ref:String) { // refs += (out.size -> ref) // w(GOTO, 0) // the 0 will be replaced in resolveGotos // } // // def wDefPostlude(paramSize:Int, rtSize:Int) = { // // decrement SP to point at return value // for(i <- (1 to (rtSize / 4))) // w(DEC_SP_INT) // for(i <- (1 to (rtSize % 4))) // w(DEC_SP) // // store answer on calling function's operand stack // w(MOVE_FP_A) // w(I_CONST_B, paramSize) // !!! what about functions w/ no params?! // w(I_SUB) // w(MOVE_A_B) // w(I_LOAD_A_SP) // w(I_STORE_A_B) // // set FP to saved FP (on stack) // w(DEC_SP_INT) // w(DEC_SP_INT) // w(I_LOAD_FP_SP) // load the value at addr SP into FP // // goto return address (on stack) // w(INC_SP_INT) // w(I_LOAD_A_SP) // w(GOTO_A) // } // // def getSize(e:Expr) = // tt.getSize(TypeCheck.inferType(e, tt, allFuncs)) // // def wCallPostlude(paramSize:Int, rtSize:Int) = { // w(MOVE_SP_A) // w(I_CONST_B, 4 + (paramSize - rtSize)) // w(I_SUB) // w(MOVE_A_SP) // } // // def cmpOp(a:Expr, b:Expr, s:Scope, cmp:()=>Unit) = // intOp(a, b, s, { w(I_SUB); cmp(); wPushByte }) // // def intOp(a:Expr, b:Expr, s:Scope, ops:()=>Unit) = { // intOpNoPush(a, b, s, ops) // wPushInt // } // def intOpNoPush(a:Expr, b:Expr, s:Scope, ops:()=>Unit) = { // wExpr(a, s) // wExpr(b, s) // wPopIntB // wPopIntA // ops() // } // // def byteOp(a:Expr, b:Expr, s:Scope, ops:()=>Unit) = { // byteOpNoPush(a, b, s, ops) // wPushByte // } // def byteOpNoPush(a:Expr, b:Expr, s:Scope, ops:()=>Unit) = { // wExpr(a, s) // wExpr(b, s) // wPopByteB // wPopByteA // ops() // } // // def wPopIntA = { w(DEC_SP_INT); w(I_LOAD_A_SP) } // def wPopIntB = { w(DEC_SP_INT); w(I_LOAD_B_SP) } // def wPushInt = { w(I_STORE_A_SP); w(INC_SP_INT) } // // def wPopByteA = { w(DEC_SP); w(B_LOAD_A_SP) } // def wPopByteB = { w(DEC_SP); w(B_LOAD_B_SP) } // def wPushByte() = { w(DEC_SP); w(B_STORE_A_SP); } // // def w(oc:Opcodes):Unit = out.write(oc.toByte) // def w(oc:Opcodes, arg:Int):Unit = { w(oc); out.writeInt(arg) } // def w(oc:Opcodes, arg:Float):Unit = { w(oc); out.writeFloat(arg) } // def w(oc:Opcodes, arg:Byte):Unit = { w(oc); out.writeByte(arg) } // // } diff --git a/src/vmlang/compiler/Main.scala b/src/vmlang/compiler/Main.scala index 5bba48a..490a593 100644 --- a/src/vmlang/compiler/Main.scala +++ b/src/vmlang/compiler/Main.scala @@ -1,63 +1,63 @@ -// package vmlang.compiler -// -// import vmlang.common.optparser._ -// -// import vmlang.compiler.typecheck.TypeCheck -// import vmlang.compiler.ast._ -// import vmlang.vm.{VM, VMError} -// -// import java.util.Scanner -// -// import collection.mutable.HashMap -// -// object Main extends OptParser { -// -// def numArgs(n:Int) = n == 0 || n == 1 -// val argErrorMsg = "supply 1 file to compile, or no argument for interactive prompt" -// val knownFlags = List("v") -// val defaultOpts = Map[String,String]() -// val help = "usage: vmlc <optional source file> <options>\n" + -// "-v print out messages about what the compiler is doing" -// -// def run(args:List[String], flags:List[String], opts:Map[String,String]):Unit = -// args match { -// case Nil => runIPrompt -// case List(fn) => -// try { -// writeFile(Compile(loadFile(fn)), (fn split '.')(0) + ".vmlc") -// } catch { -// case e:CompilerError => throw FatalError(e.repr) -// } -// } -// -// def runIPrompt = { -// val s = new Scanner(System.in) -// var counter = 0 -// var defs = Map[String,Def]() -// while(true) { -// print(">> ") -// try { -// val input = s.nextLine -// if(input startsWith ":t ") { -// println(TypeCheck.inferType(Parse.parseExpr(input substring 3))) -// } else { -// Parse.parseIPromptStmt(input) match { -// case e:Expr => -// defs = defs + ("main" -> Def("main", Nil, TypeExpr("Null",Nil), e match { -// case Call("printInt",args) => e -// case expr => Call("printInt",List(expr)) -// })) -// case d:Def => -// defs = defs + (d.name -> d) -// } -// val code = Linearize(Simplify(TypeCheck(Prog(defs)))) -// new VM(code, 1024, 1024).run -// } -// } catch { -// case e:CompilerError => println(e.repr) -// case e:VMError => println(e.getMessage) -// } -// } -// } -// -// } +package vmlang.compiler + +import vmlang.common.optparser._ + +import vmlang.compiler.typecheck.TypeCheck +import vmlang.compiler.ast._ +import vmlang.vm.{VM, VMError} + +import java.util.Scanner + +import collection.mutable.HashMap + +object Main extends OptParser { + + def numArgs(n:Int) = n == 0 || n == 1 + val argErrorMsg = "supply 1 file to compile, or no argument for interactive prompt" + val knownFlags = List("v") + val defaultOpts = Map[String,String]() + val help = "usage: vmlc <optional source file> <options>\n" + + "-v print out messages about what the compiler is doing" + + def run(args:List[String], flags:List[String], opts:Map[String,String]):Unit = + args match { + case Nil => runREPL + case List(fn) => + try { + writeFile(Compile(loadFile(fn)), ( fn split '.')(0) + ".vmlc") + } catch { + case e:CompilerError => throw FatalError(e.repr) + } + } + + def runREPL = { + val s = new Scanner(System.in) + var resCounter = 0 + var env = Env(Map[String,Def](), TypeCheck.rootFuncTypes, TypeCheck.typeTree) + while(true) { + print(">> ") + try { + val input = s.nextLine + if(input startsWith ":t ") { + println(TypeCheck.inferType(Parse.parseExpr(input substring 3), env)) + } else { + Parse.parseREPLStmt(input) match { + case e:Expr => + env = env.addDef(Def("res" + resCounter, Nil, TypeCheck.inferType(e, env), e)) + env = env.addDef(Def("main", Nil, TypeExpr("Null", Nil), + Call("printInt",List(Call("res" + resCounter, Nil))))) + resCounter += 1 + val code = Linearize(Simplify(TypeCheck(env))) + new VM(code, 1024, 1024).run + case d:Def => + env = env.addDef(d) + } + } + } catch { + case e:CompilerError => println(e.repr) + case e:VMError => println(e.getMessage) + } + } + } + +} diff --git a/src/vmlang/compiler/Parse.scala b/src/vmlang/compiler/Parse.scala index d42113c..297c88a 100644 --- a/src/vmlang/compiler/Parse.scala +++ b/src/vmlang/compiler/Parse.scala @@ -1,136 +1,136 @@ package vmlang.compiler import vmlang.compiler.ast._ import util.parsing.combinator.syntactical._ import runtime.RichString import collection.immutable.HashMap case class ParserError(msg:String) extends NormalCompilerError { val repr = "Parser Error: " + msg } case object TooManyParams extends ParserError("can't make a function with more than 9 params") object Parse extends StandardTokenParsers { def apply(s:String) = phrase(program)(new lexical.Scanner(s)) match { case Success(tree, _) => tree case e:NoSuccess => throw ParserError(e.toString) } def parseTypeExpr(t:String) = phrase(typeExpr)(new lexical.Scanner(t)) match { case Success(t, _) => t case e:NoSuccess => throw new ParserError(e.toString) } - def parseIPromptStmt(s:String) = - phrase(iPromptStmt)(new lexical.Scanner(s)) match { + def parseREPLStmt(s:String) = + phrase(REPLStmt)(new lexical.Scanner(s)) match { case Success(t, _) => t case e:NoSuccess => throw ParserError(e.toString) } def parseExpr(s:String) = phrase(expr)(new lexical.Scanner(s)) match { case Success(t, _) => t case e:NoSuccess => throw new ParserError(e.toString) } // LEXICAL INFO lexical.delimiters ++= List("+","-","*","/","(",")","[","]","=","=>",":",",",">","<", ">=","<=","==","!","!=") lexical.reserved ++= List("if","then","else","and","or") // RULES def program = definition + - def iPromptStmt = ( definition | expr ) + def REPLStmt = ( definition | expr ) def definition = ident ~ (paramsSpec?) ~ typeSpec ~ ("=" ~> expr) ^^ { case i ~ Some(ps) ~ rt ~ e => Def(i, checkPs(ps), rt, e) case i ~ None ~ rt ~ e => Def(i, Nil, rt, e) } def checkPs(ps:List[ParamSpec]) = if(ps.length <= 9) ps else throw TooManyParams def paramsSpec = "(" ~> repsep(paramSpec, ",") <~ ")" def paramSpec = ident ~ typeSpec ^^ { case i ~ t => ParamSpec(i,t) } def typeSpec = ":" ~> typeExpr def typeExpr:Parser[TypeExpr] = ( normalTypeExpr | funcTypeExpr ) def normalTypeExpr:Parser[TypeExpr] = ident ~ (typeParams?) ^^ { case i ~ Some(tp) => TypeExpr(i, tp) case i ~ None => TypeExpr(i, Nil) } def funcTypeExpr:Parser[TypeExpr] = ("(" ~> repsep(typeExpr,",") <~ ")") ~ ("=>" ~> typeExpr) ^^ { case pts ~ rt => mkFuncTypeExpr(pts, rt) } def mkFuncTypeExpr(paramTypes:List[TypeExpr], returnType:TypeExpr):TypeExpr = if(paramTypes.length <= 9) TypeExpr("Function" + paramTypes.length, paramTypes ::: List(returnType)) else throw TooManyParams def typeParams = "[" ~> repsep(typeExpr,",") <~ "]" def expr:Parser[Expr] = ( ifStatement | orExpr ) def ifStatement = (("if" ~> orExpr) ~ ("then" ~> orExpr) ~ ("else" ~> orExpr)) ^^ { case c ~ i ~ e => IfExpr(c,i,e) } def orExpr = andExpr * ( "or" ^^^ { (a:Expr, b:Expr) => Call("or",List(a,b)) } ) def andExpr = comparison * ( "and" ^^^ { (a:Expr, b:Expr) => Call("and",List(a,b)) } ) def comparison = sum * ( ">" ^^^ { (a:Expr, b:Expr) => Call(">",List(a,b)) } | "<" ^^^ { (a:Expr, b:Expr) => Call("<",List(a,b)) } | "==" ^^^ { (a:Expr, b:Expr) => Call("==",List(a,b)) } | "<=" ^^^ { (a:Expr, b:Expr) => Call("<=",List(a,b)) } | ">=" ^^^ { (a:Expr, b:Expr) => Call(">=",List(a,b)) } | "!=" ^^^ { (a:Expr, b:Expr) => Call("!=",List(a,b)) } ) // I'm sure there's a super-elegant way to do this, // but my Scala chops aren't up to it yet def sum = product * ( "+" ^^^ { (a:Expr, b:Expr) => Call("+",List(a,b)) } | "-" ^^^ { (a:Expr, b:Expr) => Call("-",List(a,b)) } ) def product = atom * ( "*" ^^^ { (a:Expr, b:Expr) => Call("*",List(a,b)) } | "/" ^^^ { (a:Expr, b:Expr) => Call("/",List(a,b)) } ) def atom = ( int | list | string | call | parenthesizedExpr | unaryMinus | unaryNot ) // todo: char lit (not in standardtokenparsers...) def list = "[" ~> repsep(expr,",") <~ "]" ^^ concatIze def string = stringLit ^^ { (s:String) => concatIze(new RichString(s) map { CharLit(_) }) } def concatIze(items:Seq[Expr]):Expr = items.foldRight(Call("EmptyList",Nil).asInstanceOf[Expr]){ (i,a) => Call(":",List(i,a)) } def parenthesizedExpr = "(" ~> expr <~ ")" def unaryNot:Parser[Expr] = "not" ~> atom ^^ { a => Call("not",List(a)) } def unaryMinus:Parser[Expr] = "-" ~> atom ^^ { a => Call("*",List(a,IntLit(-1))) } def int = numericLit ^^ { s => IntLit(s.toInt) } def call = ident ~ (args ?) ^^ { case i ~ Some(a) => Call(i,a) case i ~ None => Call(i,Nil) } def args = "(" ~> repsep(expr,",") <~ ")" } diff --git a/src/vmlang/compiler/typecheck/TypeCheck.scala b/src/vmlang/compiler/typecheck/TypeCheck.scala index 63e8966..74a012a 100644 --- a/src/vmlang/compiler/typecheck/TypeCheck.scala +++ b/src/vmlang/compiler/typecheck/TypeCheck.scala @@ -1,162 +1,131 @@ package vmlang.compiler.typecheck import vmlang.compiler.ast._ import collection.immutable.{ Map, HashMap } object TypeCheck { val typeTree = TypeTree(AbsType("Value",0),List( TypeTree(AbsType("Function",0),List( TypeTree(RefType("Function0",1),Nil), TypeTree(RefType("Function1",2),Nil), TypeTree(RefType("Function2",3),Nil), TypeTree(RefType("Function3",4),Nil), TypeTree(RefType("Function4",5),Nil), TypeTree(RefType("Function5",6),Nil), TypeTree(RefType("Function6",7),Nil), TypeTree(RefType("Function7",8),Nil), TypeTree(RefType("Function8",9),Nil), TypeTree(RefType("Function9",10),Nil))), TypeTree(PrimType("Int",4),Nil), TypeTree(PrimType("Bool",1),Nil), TypeTree(PrimType("Null",0),Nil))) type FuncTable = Map[String,TypeExpr] type Scope = Map[String,TypeExpr] val rootFuncTypes = new HashMap[String, TypeExpr] ++ (List( ("+" , "(Int, Int) => Int" ), ("-" , "(Int, Int) => Int" ), ("*" , "(Int, Int) => Int" ), ("/" , "(Int, Int) => Int" ), ("==" , "(Int, Int) => Bool" ), ("!=" , "(Int, Int) => Bool" ), (">" , "(Int, Int) => Bool" ), (">=" , "(Int, Int) => Bool" ), ("<" , "(Int, Int) => Bool" ), ("<=" , "(Int, Int) => Bool" ), ("true" , "() => Bool" ), ("false" , "() => Bool" ), ("null" , "() => Null" ), ("and" , "(Bool, Bool) => Bool" ), ("or" , "(Bool, Bool) => Bool" ), ("not" , "(Bool) => Bool" ), ("printInt" , "(Int) => Null" ) ) map { tp => (tp._1, Parse.parseTypeExpr(tp._2)) }) - def apply(defs:List[Def]):Env = - apply(defs, rootFuncTypes, typeTree) - - def apply(defs:List[Def], ft:FuncTable, tt:TypeTree):Env = { - val (ds, dupErrors) = checkForDuplicates(defs) - val allFuncs = addTypeSigs(ft, defs) - (dupErrors ::: checkForValidMain(ds) ::: checkCompliance(ds, allFuncs, tt)) match { - case Nil => - val defs = Map[String,Def]() ++ (ds map { d => (d.name, d) }) - Env(defs, allFuncs, tt) - case es => throw new TypeErrors(es.removeDuplicates) - } - } - - def checkForDuplicates(defs:List[Def]):(List[Def], List[TypeError]) = { - val (nonDups, dups) = checkForDuplicates(Nil, defs) - (nonDups, dups map { d => DuplicateDefError(d.name) }) - } - - def checkForDuplicates(alreadyDefined:List[Def], defs:List[Def]):(List[Def], List[Def]) = - defs match { - case Nil => (alreadyDefined, Nil) - case first :: rest => { - if(alreadyDefined exists { _.name == first.name }) { - val (restNonDups, restDups) = checkForDuplicates(alreadyDefined, rest) - (restNonDups, first :: restDups) - } else { - checkForDuplicates(first :: alreadyDefined, rest) - } - } + def apply(e:Env):Env = + (checkForValidMain(e) ::: checkCompliance(e)) match { + case Nil => e + case es => throw new TypeErrors(es.removeDuplicates) } - def checkForValidMain(defs:List[Def]):List[TypeError] = + def checkForValidMain(e:Env):List[TypeError] = // check that main exists and is () => Null - (defs find { _.name == "main" }) match { - case Some(d) => (d.returnType == TypeExpr("Null",Nil) && d.params == Nil) match { + (e.defs get "main") match { + case Some(d) => (d.returnType == TypeExpr("Null", Nil) && d.params == Nil) match { case true => Nil - case false => List(InvalidMainError(mkFuncTypeExpr(d))) + case false => List(InvalidMainError(d.typeExpr)) } case None => List(NoMainError) } - def addTypeSigs(ft:FuncTable, defs:List[Def]):FuncTable = - defs.foldLeft(ft){ (ft, d) => ft + (d.name -> mkFuncTypeExpr(d)) } - - def mkFuncTypeExpr(d:Def):TypeExpr = - TypeExpr("Function" + d.params.length, (d.params map { _.argType }) ::: List(d.returnType)) - - def checkCompliance(defs:List[Def], ft:FuncTable, tt:TypeTree):List[TypeError] = - defs flatMap { d => checkDef(d, ft, tt) } + def checkCompliance(e:Env):List[TypeError] = + e.defs.toList flatMap { case (name, d) => checkDef(d, e) } - def checkDef(d:Def, ft:FuncTable, tt:TypeTree):List[TypeError] = { + def checkDef(d:Def, e:Env):List[TypeError] = { val scope = Map() ++ (d.params map { ps => (ps.name, ps.argType) }) - (d.params flatMap { ps => tt.checkValidTypeExpr(ps.argType) }) ::: - (tt.checkValidTypeExpr(d.returnType)) ::: - (tt.checkCompilableTypeExpr(d.returnType, { te => UncompilableTypeSpecError(te) })) ::: - (checkCalls(d.body, scope, ft, tt) match { - case Nil => tt.complies(d.returnType, inferType(d.body, scope, ft, tt)) + (d.params flatMap { ps => e.tt.checkValidTypeExpr(ps.argType) }) ::: + (e.tt.checkValidTypeExpr(d.returnType)) ::: + (e.tt.checkCompilableTypeExpr(d.returnType, { te => UncompilableTypeSpecError(te) })) ::: + (checkCalls(d.body, scope, e) match { + case Nil => e.tt.complies(d.returnType, inferType(d.body, scope, e)) case l => l }) } - def checkCalls(e:Expr, s:Scope, ft:FuncTable, tt:TypeTree):List[TypeError] = - e match { - case a:Atom => Nil - case IfExpr(i, c, e) => checkCalls(List(i, c, e), s, ft, tt) - case c:Call => checkCall(c, s, ft, tt) + def checkCalls(ex:Expr, s:Scope, e:Env):List[TypeError] = + ex match { + case a:Atom => Nil + case IfExpr(cond, i, el) => checkCalls(List(cond, i, el), s, e) + case c:Call => checkCall(c, s, e) } - def checkCalls(es:List[Expr], s:Scope, ft:FuncTable, tt:TypeTree):List[TypeError] = - es flatMap { e => checkCalls(e, s, ft, tt) } + def checkCalls(exprs:List[Expr], s:Scope, e:Env):List[TypeError] = + exprs flatMap { expr => checkCalls(expr, s, e) } - def checkCall(call:Call, scope:Scope, ft:FuncTable, tt:TypeTree):List[TypeError] = { + def checkCall(call:Call, scope:Scope, e:Env):List[TypeError] = { val giv = call.args (scope get call.name) match { case Some(_) => Nil - case None => (ft get call.name) match { + case None => (e.ft get call.name) match { case Some(funcType) => { val exp = funcType.args.init (if(exp.length == giv.length) Nil else List(WrongNumCallArgs(call.name, exp.length, giv.length))) ::: - checkArgCompliance(exp, giv, scope, ft, tt) + checkArgCompliance(exp, giv, scope, e) } - case None => NonexistentFuncError(call.name) :: checkCalls(call.args, scope, ft, tt) + case None => NonexistentFuncError(call.name) :: checkCalls(call.args, scope, e) } } } - def checkArgCompliance(expTypes:List[TypeExpr], args:List[Expr], - s:Scope, ft:FuncTable, tt:TypeTree):List[TypeError] = - checkCalls(args.dropRight(expTypes.length - args.length), s, ft, tt) ::: - ((expTypes zip args) flatMap { case (et, e) => checkCalls(e, s, ft, tt) match { + def checkArgCompliance(expTypes:List[TypeExpr], args:List[Expr], s:Scope, e:Env):List[TypeError] = + checkCalls(args.dropRight(expTypes.length - args.length), s, e) ::: + ((expTypes zip args) flatMap { case (ext, ex) => checkCalls(ex, s, e) match { case Nil => - val inferredTypeExpr = inferType(e, s, ft, tt) - tt.complies(et, inferredTypeExpr) ::: - tt.checkCompilableTypeExpr(inferredTypeExpr, { te => UncompilableArgTypeError(te) }) + val inferredTypeExpr = inferType(ex, s, e) + e.tt.complies(ext, inferredTypeExpr) ::: + e.tt.checkCompilableTypeExpr(inferredTypeExpr, { te => UncompilableArgTypeError(te) }) case l => l } }) - def inferType(expr:Expr, s:Scope, ft:FuncTable, tt:TypeTree):TypeExpr = { - expr match { - case IntLit(_) => TypeExpr("Int",Nil) - case CharLit(_) => TypeExpr("Char",Nil) - case FloatLit(_) => TypeExpr("Float",Nil) - case IfExpr(_, i, t) => tt.deepestCommonAncestor(inferType(i, s, ft, tt), - inferType(t, s, ft, tt)) - case c:Call => if(isParam(c, s)) s(c.name) else ft(c.name).args.last - } - } + def inferType(expr:Expr, e:Env):TypeExpr = + inferType(expr, Map[String,TypeExpr](), e) + + def inferType(expr:Expr, s:Scope, e:Env):TypeExpr = + expr match { + case IntLit(_) => TypeExpr("Int",Nil) + case CharLit(_) => TypeExpr("Char",Nil) + case FloatLit(_) => TypeExpr("Float",Nil) + case IfExpr(_, i, t) => e.tt.deepestCommonAncestor(inferType(i, s, e), + inferType(t, s, e)) + case c:Call => if(isParam(c, s)) s(c.name) else e.ft(c.name).args.last + } def isParam(call:Call, scope:Scope):Boolean = call.args.isEmpty && (scope isDefinedAt call.name) } diff --git a/src/vmlang/compiler/typecheck/TypeErrors.scala b/src/vmlang/compiler/typecheck/TypeErrors.scala index 2a80888..2c17460 100644 --- a/src/vmlang/compiler/typecheck/TypeErrors.scala +++ b/src/vmlang/compiler/typecheck/TypeErrors.scala @@ -1,49 +1,53 @@ package vmlang.compiler.typecheck import vmlang.compiler.ast.TypeExpr case class TypeErrors(errors:List[CompilerError]) extends CompoundCompilerError(errors) abstract class TypeError extends NormalCompilerError case class NonexistentType(name:String) extends TypeError { val repr = "Nonexistent type: \"" + name + "\"" } case class Mismatch(expected:TypeExpr, given:TypeExpr) extends TypeError { val repr = "Type mismatch. Expected: " + expected.repr + "; given: " + given.repr } case class WrongNumTypeArgs(expected:Int, given:Int) extends TypeError { val repr = "Wrong number of type arguments. Expected: " + expected + "; given: " + given } case class WrongNumCallArgs(func:String, expected:Int, given:Int) extends TypeError { val repr = "Wrong number of arguments for " + func + ". Expected: " + expected + "; given: " + given } case class NonexistentFuncError(funcName:String) extends TypeError { val repr = "Call to nonexistent function " + funcName } case class DuplicateDefError(name:String) extends TypeError { val repr = "Function " + name + " already defined. Taking first definition." } +case class RootDefError(name:String) extends TypeError { + val repr = "\"" + name + "\" is a root function; cannot be redefined." +} + case object NoMainError extends TypeError { val repr = "No main function. (Must be () => Null)" } case class InvalidMainError(te:TypeExpr) extends TypeError { val repr = "Function main is " + te + "; must be () => Null" } case class UncompilableTypeSpecError(te:TypeExpr) extends TypeError { val repr = "Return type is " + te + "; must be a primitive type or an abstract type with all reference types as subtypes" } case class UncompilableArgTypeError(te:TypeExpr) extends TypeError { val repr = "Type of argument is " + te + "; must be a primitive type or an abstract type with all reference types as subtypes" }
vilterp/VMLang
89681d06459e2d112b66f5eb1345cbad0cd0da4b
added all permutations of move, store, and load
diff --git a/src/vmlang/assembler/Assemble.scala b/src/vmlang/assembler/Assemble.scala deleted file mode 100644 index 6f61027..0000000 --- a/src/vmlang/assembler/Assemble.scala +++ /dev/null @@ -1,43 +0,0 @@ -package vmlang.assembler - -import vmlang.common.Opcodes._ -import vmlang.common.Opcodes - -case class AssemblyError(msg:String) extends Exception - -object Assemble { - - val opcodes = Map[String,Byte]() ++ (Opcodes.values map { oc => (oc.toString, oc.toByte) }) - - def apply(prog:Prog):List[Byte] = - prog.instrs flatMap { case Instr(opcode, arg) => (opcodes get opcode) match { - case Some(byte) => opcode match { - case "I_CONST_A" | - "I_CONST_B" | - "GOTO" => byte :: (arg match { - case Some(i) => i match { - case i:Int => intBytes(i) - case _ => throw AssemblyError("opcode " + opcode + " takes an int argument") - } - case None => throw AssemblyError("opcode " + opcode + " takes an int argument") - }) - case "B_CONST_A" | - "B_CONST_B" => byte :: (arg match { - case Some(b) => b match { - case b:Byte => b :: Nil - case _ => throw AssemblyError("opcode " + opcode + " takes a byte argument") - } - case None => throw AssemblyError("opcode " + opcode + " takes a byte argument") - }) - case _ => List(byte) - } - case None => throw AssemblyError("nonexistent opcode: " + opcode) - } } - - def intBytes(i:Int):List[Byte] = - (0xff & (i << 24)).asInstanceOf[Byte] :: - (0xff & (i << 16)).asInstanceOf[Byte] :: - (0xff & (i << 8)).asInstanceOf[Byte] :: - (0xff & i).asInstanceOf[Byte] :: Nil - -} diff --git a/src/vmlang/assembler/Main.scala b/src/vmlang/assembler/Main.scala deleted file mode 100644 index 76b26e6..0000000 --- a/src/vmlang/assembler/Main.scala +++ /dev/null @@ -1,21 +0,0 @@ -package vmlang.assembler - -import vmlang.common.optparser._ - -object Main extends OptParser { - - def numArgs(n:Int) = n == 1 - val argErrorMsg = "supply 1 file to assemble" - val knownFlags = List() - val defaultOpts = Map[String,String]() - val help = "usage: vmla <file to assemble>" - - def run(args:List[String], flags:List[String], opts:Map[String,String]):Unit = - try { - writeFile(Assemble(Parse(loadFile(args.head))), (args.head split '.')(0) + ".vmlc") - } catch { - case ParserError(msg) => throw FatalError("Parser Error: " + msg) - case AssemblyError(msg) => throw FatalError("Assembly Error: " + msg) - } - -} diff --git a/src/vmlang/assembler/Parse.scala b/src/vmlang/assembler/Parse.scala deleted file mode 100644 index c29ee52..0000000 --- a/src/vmlang/assembler/Parse.scala +++ /dev/null @@ -1,28 +0,0 @@ -package vmlang.assembler - -import util.parsing.input.CharSequenceReader -import util.parsing.combinator.JavaTokenParsers - -object Parse extends JavaTokenParsers { - - def prog = (instr+) ^^ { is => Prog(is) } - - def instr = opcode ~ (arg?) ^^ { case oc ~ a => Instr(oc, a) } - - def opcode = ident - - def arg = wholeNumber ^^ { _.toInt } - - def apply(input:String):Prog = - phrase(prog)(new CharSequenceReader(input)) match { - case Success(t, _) => t - case e:NoSuccess => throw ParserError(e.toString) - } - -} - -case class ParserError(msg:String) extends Exception - -abstract class ASTNode -case class Prog(instrs:List[Instr]) extends ASTNode -case class Instr(opcode:String, arg:Option[AnyVal]) diff --git a/src/vmlang/common/Opcodes.java b/src/vmlang/common/Opcodes.java index 0a64be7..ee84580 100644 --- a/src/vmlang/common/Opcodes.java +++ b/src/vmlang/common/Opcodes.java @@ -1,63 +1,122 @@ package vmlang.common; +/* +I_LOAD_SP_A: A = memReadInt(SP) +I_STORE_A_SP: memWriteInt(SP,A) +MOVE_A_B: B = A +*/ + public enum Opcodes { STOP, GOTO, GOTO_A, - IF_EQ, - IF_LT, + GOTO_SP, + GOTO_IF_NOT_A, + I_CONST_A, I_CONST_B, B_CONST_A, B_CONST_B, + + I_LOAD_A_B, I_LOAD_A_SP, - I_LOAD_A_A, - I_LOAD_FP_SP, + I_LOAD_A_FP, + I_LOAD_B_A, I_LOAD_B_SP, - I_LOAD_SP_SP, + I_LOAD_B_FP, + I_LOAD_SP_A, + I_LOAD_SP_B, + I_LOAD_SP_FP, + I_LOAD_FP_A, + I_LOAD_FP_B, + I_LOAD_FP_SP, + B_LOAD_A_B, B_LOAD_A_SP, - B_LOAD_A_A, + B_LOAD_A_FP, + B_LOAD_B_A, B_LOAD_B_SP, + B_LOAD_B_FP, + B_LOAD_SP_A, + B_LOAD_SP_B, + B_LOAD_SP_FP, + B_LOAD_FP_A, + B_LOAD_FP_B, + B_LOAD_FP_SP, + + I_STORE_A_B, I_STORE_A_SP, + I_STORE_A_FP, + I_STORE_B_A, + I_STORE_B_SP, + I_STORE_B_FP, + I_STORE_SP_A, + I_STORE_SP_B, + I_STORE_SP_FP, + I_STORE_FP_A, + I_STORE_FP_B, I_STORE_FP_SP, + B_STORE_A_B, B_STORE_A_SP, + B_STORE_A_FP, + B_STORE_B_A, + B_STORE_B_SP, + B_STORE_B_FP, + B_STORE_SP_A, + B_STORE_SP_B, + B_STORE_SP_FP, + B_STORE_FP_A, + B_STORE_FP_B, + B_STORE_FP_SP, + MOVE_COUNTER_A, - MOVE_SP_A, - MOVE_FP_A, + MOVE_A_B, MOVE_A_SP, MOVE_A_FP, + MOVE_B_A, + MOVE_B_SP, + MOVE_B_FP, + MOVE_SP_A, + MOVE_SP_B, MOVE_SP_FP, + MOVE_FP_A, + MOVE_FP_B, + MOVE_FP_SP, + I_ADD, I_SUB, I_MUL, I_DIV, I_MOD, + F_ADD, F_SUB, F_MUL, F_DIV, F_MOD, + INC_A, INC_B, INC_SP, INC_SP_INT, DEC_A, DEC_B, DEC_SP, DEC_SP_INT, + NEG_A, EQ_A, LT_A, GT_A, AND, OR, + PRINT_CHAR_A, PRINT_INT_A, READ_CHAR_A, STACK_START; public byte toByte() { return (byte)ordinal(); } } diff --git a/src/vmlang/disassembler/Main.scala b/src/vmlang/disassembler/Main.scala index d0d1f2e..9c384c9 100644 --- a/src/vmlang/disassembler/Main.scala +++ b/src/vmlang/disassembler/Main.scala @@ -1,47 +1,48 @@ package vmlang.disassembler import vmlang.common.optparser._ import vmlang.common.Opcodes import vmlang.common.Opcodes._ import java.io.{File, FileInputStream, DataInputStream, FileNotFoundException, IOException, EOFException} object Main extends OptParser { def numArgs(n:Int) = n == 1 val argErrorMsg = "supply 1 bytecode file to disassemble" val knownFlags = List() val defaultOpts = Map[String,String]() val help = "usage: vmld <bytecode file>\n" def run(args:List[String], flags:List[String], opts:Map[String,String]):Unit = disassemble(args.head) def disassemble(fileName:String) = try { var addr = 0 val in = new DataInputStream(new FileInputStream(new File(fileName))) val ocs = Opcodes.values while(in.available > 0) { print(addr + "\t") val oc = ocs(in.readByte) addr += 1 print(oc + "\t") oc match { - case I_CONST_A => print(in.readInt); addr += 4 - case I_CONST_B => print(in.readInt); addr += 4 - case B_CONST_A => print(in.readByte); addr += 1 - case B_CONST_B => print(in.readByte); addr += 1 - case GOTO => print(in.readInt); addr += 4 - case _ => + case I_CONST_A => print(in.readInt); addr += 4 + case I_CONST_B => print(in.readInt); addr += 4 + case B_CONST_A => print(in.readByte); addr += 1 + case B_CONST_B => print(in.readByte); addr += 1 + case GOTO => print(in.readInt); addr += 4 + case GOTO_IF_NOT_A => print(in.readInt); addr += 4 + case _ => } println } } catch { case e:FileNotFoundException => throw FatalError("File not found: " + fileName) case e:EOFException => throw FatalError("malformed program") case e:ArrayIndexOutOfBoundsException => throw FatalError("malformed program") case e:IOException => throw FatalError("Error reading file " + fileName) } } diff --git a/src/vmlang/vm/VM.java b/src/vmlang/vm/VM.java index ab8a34b..544f1ea 100644 --- a/src/vmlang/vm/VM.java +++ b/src/vmlang/vm/VM.java @@ -1,325 +1,459 @@ package vmlang.vm; import java.io.IOException; import java.io.PrintStream; import java.io.InputStream; import vmlang.common.Opcodes; public class VM { // registers private int A, B, SP, FP; private int counter; // memory private byte[] program; private byte[] memory; // io private InputStream in; private PrintStream out; private int stackStart; private static final Opcodes[] opcodes = Opcodes.values(); // inefficient? public VM(byte[] prog, int heapSize, int stackSize) throws InitError { this(prog, heapSize, stackSize, System.in, System.out); } public VM(byte[] prog, int heapSize, int stackSize, InputStream is, PrintStream os) throws InitError { if(heapSize % 8 != 0) throw new InitError("Heap size must be divisible by 8 (for malloc)"); program = prog; memory = new byte[heapSize + stackSize]; stackStart = heapSize; in = is; out = os; } public void run() throws VMError { int nextAddr; while(true) { Opcodes opcode; try { opcode = opcodes[progReadByte()]; } catch(ArrayIndexOutOfBoundsException e) { throw getMalfProgEx(); } switch(opcode) { // FLOW CONTROL // basic case STOP: return; case GOTO: counter = progReadInt(); break; case GOTO_A: counter = A; break; - // conditional jumps: based on post-SUB state of register A - case IF_EQ: - nextAddr = progReadInt(); - if(A != 0) - counter = nextAddr; + case GOTO_SP: + counter = memReadInt(SP); break; - case IF_LT: + case GOTO_IF_NOT_A: nextAddr = progReadInt(); - if(A >= 0) + if(A == 0) counter = nextAddr; break; // LOAD & STORE (Von-Neumann bottleneck) - // int constants + // constants + case I_CONST_A: A = progReadInt(); break; case I_CONST_B: B = progReadInt(); break; - // byte constants case B_CONST_A: A = progReadByte(); break; case B_CONST_B: B = progReadByte(); break; - // load int + + // load + + case I_LOAD_A_B: + B = memReadInt(A); + break; case I_LOAD_A_SP: - A = memReadInt(SP); - break; - case I_LOAD_A_A: - A = memReadInt(A); - break; - case I_LOAD_FP_SP: - FP = memReadInt(SP); - break; + SP = memReadInt(A); + break; + case I_LOAD_A_FP: + FP = memReadInt(A); + break; + case I_LOAD_B_A: + A = memReadInt(B); + break; case I_LOAD_B_SP: - B = memReadInt(SP); - break; - case I_LOAD_SP_SP: - SP = memReadInt(SP); - break; - // load byte + SP = memReadInt(B); + break; + case I_LOAD_B_FP: + FP = memReadInt(B); + break; + case I_LOAD_SP_A: + A = memReadInt(SP); + break; + case I_LOAD_SP_B: + B = memReadInt(SP); + break; + case I_LOAD_SP_FP: + FP = memReadInt(SP); + break; + case I_LOAD_FP_A: + A = memReadInt(FP); + break; + case I_LOAD_FP_B: + B = memReadInt(FP); + break; + case I_LOAD_FP_SP: + SP = memReadInt(FP); + break; + case B_LOAD_A_B: + B = memReadByte(A); + break; case B_LOAD_A_SP: - A = memReadByte(SP); - break; - case B_LOAD_A_A: - A = memReadByte(A); - break; + SP = memReadByte(A); + break; + case B_LOAD_A_FP: + FP = memReadByte(A); + break; + case B_LOAD_B_A: + A = memReadByte(B); + break; case B_LOAD_B_SP: - B = memReadByte(SP); - break; - // store int + SP = memReadByte(B); + break; + case B_LOAD_B_FP: + FP = memReadByte(B); + break; + case B_LOAD_SP_A: + A = memReadByte(SP); + break; + case B_LOAD_SP_B: + B = memReadByte(SP); + break; + case B_LOAD_SP_FP: + FP = memReadByte(SP); + break; + case B_LOAD_FP_A: + A = memReadByte(FP); + break; + case B_LOAD_FP_B: + B = memReadByte(FP); + break; + case B_LOAD_FP_SP: + SP = memReadByte(FP); + break; + + + // store + + case I_STORE_A_B: + memWriteInt(B,A); + break; case I_STORE_A_SP: - memWriteInt(SP,A); - break; + memWriteInt(SP,A); + break; + case I_STORE_A_FP: + memWriteInt(FP,A); + break; + case I_STORE_B_A: + memWriteInt(A,B); + break; + case I_STORE_B_SP: + memWriteInt(SP,B); + break; + case I_STORE_B_FP: + memWriteInt(FP,B); + break; + case I_STORE_SP_A: + memWriteInt(A,SP); + break; + case I_STORE_SP_B: + memWriteInt(B,SP); + break; + case I_STORE_SP_FP: + memWriteInt(FP,SP); + break; + case I_STORE_FP_A: + memWriteInt(A,FP); + break; + case I_STORE_FP_B: + memWriteInt(B,FP); + break; case I_STORE_FP_SP: - memWriteInt(SP,FP); - break; - // store byte + memWriteInt(SP,FP); + break; + case B_STORE_A_B: + memWriteByte(B,(byte)A); + break; case B_STORE_A_SP: - memWriteByte(SP,(byte)A); - break; + memWriteByte(SP,(byte)A); + break; + case B_STORE_A_FP: + memWriteByte(FP,(byte)A); + break; + case B_STORE_B_A: + memWriteByte(A,(byte)B); + break; + case B_STORE_B_SP: + memWriteByte(SP,(byte)B); + break; + case B_STORE_B_FP: + memWriteByte(FP,(byte)B); + break; + case B_STORE_SP_A: + memWriteByte(A,(byte)SP); + break; + case B_STORE_SP_B: + memWriteByte(B,(byte)SP); + break; + case B_STORE_SP_FP: + memWriteByte(FP,(byte)SP); + break; + case B_STORE_FP_A: + memWriteByte(A,(byte)FP); + break; + case B_STORE_FP_B: + memWriteByte(B,(byte)FP); + break; + case B_STORE_FP_SP: + memWriteByte(SP,(byte)FP); + break; + // moves + case MOVE_COUNTER_A: A = counter; break; - case MOVE_SP_A: - A = SP; - break; - case MOVE_FP_A: - A = FP; - break; + case MOVE_A_B: + B = A; + break; case MOVE_A_SP: - SP = A; - break; + SP = A; + break; case MOVE_A_FP: - FP = A; - break; + FP = A; + break; + case MOVE_B_A: + A = B; + break; + case MOVE_B_SP: + SP = B; + break; + case MOVE_B_FP: + FP = B; + break; + case MOVE_SP_A: + A = SP; + break; + case MOVE_SP_B: + B = SP; + break; case MOVE_SP_FP: - FP = SP; - break; + FP = SP; + break; + case MOVE_FP_A: + A = FP; + break; + case MOVE_FP_B: + B = FP; + break; + case MOVE_FP_SP: + SP = FP; + break; // REGISTER OPERATIONS // int arithmetic case I_ADD: A = A + B; break; case I_SUB: A = A - B; break; case I_MUL: A = A * B; break; case I_DIV: A = A / B; break; case I_MOD: A = A % B; break; case INC_A: A++; break; // float arithmetic case F_ADD: A = Float.floatToIntBits(Float.intBitsToFloat(A) + Float.intBitsToFloat(B)); break; case F_SUB: A = Float.floatToIntBits(Float.intBitsToFloat(A) - Float.intBitsToFloat(B)); break; case F_MUL: A = A = Float.floatToIntBits(Float.intBitsToFloat(A) * Float.intBitsToFloat(B)); break; case F_DIV: A = Float.floatToIntBits(Float.intBitsToFloat(A) / Float.intBitsToFloat(B)); break; case F_MOD: A = Float.floatToIntBits(Float.intBitsToFloat(A) % Float.intBitsToFloat(B)); break; // inc/dec case INC_B: B++; break; case INC_SP: SP++; break; case INC_SP_INT: SP += 4; break; case DEC_A: A--; break; case DEC_B: B--; break; case DEC_SP: SP--; break; case DEC_SP_INT: SP -= 4; break; // logic (0: false; non-0: true) case NEG_A: if(A == 0) A = 1; else A = 0; break; case EQ_A: if(A == 0) A = 1; else A = 0; break; case LT_A: if(A < 0) A = 1; else A = 0; break; case GT_A: if(A > 0) A = 1; else A = 0; break; case AND: if(A != 0 && B != 0) A = 1; else A = 0; break; case OR: if(A != 0 || B != 0) A = 1; else A = 0; break; case STACK_START: A = stackStart; break; // io case PRINT_CHAR_A: out.print((char)A); break; case PRINT_INT_A: out.println(A); break; case READ_CHAR_A: try { A = in.read(); } catch(IOException e) { out.println(e.getMessage()); } break; } } } // PROGRAM READERS private byte progReadByte() throws MalformedProgramError { byte result; try { result = program[counter]; } catch(ArrayIndexOutOfBoundsException e) { throw getMalfProgEx(); } counter++; return result; } private int progReadInt() throws MalformedProgramError { return ((progReadByte() & 0xff) << 24) | ((progReadByte() & 0xff) << 16) | ((progReadByte() & 0xff) << 8) | (progReadByte() & 0xff); } // MEMORY READERS & WRITERS private byte memReadByte(int addr) throws StackOverflowError { try { return memory[addr]; } catch(ArrayIndexOutOfBoundsException e) { throw new StackOverflowError(); } } private int memReadInt(int addr) throws StackOverflowError { return ((memReadByte(addr) & 0xff) << 24) | ((memReadByte(addr+1) & 0xff) << 16) | ((memReadByte(addr+2) & 0xff) << 8) | (memReadByte(addr+3) & 0xff); } private void memWriteByte(int addr, byte val) throws StackOverflowError { try { memory[addr] = val; } catch(ArrayIndexOutOfBoundsException e) { throw new StackOverflowError(); } } private void memWriteInt(int addr, int val) throws StackOverflowError { memWriteByte(addr ,(byte)(0xff & (val >> 24))); memWriteByte(addr+1,(byte)(0xff & (val >> 16))); memWriteByte(addr+2,(byte)(0xff & (val >> 8))); memWriteByte(addr+3,(byte)(0xff & val)); } private MalformedProgramError getMalfProgEx() { return new MalformedProgramError(); } } \ No newline at end of file
vilterp/VMLang
f1635a71d5e3be4db9057f9da199306a7fe77b30
added call graph visualizer
diff --git a/examples/fib.vml b/examples/fib.vml new file mode 100644 index 0000000..4da6a19 --- /dev/null +++ b/examples/fib.vml @@ -0,0 +1,2 @@ +main:Null = printInt(fib(20)) +fib(n:Int):Int = if n == 0 or n == 1 then 1 else fib(n-1) + fib(n-2) diff --git a/examples/fib.vmlcg b/examples/fib.vmlcg new file mode 100644 index 0000000..90256fb --- /dev/null +++ b/examples/fib.vmlcg @@ -0,0 +1,10 @@ +fib or +fib == +fib == +fib + +fib fib +fib - +fib fib +fib - +main printInt +main fib diff --git a/examples/test2.vmlcg b/examples/test2.vmlcg new file mode 100644 index 0000000..781b164 --- /dev/null +++ b/examples/test2.vmlcg @@ -0,0 +1,2 @@ +main printInt +main a diff --git a/src/vmlang/callgraph/CallGraphViz.pdf b/src/vmlang/callgraph/CallGraphViz.pdf new file mode 100644 index 0000000..ebe923a Binary files /dev/null and b/src/vmlang/callgraph/CallGraphViz.pdf differ diff --git a/src/vmlang/callgraph/CallGraphViz.py b/src/vmlang/callgraph/CallGraphViz.py new file mode 100644 index 0000000..dc25f4d --- /dev/null +++ b/src/vmlang/callgraph/CallGraphViz.py @@ -0,0 +1,31 @@ +# runs in Nodebox (nodebox.net) +# doesn't draw connections from a node to itself (recursive calls). pity. + +graph = ximport('graph') + +path = '/Users/petevilter/Dropbox/code/vmlang/examples/fib.vmlcg' + +cgtuples = [l.split('\t') for l in open(path).read().split('\n') if l != ''] + +print cgtuples + +speed(30) + +def setup(): + global g, cgtuples + g = graph.create() + + for tuple in cgtuples: + g.add_node(tuple[0]) + g[tuple[0]].id = tuple[0] + + for tuple in cgtuples: + g.add_edge(tuple[0],tuple[1]) + + g['main'].style = 'important' + + g.prune() + +def draw(): + global g + g.draw(directed=True) diff --git a/src/vmlang/callgraph/Main.scala b/src/vmlang/callgraph/Main.scala new file mode 100644 index 0000000..0f03fe6 --- /dev/null +++ b/src/vmlang/callgraph/Main.scala @@ -0,0 +1,37 @@ +package vmlang.callgraph + +import vmlang.common.optparser._ + +import vmlang.compiler._ +import vmlang.compiler.typecheck._ +import vmlang.compiler.ast._ + +object Main extends OptParser { + + def numArgs(n:Int) = n == 1 + val argErrorMsg = "supply 1 file to show callgraph for" + val knownFlags = List() + val defaultOpts = Map[String,String]() + val help = "usage: vmlcg <file to show call graph for>" + + def run(args:List[String], flags:List[String], opts:Map[String,String]):Unit = + try { + val callTuples = extractCalls(TypeCheck(Parse(loadFile(args.head))).defs) flatMap { + case (n, cs) => cs map { c => (n, c) } } + callTuples foreach { case (caller, callee) => println(caller + "\t" + callee) } + } catch { + case e:CompilerError => println(e.repr) + } + + def extractCalls(defs:Map[String,Def]):Map[String,List[String]] = + Map() ++ (defs map { case (n,d) => (n, calls(d.body) filter { + c => !d.params.exists { _.name == c } }) }) + + def calls(e:Expr):List[String] = + e match { + case a:Atom => Nil + case IfExpr(c, i, e) => calls(c) ::: calls(i) ::: calls(e) + case Call(name, args) => name :: (args flatMap (calls _)) + } + +}
vilterp/VMLang
e5ce669a8f737f55331238954ba9793d1ffe39a5
typechecker additions, added Env, added inliner
diff --git a/bugs.txt b/bugs.txt index caa203b..c60dbcb 100644 --- a/bugs.txt +++ b/bugs.txt @@ -1,28 +1,29 @@ COMPILER Overall - - should be object-oriented -- will take care of overloading + - what about overloading (typeclasses, abstract classes, oh my!) + - doesn't give error if user tries to define "true" or any other root function Parser - can't parse floats or chars - use RegexParsers to make custom scanner - error messages will be hard - give location info to tokens, if possible - maybe use scala.io.Source (has fromString method) - then use custom scanner in existing parser - unary "not"s aren't parsed right Linearizer - function calls don't work - if statements aren't implemented - uses Type#size to compute instructions, but defs that take parameters with abstract types don't know what they will be called with! this computation must take place on a per-call basis, when argument types are known (note this makes CheckedDef useless) INTERACTIVE PROMPT - ":t <expr>" doesn't take user-defined functions into account - defining a function yields "No main function. (Must be () => Null)" - ":t myFunction" should give myFunction's type signature, not parse it as an expression - should save expressions typed in as "res{n}" diff --git a/src/vmlang/compiler/Compile.scala b/src/vmlang/compiler/Compile.scala index c6cca61..f6efac0 100644 --- a/src/vmlang/compiler/Compile.scala +++ b/src/vmlang/compiler/Compile.scala @@ -1,9 +1,9 @@ -package vmlang.compiler - -import vmlang.compiler.typecheck.TypeCheck - -object Compile { - - def apply(prog:String):Array[Byte] = Linearize(Simplify(TypeCheck(Parse(prog)))) - -} +// package vmlang.compiler +// +// import vmlang.compiler.typecheck.TypeCheck +// +// object Compile { +// +// def apply(prog:String):Array[Byte] = Linearize(Simplify(TypeCheck(Parse(prog)))) +// +// } diff --git a/src/vmlang/compiler/Env.scala b/src/vmlang/compiler/Env.scala new file mode 100644 index 0000000..7e513b3 --- /dev/null +++ b/src/vmlang/compiler/Env.scala @@ -0,0 +1,6 @@ +package vmlang.compiler + +import vmlang.compiler.ast.{ Def, TypeExpr } +import vmlang.compiler.typecheck.TypeTree + +case class Env(defs:Map[String,Def], ft:Map[String,TypeExpr], tt:TypeTree) diff --git a/src/vmlang/compiler/Linearize.scala b/src/vmlang/compiler/Linearize.scala index 82ce69c..861bb8d 100644 --- a/src/vmlang/compiler/Linearize.scala +++ b/src/vmlang/compiler/Linearize.scala @@ -1,188 +1,203 @@ // package vmlang.compiler // // import java.io.{DataOutputStream, ByteArrayOutputStream} // import collection.mutable.HashMap // // // import vmlang.common.Opcodes // import vmlang.common.Opcodes._ // import vmlang.compiler.ast._ // // // shameful imperative code... // // object Linearize { // -// def apply(prog:Prog):Array[Byte] = new Linearizer(prog).run +// def apply(prog:List[Def], tt:TypeTree, ft:Map[String,TypeExpr]):Array[Byte] = +// new Linearizer(prog, tt).run // // } // -// class Linearizer(prog:Prog) { +// class Linearizer(defs:List[Def], tt:TypeTree, ft:Map[String,TypeExpr]) { // -// private val baos = new ByteArrayOutputStream -// private val out = new DataOutputStream(baos) -// private val refs = new HashMap[Int,String] -// private val startingPoints = new HashMap[String,Int] +// type Scope = List[(String, TypeExpr)] +// +// val baos = new ByteArrayOutputStream +// val out = new DataOutputStream(baos) +// val refs = new HashMap[Int,String] +// val startingPoints = new HashMap[String,Int] +// +// val rtSizes = Map[String,Int]() ++ (defs map { d => (d.name, tt getSize d.returnType) }) +// val scopes = Map[String,Int]() ++ +// (defs map { d => (d.name, d.params map { p => (p.name, tt getSize p.argType) }) }) // // def run:Array[Byte] = { // wExpr(Call("main", Nil), Nil) // w(STOP) -// for((n, d) <- prog.defs) { +// for((n, d) <- defs) { // startingPoints += (n -> out.size) -// wExpr(d.body, d.params) -// // goto return address (on stack) -// w(MOVE_A_FP) -// w(DEC_SP_INT) -// w(I_LOAD_A_SP) -// w(GOTO_A) +// // write def body expr +// val scope = scopes(n) +// wExpr(d.body, scope) +// wDefPostlude(scope.foldLeft(0){ _ + _._2 }, rtSizes(n)) // } // resolveGotos // } // -// private def resolveGotos:Array[Byte] = { +// def resolveGotos:Array[Byte] = { // val result = baos.toByteArray // for((ind, ref) <- refs) { // val refInd = startingPoints(ref) // // write program index (integer) to result array // result(ind+1) = (0xff & (refInd << 24)).asInstanceOf[Byte] // result(ind+2) = (0xff & (refInd << 16)).asInstanceOf[Byte] // result(ind+3) = (0xff & (refInd << 8)).asInstanceOf[Byte] // result(ind+4) = (0xff & refInd).asInstanceOf[Byte] // } // result // } // -// private def w(oc:Opcodes):Unit = out.write(oc.toByte) -// private def w(oc:Opcodes, arg:Int):Unit = { w(oc); out.writeInt(arg) } -// private def w(oc:Opcodes, arg:Float):Unit = { w(oc); out.writeFloat(arg) } -// private def w(oc:Opcodes, arg:Byte):Unit = { w(oc); out.writeByte(arg) } -// -// private def wExpr(e:Expr, s:Scope):Unit = e match { +// def wExpr(e:Expr, s:Scope):Unit = e match { // // case IntLit(i) => w(I_CONST_A, i); w(I_STORE_A_SP); w(INC_SP_INT) // case CharLit(c) => w(B_CONST_A, c.toByte); w(B_STORE_A_SP); w(INC_SP) // case FloatLit(f) => w(I_CONST_A, java.lang.Float.floatToIntBits(f)); w(I_STORE_A_SP); w(INC_SP_INT) // // case Call("+", List(a, b)) => intOp(a, b, s, ()=>{ w(I_ADD) }) // case Call("-", List(a, b)) => intOp(a, b, s, ()=>{ w(I_SUB) }) // case Call("*", List(a, b)) => intOp(a, b, s, ()=>{ w(I_MUL) }) // case Call("/", List(a, b)) => intOp(a, b, s, ()=>{ w(I_DIV) }) // case Call("%", List(a, b)) => intOp(a, b, s, ()=>{ w(I_MOD) }) // // case Call("==", List(a, b)) => cmpOp(a, b, s, ()=>{ w(EQ_A) }) // case Call(">" , List(a, b)) => cmpOp(a, b, s, ()=>{ w(GT_A) }) // case Call("<" , List(a, b)) => cmpOp(a, b, s, ()=>{ w(LT_A) }) // case Call(">=", List(a, b)) => cmpOp(a, b, s, ()=>{ w(LT_A); w(NEG_A) }) // case Call("<=", List(a, b)) => cmpOp(a, b, s, ()=>{ w(GT_A); w(NEG_A) }) // // case Call("and", List(a, b)) => byteOp(a, b, s, ()=>{ w(AND) }) // case Call("or" , List(a, b)) => byteOp(a, b, s, ()=>{ w(OR) }) // case Call("not", List(a)) => wExpr(a, s); wPopByteA; w(NEG_A); wPushByte() // // case Call("true" , Nil) => w(B_CONST_A, 1:Byte); wPushByte // case Call("false", Nil) => w(B_CONST_A, 0:Byte); wPushByte // case Call("null" , Nil) => // do nothing // // case Call("printInt", List(a)) => wExpr(a, s); wPopIntA; w(PRINT_INT_A) // // case Call(name, args) => argOffset(name, s) match { -// case Some(offset) => +// case Some(offset) => // is parameter // w(MOVE_FP_A) // w(I_CONST_B, offset) // w(I_SUB) // w(I_LOAD_A_A) // w(I_STORE_A_SP) // w(INC_SP_INT) -// case None => +// case None => // is call // (args foreach { wExpr(_, s) }) // wCallPrelude // wGoto(name) -// wCallPostlude(prog(name).params.foldLeft(0){ _ + _._2}) // retrieve returned value +// wCallPostlude(scopes(name).foldLeft(0){ _ + _._2 }) // retrieve returned value // } // // } // -// private def argOffset(name:String, scope:Scope):Option[Int] = +// def argOffset(name:String, scope:Scope):Option[Int] = // (scope findIndexOf { _._1 == name }) match { // case -1 => None // case index => Some((scope drop index).foldLeft(0){ _ + _._2 }) // } // -// private def wCallPrelude = { +// def wCallPrelude = { // // push base pointer // w(MOVE_FP_A) // w(I_STORE_A_SP) // w(MOVE_SP_FP) // w(INC_SP_INT) // // push (program address+13) // // so it will return to the instruction right after the GOTO // w(MOVE_COUNTER_A) // w(I_CONST_B, 13) // w(I_ADD) // w(I_STORE_A_SP) // w(INC_SP_INT) // } // -// private def wGoto(ref:String) { +// def wGoto(ref:String) { // refs += (out.size -> ref) // w(GOTO, 0) // the 0 will be replaced in resolveGotos // } // -// private def wCallPostlude(paramSize:Int) = { -// // load answer into FP -// w(INC_SP_INT) -// w(I_LOAD_FP_SP) -// // save answer from FP to stack -// w(MOVE_SP_A) -// w(I_CONST_B, paramSize + 8) +// def wDefPostlude(paramSize:Int, rtSize:Int) = { +// // decrement SP to point at return value +// for(i <- (1 to (rtSize / 4))) +// w(DEC_SP_INT) +// for(i <- (1 to (rtSize % 4))) +// w(DEC_SP) +// // store answer on calling function's operand stack +// w(MOVE_FP_A) +// w(I_CONST_B, paramSize) // !!! what about functions w/ no params?! // w(I_SUB) -// w(MOVE_A_SP) -// w(I_STORE_FP_SP) -// // get FP from stack -// w(MOVE_SP_A) -// w(I_CONST_B, paramSize) -// w(I_ADD) -// w(MOVE_A_SP) -// w(I_LOAD_FP_SP) -// // move SP back to operand stack +// w(MOVE_A_B) +// w(I_LOAD_A_SP) +// w(I_STORE_A_B) +// // set FP to saved FP (on stack) +// w(DEC_SP_INT) +// w(DEC_SP_INT) +// w(I_LOAD_FP_SP) // load the value at addr SP into FP +// // goto return address (on stack) +// w(INC_SP_INT) +// w(I_LOAD_A_SP) +// w(GOTO_A) +// } +// +// def getSize(e:Expr) = +// tt.getSize(TypeCheck.inferType(e, tt, allFuncs)) +// +// def wCallPostlude(paramSize:Int, rtSize:Int) = { // w(MOVE_SP_A) -// w(I_CONST_B, paramSize) +// w(I_CONST_B, 4 + (paramSize - rtSize)) // w(I_SUB) // w(MOVE_A_SP) // } // -// private def cmpOp(a:Expr, b:Expr, s:Scope, cmp:()=>Unit) = +// def cmpOp(a:Expr, b:Expr, s:Scope, cmp:()=>Unit) = // intOp(a, b, s, { w(I_SUB); cmp(); wPushByte }) // -// private def intOp(a:Expr, b:Expr, s:Scope, ops:()=>Unit) = { +// def intOp(a:Expr, b:Expr, s:Scope, ops:()=>Unit) = { // intOpNoPush(a, b, s, ops) // wPushInt // } -// private def intOpNoPush(a:Expr, b:Expr, s:Scope, ops:()=>Unit) = { +// def intOpNoPush(a:Expr, b:Expr, s:Scope, ops:()=>Unit) = { // wExpr(a, s) // wExpr(b, s) // wPopIntB // wPopIntA // ops() // } // -// private def byteOp(a:Expr, b:Expr, s:Scope, ops:()=>Unit) = { +// def byteOp(a:Expr, b:Expr, s:Scope, ops:()=>Unit) = { // byteOpNoPush(a, b, s, ops) // wPushByte // } -// private def byteOpNoPush(a:Expr, b:Expr, s:Scope, ops:()=>Unit) = { +// def byteOpNoPush(a:Expr, b:Expr, s:Scope, ops:()=>Unit) = { // wExpr(a, s) // wExpr(b, s) // wPopByteB // wPopByteA // ops() // } // -// private def wPopIntA = { w(DEC_SP_INT); w(I_LOAD_A_SP) } -// private def wPopIntB = { w(DEC_SP_INT); w(I_LOAD_B_SP) } -// private def wPushInt = { w(I_STORE_A_SP); w(INC_SP_INT) } +// def wPopIntA = { w(DEC_SP_INT); w(I_LOAD_A_SP) } +// def wPopIntB = { w(DEC_SP_INT); w(I_LOAD_B_SP) } +// def wPushInt = { w(I_STORE_A_SP); w(INC_SP_INT) } +// +// def wPopByteA = { w(DEC_SP); w(B_LOAD_A_SP) } +// def wPopByteB = { w(DEC_SP); w(B_LOAD_B_SP) } +// def wPushByte() = { w(DEC_SP); w(B_STORE_A_SP); } // -// private def wPopByteA = { w(DEC_SP); w(B_LOAD_A_SP) } -// private def wPopByteB = { w(DEC_SP); w(B_LOAD_B_SP) } -// private def wPushByte() = { w(DEC_SP); w(B_STORE_A_SP); } +// def w(oc:Opcodes):Unit = out.write(oc.toByte) +// def w(oc:Opcodes, arg:Int):Unit = { w(oc); out.writeInt(arg) } +// def w(oc:Opcodes, arg:Float):Unit = { w(oc); out.writeFloat(arg) } +// def w(oc:Opcodes, arg:Byte):Unit = { w(oc); out.writeByte(arg) } // // } diff --git a/src/vmlang/compiler/Parse.scala b/src/vmlang/compiler/Parse.scala index 847ada4..d42113c 100644 --- a/src/vmlang/compiler/Parse.scala +++ b/src/vmlang/compiler/Parse.scala @@ -1,139 +1,136 @@ package vmlang.compiler import vmlang.compiler.ast._ import util.parsing.combinator.syntactical._ import runtime.RichString import collection.immutable.HashMap case class ParserError(msg:String) extends NormalCompilerError { val repr = "Parser Error: " + msg } case object TooManyParams extends ParserError("can't make a function with more than 9 params") object Parse extends StandardTokenParsers { + def apply(s:String) = + phrase(program)(new lexical.Scanner(s)) match { + case Success(tree, _) => tree + case e:NoSuccess => + throw ParserError(e.toString) + } + + def parseTypeExpr(t:String) = + phrase(typeExpr)(new lexical.Scanner(t)) match { + case Success(t, _) => t + case e:NoSuccess => + throw new ParserError(e.toString) + } + + def parseIPromptStmt(s:String) = + phrase(iPromptStmt)(new lexical.Scanner(s)) match { + case Success(t, _) => t + case e:NoSuccess => + throw ParserError(e.toString) + } + + def parseExpr(s:String) = + phrase(expr)(new lexical.Scanner(s)) match { + case Success(t, _) => t + case e:NoSuccess => + throw new ParserError(e.toString) + } + + // LEXICAL INFO + lexical.delimiters ++= List("+","-","*","/","(",")","[","]","=","=>",":",",",">","<", ">=","<=","==","!","!=") lexical.reserved ++= List("if","then","else","and","or") // RULES def program = definition + def iPromptStmt = ( definition | expr ) def definition = ident ~ (paramsSpec?) ~ typeSpec ~ ("=" ~> expr) ^^ { case i ~ Some(ps) ~ rt ~ e => Def(i, checkPs(ps), rt, e) case i ~ None ~ rt ~ e => Def(i, Nil, rt, e) } def checkPs(ps:List[ParamSpec]) = if(ps.length <= 9) ps else throw TooManyParams def paramsSpec = "(" ~> repsep(paramSpec, ",") <~ ")" def paramSpec = ident ~ typeSpec ^^ { case i ~ t => ParamSpec(i,t) } def typeSpec = ":" ~> typeExpr def typeExpr:Parser[TypeExpr] = ( normalTypeExpr | funcTypeExpr ) def normalTypeExpr:Parser[TypeExpr] = ident ~ (typeParams?) ^^ { case i ~ Some(tp) => TypeExpr(i, tp) case i ~ None => TypeExpr(i, Nil) } def funcTypeExpr:Parser[TypeExpr] = ("(" ~> repsep(typeExpr,",") <~ ")") ~ ("=>" ~> typeExpr) ^^ { case pts ~ rt => mkFuncTypeExpr(pts, rt) } def mkFuncTypeExpr(paramTypes:List[TypeExpr], returnType:TypeExpr):TypeExpr = if(paramTypes.length <= 9) TypeExpr("Function" + paramTypes.length, paramTypes ::: List(returnType)) else throw TooManyParams def typeParams = "[" ~> repsep(typeExpr,",") <~ "]" def expr:Parser[Expr] = ( ifStatement | orExpr ) def ifStatement = (("if" ~> orExpr) ~ ("then" ~> orExpr) ~ ("else" ~> orExpr)) ^^ { case c ~ i ~ e => IfExpr(c,i,e) } def orExpr = andExpr * ( "or" ^^^ { (a:Expr, b:Expr) => Call("or",List(a,b)) } ) def andExpr = comparison * ( "and" ^^^ { (a:Expr, b:Expr) => Call("and",List(a,b)) } ) def comparison = sum * ( ">" ^^^ { (a:Expr, b:Expr) => Call(">",List(a,b)) } | "<" ^^^ { (a:Expr, b:Expr) => Call("<",List(a,b)) } | "==" ^^^ { (a:Expr, b:Expr) => Call("==",List(a,b)) } | "<=" ^^^ { (a:Expr, b:Expr) => Call("<=",List(a,b)) } | ">=" ^^^ { (a:Expr, b:Expr) => Call(">=",List(a,b)) } | "!=" ^^^ { (a:Expr, b:Expr) => Call("!=",List(a,b)) } ) // I'm sure there's a super-elegant way to do this, // but my Scala chops aren't up to it yet def sum = product * ( "+" ^^^ { (a:Expr, b:Expr) => Call("+",List(a,b)) } | "-" ^^^ { (a:Expr, b:Expr) => Call("-",List(a,b)) } ) def product = atom * ( "*" ^^^ { (a:Expr, b:Expr) => Call("*",List(a,b)) } | "/" ^^^ { (a:Expr, b:Expr) => Call("/",List(a,b)) } ) def atom = ( int | list | string | call | parenthesizedExpr | unaryMinus | unaryNot ) // todo: char lit (not in standardtokenparsers...) def list = "[" ~> repsep(expr,",") <~ "]" ^^ concatIze def string = stringLit ^^ { (s:String) => concatIze(new RichString(s) map { CharLit(_) }) } def concatIze(items:Seq[Expr]):Expr = items.foldRight(Call("EmptyList",Nil).asInstanceOf[Expr]){ (i,a) => Call(":",List(i,a)) } def parenthesizedExpr = "(" ~> expr <~ ")" def unaryNot:Parser[Expr] = "not" ~> atom ^^ { a => Call("not",List(a)) } def unaryMinus:Parser[Expr] = "-" ~> atom ^^ { a => Call("*",List(a,IntLit(-1))) } def int = numericLit ^^ { s => IntLit(s.toInt) } def call = ident ~ (args ?) ^^ { case i ~ Some(a) => Call(i,a) case i ~ None => Call(i,Nil) } def args = "(" ~> repsep(expr,",") <~ ")" - // END OF RULES - - def parse(s:String) = phrase(program)(new lexical.Scanner(s)) - - def parseTypeExpr(t:String) = phrase(typeExpr)(new lexical.Scanner(t)) match { - case Success(t, _) => t - case e: NoSuccess => - throw new ParserError(e.toString) - } - - def parseIPromptStmt(s:String) = { - phrase(iPromptStmt)(new lexical.Scanner(s)) match { - case Success(t, _) => t - case e: NoSuccess => - throw ParserError(e.toString) - } - } - - def parseExpr(s:String) = - phrase(expr)(new lexical.Scanner(s)) match { - case Success(t, _) => t - case e: NoSuccess => - throw new ParserError(e.toString) - } - - def apply(s:String) = { - parse(s) match { - case Success(tree, _) => tree - case e: NoSuccess => - throw ParserError(e.toString) - } - } - } diff --git a/src/vmlang/compiler/Simplify.scala b/src/vmlang/compiler/Simplify.scala index f552f1c..4bb4e8d 100644 --- a/src/vmlang/compiler/Simplify.scala +++ b/src/vmlang/compiler/Simplify.scala @@ -1,47 +1,75 @@ package vmlang.compiler import vmlang.compiler.ast._ -import collection.immutable.HashSet -// TODO: inline calls to functions like "a:Int = 2" +import collection.Set object Simplify { - def apply(prog:Map[String,Def]):Map[String,Def] = + type DefMap = Map[String,Def] + type FuncTable = Map[String,TypeExpr] + + def apply(env:Env):Env = + Env(inlineAll(simplifyAll(env.defs), Set() ++ env.ft.keySet.toList -- env.defs.keySet.toList), + env.ft, env.tt) + + def simplifyAll(defs:DefMap) = + applyToAllDefs(defs, simplify _) + + def inlineAll(defs:DefMap, rootNames:Set[String]) = Map[String,Def]() ++ - (prog map { case (name, d) => (name, Def(d.name, d.params, d.returnType, simplify(d.body))) }) + (applyToAllDefs(defs, { e => inline(e,defs,rootNames) }) filter { + case (_, d) => !d.body.isInstanceOf[Atom] }) + + def applyToAllDefs(defs:DefMap, f:(Expr) => Expr):DefMap = + Map[String,Def]() ++ (defs map { case (na, Def(n, ps, rt, b)) => (na, Def(n, ps, rt, f(b))) }) + + def inline(e:Expr, defs:DefMap, rootNames:Set[String]):Expr = + e match { + case a:Atom => a + case IfExpr(c, i, e) => + IfExpr(inline(c, defs, rootNames), inline(c, defs, rootNames), inline(c, defs, rootNames)) + case Call(name, args) => + if(rootNames contains name) + Call(name, args map { e => inline(e, defs, rootNames) }) + else + defs(name).body match { + case a:Atom => a + case _ => Call(name, args map { e => inline(e, defs, rootNames) }) + } + } def simplify(e:Expr):Expr = e match { case a:Atom => a case IfExpr(c,i,e) => (simplify(c), simplify(i), simplify(e)) match { case (Call("true",Nil), i, e) => i case (Call("false",Nil), i, e) => e case (c, i, e) => IfExpr(c, i, e) } case Call(n,args) => (n, args map simplify) match { case ("+" , List(IntLit(a),IntLit(b))) => IntLit(a + b) case ("-" , List(IntLit(a),IntLit(b))) => IntLit(a - b) case ("*" , List(IntLit(a),IntLit(b))) => IntLit(a * b) case ("/" , List(IntLit(a),IntLit(b))) => IntLit(a / b) case (">" , List(IntLit(a),IntLit(b))) => Call(if(a > b) "true" else "false", Nil) case (">=", List(IntLit(a),IntLit(b))) => Call(if(a >= b) "true" else "false", Nil) case ("<" , List(IntLit(a),IntLit(b))) => Call(if(a < b) "true" else "false", Nil) case ("<=", List(IntLit(a),IntLit(b))) => Call(if(a <= b) "true" else "false", Nil) case ("==", List(IntLit(a),IntLit(b))) => Call(if(a == b) "true" else "false", Nil) case ("not", List(Call("true",Nil))) => Call("false", Nil) case ("not", List(Call("false",Nil))) => Call("true", Nil) case ("and", List(Call(a,Nil),Call(b,Nil))) => Call(if(a == "true" && b == "true") "true" else "false", Nil) case ("or", List(Call(a,Nil),Call(b,Nil))) => Call(if(a == "true" || b == "true") "true" else "false", Nil) case (n, args) => Call(n, args) } } } diff --git a/src/vmlang/compiler/typecheck/TypeCheck.scala b/src/vmlang/compiler/typecheck/TypeCheck.scala index 357d344..63e8966 100644 --- a/src/vmlang/compiler/typecheck/TypeCheck.scala +++ b/src/vmlang/compiler/typecheck/TypeCheck.scala @@ -1,161 +1,162 @@ package vmlang.compiler.typecheck import vmlang.compiler.ast._ import collection.immutable.{ Map, HashMap } object TypeCheck { val typeTree = TypeTree(AbsType("Value",0),List( TypeTree(AbsType("Function",0),List( TypeTree(RefType("Function0",1),Nil), TypeTree(RefType("Function1",2),Nil), TypeTree(RefType("Function2",3),Nil), TypeTree(RefType("Function3",4),Nil), TypeTree(RefType("Function4",5),Nil), TypeTree(RefType("Function5",6),Nil), TypeTree(RefType("Function6",7),Nil), TypeTree(RefType("Function7",8),Nil), TypeTree(RefType("Function8",9),Nil), TypeTree(RefType("Function9",10),Nil))), TypeTree(PrimType("Int",4),Nil), TypeTree(PrimType("Bool",1),Nil), TypeTree(PrimType("Null",0),Nil))) type FuncTable = Map[String,TypeExpr] type Scope = Map[String,TypeExpr] val rootFuncTypes = new HashMap[String, TypeExpr] ++ (List( ("+" , "(Int, Int) => Int" ), ("-" , "(Int, Int) => Int" ), ("*" , "(Int, Int) => Int" ), ("/" , "(Int, Int) => Int" ), ("==" , "(Int, Int) => Bool" ), ("!=" , "(Int, Int) => Bool" ), (">" , "(Int, Int) => Bool" ), (">=" , "(Int, Int) => Bool" ), ("<" , "(Int, Int) => Bool" ), ("<=" , "(Int, Int) => Bool" ), ("true" , "() => Bool" ), ("false" , "() => Bool" ), ("null" , "() => Null" ), ("and" , "(Bool, Bool) => Bool" ), ("or" , "(Bool, Bool) => Bool" ), ("not" , "(Bool) => Bool" ), ("printInt" , "(Int) => Null" ) ) map { tp => (tp._1, Parse.parseTypeExpr(tp._2)) }) - def apply(defs:List[Def]):Map[String,Def] = + def apply(defs:List[Def]):Env = apply(defs, rootFuncTypes, typeTree) - def apply(defs:List[Def], ft:FuncTable, tt:TypeTree):Map[String,Def] = { + def apply(defs:List[Def], ft:FuncTable, tt:TypeTree):Env = { val (ds, dupErrors) = checkForDuplicates(defs) - (dupErrors ::: checkForValidMain(ds) ::: checkCompliance(ds, addTypeSigs(ft, defs), tt)) match { - case Nil => Map[String,Def]() ++ (ds map { d => (d.name, d) }) + val allFuncs = addTypeSigs(ft, defs) + (dupErrors ::: checkForValidMain(ds) ::: checkCompliance(ds, allFuncs, tt)) match { + case Nil => + val defs = Map[String,Def]() ++ (ds map { d => (d.name, d) }) + Env(defs, allFuncs, tt) case es => throw new TypeErrors(es.removeDuplicates) } } - private def checkForDuplicates(defs:List[Def]):(List[Def], List[TypeError]) = { + def checkForDuplicates(defs:List[Def]):(List[Def], List[TypeError]) = { val (nonDups, dups) = checkForDuplicates(Nil, defs) (nonDups, dups map { d => DuplicateDefError(d.name) }) } - private def checkForDuplicates(alreadyDefined:List[Def], defs:List[Def]):(List[Def], List[Def]) = + def checkForDuplicates(alreadyDefined:List[Def], defs:List[Def]):(List[Def], List[Def]) = defs match { case Nil => (alreadyDefined, Nil) case first :: rest => { if(alreadyDefined exists { _.name == first.name }) { val (restNonDups, restDups) = checkForDuplicates(alreadyDefined, rest) (restNonDups, first :: restDups) } else { checkForDuplicates(first :: alreadyDefined, rest) } } } - private def checkForValidMain(defs:List[Def]):List[TypeError] = + def checkForValidMain(defs:List[Def]):List[TypeError] = // check that main exists and is () => Null (defs find { _.name == "main" }) match { case Some(d) => (d.returnType == TypeExpr("Null",Nil) && d.params == Nil) match { case true => Nil case false => List(InvalidMainError(mkFuncTypeExpr(d))) } case None => List(NoMainError) } def addTypeSigs(ft:FuncTable, defs:List[Def]):FuncTable = defs.foldLeft(ft){ (ft, d) => ft + (d.name -> mkFuncTypeExpr(d)) } - private def mkFuncTypeExpr(d:Def):TypeExpr = + def mkFuncTypeExpr(d:Def):TypeExpr = TypeExpr("Function" + d.params.length, (d.params map { _.argType }) ::: List(d.returnType)) - private def checkCompliance(defs:List[Def], ft:FuncTable, tt:TypeTree):List[TypeError] = + def checkCompliance(defs:List[Def], ft:FuncTable, tt:TypeTree):List[TypeError] = defs flatMap { d => checkDef(d, ft, tt) } def checkDef(d:Def, ft:FuncTable, tt:TypeTree):List[TypeError] = { val scope = Map() ++ (d.params map { ps => (ps.name, ps.argType) }) (d.params flatMap { ps => tt.checkValidTypeExpr(ps.argType) }) ::: - (tt.checkValidTypeExpr(d.returnType)) ::: - (checkCalls(d.body, scope, ft, tt) match { - case Nil => tt.complies(d.returnType, inferType(d.body, scope, ft, tt)) - case l => l - }) + (tt.checkValidTypeExpr(d.returnType)) ::: + (tt.checkCompilableTypeExpr(d.returnType, { te => UncompilableTypeSpecError(te) })) ::: + (checkCalls(d.body, scope, ft, tt) match { + case Nil => tt.complies(d.returnType, inferType(d.body, scope, ft, tt)) + case l => l + }) } def checkCalls(e:Expr, s:Scope, ft:FuncTable, tt:TypeTree):List[TypeError] = e match { case a:Atom => Nil case IfExpr(i, c, e) => checkCalls(List(i, c, e), s, ft, tt) case c:Call => checkCall(c, s, ft, tt) } def checkCalls(es:List[Expr], s:Scope, ft:FuncTable, tt:TypeTree):List[TypeError] = es flatMap { e => checkCalls(e, s, ft, tt) } def checkCall(call:Call, scope:Scope, ft:FuncTable, tt:TypeTree):List[TypeError] = { val giv = call.args (scope get call.name) match { case Some(_) => Nil case None => (ft get call.name) match { case Some(funcType) => { val exp = funcType.args.init - if(exp.length == giv.length) + (if(exp.length == giv.length) Nil else - WrongNumCallArgs(call.name, exp.length, giv.length) :: + List(WrongNumCallArgs(call.name, exp.length, giv.length))) ::: checkArgCompliance(exp, giv, scope, ft, tt) } case None => NonexistentFuncError(call.name) :: checkCalls(call.args, scope, ft, tt) } } } def checkArgCompliance(expTypes:List[TypeExpr], args:List[Expr], s:Scope, ft:FuncTable, tt:TypeTree):List[TypeError] = checkCalls(args.dropRight(expTypes.length - args.length), s, ft, tt) ::: ((expTypes zip args) flatMap { case (et, e) => checkCalls(e, s, ft, tt) match { - case Nil => tt.complies(et, inferType(e, s, ft, tt)) + case Nil => + val inferredTypeExpr = inferType(e, s, ft, tt) + tt.complies(et, inferredTypeExpr) ::: + tt.checkCompilableTypeExpr(inferredTypeExpr, { te => UncompilableArgTypeError(te) }) case l => l } }) - def inferType(expr:Expr):TypeExpr = // for outside use - checkCalls(expr, Map[String,TypeExpr](), rootFuncTypes, typeTree) match { - case Nil => inferType(expr, Map(), rootFuncTypes, typeTree) - case es => throw TypeErrors(es) - } - def inferType(expr:Expr, s:Scope, ft:FuncTable, tt:TypeTree):TypeExpr = { expr match { case IntLit(_) => TypeExpr("Int",Nil) case CharLit(_) => TypeExpr("Char",Nil) case FloatLit(_) => TypeExpr("Float",Nil) case IfExpr(_, i, t) => tt.deepestCommonAncestor(inferType(i, s, ft, tt), inferType(t, s, ft, tt)) case c:Call => if(isParam(c, s)) s(c.name) else ft(c.name).args.last } } - private def isParam(call:Call, scope:Scope):Boolean = + def isParam(call:Call, scope:Scope):Boolean = call.args.isEmpty && (scope isDefinedAt call.name) } diff --git a/src/vmlang/compiler/typecheck/TypeErrors.scala b/src/vmlang/compiler/typecheck/TypeErrors.scala index 7e11335..2a80888 100644 --- a/src/vmlang/compiler/typecheck/TypeErrors.scala +++ b/src/vmlang/compiler/typecheck/TypeErrors.scala @@ -1,39 +1,49 @@ package vmlang.compiler.typecheck import vmlang.compiler.ast.TypeExpr case class TypeErrors(errors:List[CompilerError]) extends CompoundCompilerError(errors) abstract class TypeError extends NormalCompilerError case class NonexistentType(name:String) extends TypeError { val repr = "Nonexistent type: \"" + name + "\"" } case class Mismatch(expected:TypeExpr, given:TypeExpr) extends TypeError { val repr = "Type mismatch. Expected: " + expected.repr + "; given: " + given.repr } case class WrongNumTypeArgs(expected:Int, given:Int) extends TypeError { val repr = "Wrong number of type arguments. Expected: " + expected + "; given: " + given } case class WrongNumCallArgs(func:String, expected:Int, given:Int) extends TypeError { val repr = "Wrong number of arguments for " + func + ". Expected: " + expected + "; given: " + given } case class NonexistentFuncError(funcName:String) extends TypeError { val repr = "Call to nonexistent function " + funcName } case class DuplicateDefError(name:String) extends TypeError { val repr = "Function " + name + " already defined. Taking first definition." } case object NoMainError extends TypeError { val repr = "No main function. (Must be () => Null)" } case class InvalidMainError(te:TypeExpr) extends TypeError { val repr = "Function main is " + te + "; must be () => Null" } + +case class UncompilableTypeSpecError(te:TypeExpr) extends TypeError { + val repr = "Return type is " + te + + "; must be a primitive type or an abstract type with all reference types as subtypes" +} + +case class UncompilableArgTypeError(te:TypeExpr) extends TypeError { + val repr = "Type of argument is " + te + + "; must be a primitive type or an abstract type with all reference types as subtypes" +} diff --git a/src/vmlang/compiler/typecheck/TypeTree.scala b/src/vmlang/compiler/typecheck/TypeTree.scala index d14c3f2..61d708a 100644 --- a/src/vmlang/compiler/typecheck/TypeTree.scala +++ b/src/vmlang/compiler/typecheck/TypeTree.scala @@ -1,102 +1,122 @@ package vmlang.compiler.typecheck import vmlang.compiler.ast.TypeExpr // todo: make it work w/ type vars case class TypeTree(t:Type, subTypes:List[TypeTree]) { def complies(exp:TypeExpr, giv:TypeExpr):List[TypeError] = (checkValidTypeExpr(exp) ::: checkValidTypeExpr(giv)) match { case Nil => descends(exp.name, giv.name) match { case true => (exp.args zip giv.args) flatMap { p => complies(p._1, p._2) } case false => List(Mismatch(exp, giv)) } case es => es } - private def descends(e:String, g:String):Boolean = + def descends(e:String, g:String):Boolean = this findSubType e match { case Some(eTree) => eTree findSubType g match { case Some(gTree) => true case None => false } case None => throw new IllegalArgumentException("nonexistent type: " + e) } def deepestCommonAncestor(l:List[TypeExpr]):TypeExpr = l match { case Nil => throw new IllegalArgumentException("can't give DCA of empty list") case t :: Nil => t case t :: ts => deepestCommonAncestor(t,deepestCommonAncestor(ts)) } def deepestCommonAncestor(a:TypeExpr, b:TypeExpr):TypeExpr = { // TODO: this isn't really right for situations with different numbers of type args val (name, numArgs) = DCA(a.name, b.name) TypeExpr(name, ((a.args zip b.args) map { p => deepestCommonAncestor(p._1, p._2) }) take numArgs) } - private def DCA(a:String, b:String):(String,Int) = + def DCA(a:String, b:String):(String,Int) = ((path(a) zip path(b)) takeWhile { p => p._1 == p._2 }).last._1 - private def path(tn:String):List[(String,Int)] = + def path(tn:String):List[(String,Int)] = path(Nil,tn) match { case Some(l) => l case None => throw new NonexistentType(tn) } - private def path(path:List[(String,Int)], tn:String):Option[List[(String,Int)]] = + def path(path:List[(String,Int)], tn:String):Option[List[(String,Int)]] = if(tn == t.name) Some(path ::: List((t.name,t.numParams))) else if(isLeaf) None else subTypes.map(_.path(path,tn)).find(_.isInstanceOf[Some[List[String]]]) match { case Some(Some(p)) => Some(path ::: List((t.name,t.numParams)) ::: p) case Some(None) => None // would never happen... case None => None } + def checkCompilableTypeExpr(te:TypeExpr, error:(TypeExpr)=>TypeError):List[TypeError] = + findSubType(te.name) match { + case Some(TypeTree(t, subTypes)) => t match { + case at:AbsType => if(allAreRefTypes(subTypes)) Nil else List(error(te)) + case pt:PrimType => Nil + } + case None => Nil // always called after checkValidTypeExpr + } + + def allAreRefTypes(l:List[TypeTree]):Boolean = + l forall { case TypeTree(t, subTypes) => t.isInstanceOf[RefType] && allAreRefTypes(subTypes) } + def checkValidTypeExpr(te:TypeExpr):List[TypeError] = checkExistentAndNumArgs(te.name, te.args.length) ::: (te.args flatMap { a => checkValidTypeExpr(a) }) - private def checkExistentAndNumArgs(tn:String, numArgs:Int):List[TypeError] = + def getSize(te:TypeExpr):Int = + find(te.name) match { + // can assume that all subtypes of an AbsType will be reference types, + // since typechecker checks all arguments and return type specs with checkCompilableTypeExpr + case ty:AbsType => 4 + case ty:ConcreteType => ty.size + } + + def checkExistentAndNumArgs(tn:String, numArgs:Int):List[TypeError] = findSubType(tn) match { case None => List(NonexistentType(tn)) case Some(tree) => { val expNum = tree.t.numParams if(numArgs == expNum) Nil else List(WrongNumTypeArgs(expNum, numArgs)) } } - private def findSubType(tn:String):Option[TypeTree] = { + def findSubType(tn:String):Option[TypeTree] = { if(tn == t.name) Some(this) else if(isLeaf) None else subTypes.map(_ findSubType tn).find(_.isInstanceOf[Some[TypeTree]]) match { case Some(tree) => tree case None => None } } def find(tn:String):Type = { findSubType(tn) match { case Some(tt) => tt.t case None => throw NonexistentType(tn) } } def isLeaf = subTypes.isEmpty def prettyPrint:String = prettyPrint(0).mkString def prettyPrint(indent:Int):List[Char] = (" " * indent).toList ::: t.name.toList ::: List('\n') ::: ( subTypes flatMap { _ prettyPrint (indent + 2) }) }
vilterp/VMLang
469e2a7693cdde9ed70b5d5120998e9a09e2808a
typechecker fixes
diff --git a/bugs.txt b/bugs.txt index c221047..caa203b 100644 --- a/bugs.txt +++ b/bugs.txt @@ -1,29 +1,28 @@ COMPILER Overall - should be object-oriented -- will take care of overloading - - definitions with same name don't cause error Parser - can't parse floats or chars - use RegexParsers to make custom scanner - error messages will be hard - give location info to tokens, if possible - maybe use scala.io.Source (has fromString method) - then use custom scanner in existing parser - unary "not"s aren't parsed right Linearizer - function calls don't work - if statements aren't implemented - uses Type#size to compute instructions, but defs that take parameters with abstract types don't know what they will be called with! this computation must take place on a per-call basis, when argument types are known (note this makes CheckedDef useless) INTERACTIVE PROMPT - ":t <expr>" doesn't take user-defined functions into account - defining a function yields "No main function. (Must be () => Null)" - ":t myFunction" should give myFunction's type signature, not parse it as an expression - should save expressions typed in as "res{n}" diff --git a/src/vmlang/assembler/Main.scala b/src/vmlang/assembler/Main.scala index 74ede50..76b26e6 100644 --- a/src/vmlang/assembler/Main.scala +++ b/src/vmlang/assembler/Main.scala @@ -1,40 +1,21 @@ package vmlang.assembler -import vmlang.common.{OptParser, FatalError} - -import java.io.{File, FileOutputStream, FileNotFoundException, IOException} -import io.Source +import vmlang.common.optparser._ object Main extends OptParser { def numArgs(n:Int) = n == 1 val argErrorMsg = "supply 1 file to assemble" val knownFlags = List() val defaultOpts = Map[String,String]() val help = "usage: vmla <file to assemble>" def run(args:List[String], flags:List[String], opts:Map[String,String]):Unit = try { writeFile(Assemble(Parse(loadFile(args.head))), (args.head split '.')(0) + ".vmlc") } catch { case ParserError(msg) => throw FatalError("Parser Error: " + msg) case AssemblyError(msg) => throw FatalError("Assembly Error: " + msg) } - def writeFile(output:List[Byte], fileName:String):Unit = - try { - new FileOutputStream(new File(fileName)).write(output.toArray) - } catch { - case e:FileNotFoundException => throw FatalError("Error creating file " + fileName) - case e:IOException => throw FatalError("Error writing file " + fileName) - } - - def loadFile(fileName:String):String = - try { - Source.fromFile(fileName).getLines.mkString - } catch { - case e:FileNotFoundException => throw FatalError("File not found: " + fileName) - case e:IOException => throw FatalError("Error reading file " + fileName) - } - } diff --git a/src/vmlang/common/OptParser.scala b/src/vmlang/common/OptParser.scala index 4a503b8..b327a04 100644 --- a/src/vmlang/common/OptParser.scala +++ b/src/vmlang/common/OptParser.scala @@ -1,64 +1,100 @@ -package vmlang.common +package vmlang.common.optparser import collection.immutable.HashMap +import java.io.{File, FileOutputStream, FileInputStream, FileNotFoundException, IOException} +import scala.io.Source + abstract class OptParser { def numArgs(n:Int):Boolean val argErrorMsg:String val knownFlags:List[String] val defaultOpts:Map[String,String] val help:String def run(args:List[String], flags:List[String], opts:Map[String,String]):Unit def main(as:Array[String]) = { val (args, flags, opts) = parse(as) // check num args if(!numArgs(args.length)) { println(argErrorMsg) println(help) } else { // check for unknown flags flags -- knownFlags match { case Nil => { // check for unknown opts opts.keySet.toList -- defaultOpts.keySet.toList match { case Nil => { // get opts val allOpts = defaultOpts ++ opts // run try { run(args, flags, allOpts) } catch { case FatalError(msg) => println(msg) } } case l:List[String] => { println("Unknown options: " + (l mkString ", ")) println(help) } } } case l:List[String] => { println("Unkown flags: " + (l mkString ", ")) println(help) } } } } private def parse(as:Array[String]) = { val (dashStarts, args) = as.toList partition { _ startsWith "-" } val (optArgs, flags) = dashStarts partition { _ exists { _ == '=' } } val opts = new HashMap[String,String] ++ (optArgs map { a => { val s = (a substring 1) split '='; (s(0), s(1)) } } ) (args, flags map { _ substring 1 }, opts) } + def loadFileBytes(fileName:String):Array[Byte] = { + try { + val in = new FileInputStream(new File(fileName)) + val result = new Array[Byte](in.available) + in.read(result) + result + } catch { + case e:FileNotFoundException => + throw FatalError("File not found: " + fileName) + case e:IOException => + throw FatalError("Error reading file " + fileName) + } + } + + def writeFile(output:Array[Byte], fileName:String):Unit = + try { + new FileOutputStream(new File(fileName)).write(output) + } catch { + case e:FileNotFoundException => throw FatalError("Error creating file " + fileName) + case e:IOException => throw FatalError("Error writing file " + fileName) + } + + def writeFile(output:List[Byte], fileName:String):Unit = + writeFile(output.toArray, fileName) + + def loadFile(fileName:String):String = + try { + Source.fromFile(fileName).getLines.mkString + } catch { + case e:FileNotFoundException => throw FatalError("File not found: " + fileName) + case e:IOException => throw FatalError("Error reading file " + fileName) + } + } case class FatalError(msg:String) extends Exception diff --git a/src/vmlang/compiler/Main.scala b/src/vmlang/compiler/Main.scala index e186072..5bba48a 100644 --- a/src/vmlang/compiler/Main.scala +++ b/src/vmlang/compiler/Main.scala @@ -1,80 +1,63 @@ -package vmlang.compiler - -import vmlang.common.{OptParser, FatalError} -import vmlang.compiler.typecheck.TypeCheck -import vmlang.compiler.ast._ -import vmlang.vm.{VM, VMError} - -import collection.mutable.HashMap - -import java.util.Scanner -import java.io.{File, FileOutputStream, FileNotFoundException, IOException} -import io.Source - -object Main extends OptParser { - - def numArgs(n:Int) = n == 0 || n == 1 - val argErrorMsg = "supply 1 file to compile, or no argument for interactive prompt" - val knownFlags = List("v") - val defaultOpts = Map[String,String]() - val help = "usage: vmlc <optional source file> <options>\n" + - "-v print out messages about what the compiler is doing" - - def run(args:List[String], flags:List[String], opts:Map[String,String]):Unit = - args match { - case Nil => runIPrompt - case List(fn) => - try { - writeFile(Compile(loadFile(fn)), (fn split '.')(0) + ".vmlc") - } catch { - case e:CompilerError => throw FatalError(e.repr) - } - } - - def runIPrompt = { - val s = new Scanner(System.in) - var counter = 0 - var defs = Map[String,Def]() - while(true) { - print(">> ") - try { - val input = s.nextLine - if(input startsWith ":t ") { - println(TypeCheck.inferType(Parse.parseExpr(input substring 3))) - } else { - Parse.parseIPromptStmt(input) match { - case e:Expr => - defs = defs + ("main" -> Def("main", Nil, TypeExpr("Null",Nil), e match { - case Call("printInt",args) => e - case expr => Call("printInt",List(expr)) - })) - case d:Def => - defs = defs + (d.name -> d) - } - val code = Linearize(Simplify(TypeCheck(Prog(defs)))) - new VM(code, 1024, 1024).run - } - } catch { - case e:CompilerError => println(e.repr) - case e:VMError => println(e.getMessage) - } - } - } - - def writeFile(output:Array[Byte], fileName:String):Unit = - try { - new FileOutputStream(new File(fileName)).write(output) - } catch { - case e:FileNotFoundException => throw FatalError("Error creating file " + fileName) - case e:IOException => throw FatalError("Error writing file " + fileName) - } - - def loadFile(fileName:String):String = - try { - Source.fromFile(fileName).getLines.mkString - } catch { - case e:FileNotFoundException => throw FatalError("File not found: " + fileName) - case e:IOException => throw FatalError("Error reading file " + fileName) - } - -} +// package vmlang.compiler +// +// import vmlang.common.optparser._ +// +// import vmlang.compiler.typecheck.TypeCheck +// import vmlang.compiler.ast._ +// import vmlang.vm.{VM, VMError} +// +// import java.util.Scanner +// +// import collection.mutable.HashMap +// +// object Main extends OptParser { +// +// def numArgs(n:Int) = n == 0 || n == 1 +// val argErrorMsg = "supply 1 file to compile, or no argument for interactive prompt" +// val knownFlags = List("v") +// val defaultOpts = Map[String,String]() +// val help = "usage: vmlc <optional source file> <options>\n" + +// "-v print out messages about what the compiler is doing" +// +// def run(args:List[String], flags:List[String], opts:Map[String,String]):Unit = +// args match { +// case Nil => runIPrompt +// case List(fn) => +// try { +// writeFile(Compile(loadFile(fn)), (fn split '.')(0) + ".vmlc") +// } catch { +// case e:CompilerError => throw FatalError(e.repr) +// } +// } +// +// def runIPrompt = { +// val s = new Scanner(System.in) +// var counter = 0 +// var defs = Map[String,Def]() +// while(true) { +// print(">> ") +// try { +// val input = s.nextLine +// if(input startsWith ":t ") { +// println(TypeCheck.inferType(Parse.parseExpr(input substring 3))) +// } else { +// Parse.parseIPromptStmt(input) match { +// case e:Expr => +// defs = defs + ("main" -> Def("main", Nil, TypeExpr("Null",Nil), e match { +// case Call("printInt",args) => e +// case expr => Call("printInt",List(expr)) +// })) +// case d:Def => +// defs = defs + (d.name -> d) +// } +// val code = Linearize(Simplify(TypeCheck(Prog(defs)))) +// new VM(code, 1024, 1024).run +// } +// } catch { +// case e:CompilerError => println(e.repr) +// case e:VMError => println(e.getMessage) +// } +// } +// } +// +// } diff --git a/src/vmlang/compiler/Parse.scala b/src/vmlang/compiler/Parse.scala index 05f9ce8..847ada4 100644 --- a/src/vmlang/compiler/Parse.scala +++ b/src/vmlang/compiler/Parse.scala @@ -1,140 +1,139 @@ package vmlang.compiler import vmlang.compiler.ast._ import util.parsing.combinator.syntactical._ import runtime.RichString import collection.immutable.HashMap case class ParserError(msg:String) extends NormalCompilerError { val repr = "Parser Error: " + msg } case object TooManyParams extends ParserError("can't make a function with more than 9 params") object Parse extends StandardTokenParsers { lexical.delimiters ++= List("+","-","*","/","(",")","[","]","=","=>",":",",",">","<", ">=","<=","==","!","!=") lexical.reserved ++= List("if","then","else","and","or") // RULES - // TODO: duplicates get run over... - def program = (definition *) ^^ { l => Prog(new HashMap[String,Def] ++ { l map { d => (d.name, d) } }) } + def program = definition + def iPromptStmt = ( definition | expr ) def definition = ident ~ (paramsSpec?) ~ typeSpec ~ ("=" ~> expr) ^^ { case i ~ Some(ps) ~ rt ~ e => Def(i, checkPs(ps), rt, e) case i ~ None ~ rt ~ e => Def(i, Nil, rt, e) } def checkPs(ps:List[ParamSpec]) = if(ps.length <= 9) ps else throw TooManyParams def paramsSpec = "(" ~> repsep(paramSpec, ",") <~ ")" def paramSpec = ident ~ typeSpec ^^ { case i ~ t => ParamSpec(i,t) } def typeSpec = ":" ~> typeExpr def typeExpr:Parser[TypeExpr] = ( normalTypeExpr | funcTypeExpr ) def normalTypeExpr:Parser[TypeExpr] = ident ~ (typeParams?) ^^ { case i ~ Some(tp) => TypeExpr(i, tp) case i ~ None => TypeExpr(i, Nil) } def funcTypeExpr:Parser[TypeExpr] = ("(" ~> repsep(typeExpr,",") <~ ")") ~ ("=>" ~> typeExpr) ^^ { case pts ~ rt => mkFuncTypeExpr(pts, rt) } def mkFuncTypeExpr(paramTypes:List[TypeExpr], returnType:TypeExpr):TypeExpr = if(paramTypes.length <= 9) TypeExpr("Function" + paramTypes.length, paramTypes ::: List(returnType)) else throw TooManyParams def typeParams = "[" ~> repsep(typeExpr,",") <~ "]" def expr:Parser[Expr] = ( ifStatement | orExpr ) def ifStatement = (("if" ~> orExpr) ~ ("then" ~> orExpr) ~ ("else" ~> orExpr)) ^^ { case c ~ i ~ e => IfExpr(c,i,e) } def orExpr = andExpr * ( "or" ^^^ { (a:Expr, b:Expr) => Call("or",List(a,b)) } ) def andExpr = comparison * ( "and" ^^^ { (a:Expr, b:Expr) => Call("and",List(a,b)) } ) def comparison = sum * ( ">" ^^^ { (a:Expr, b:Expr) => Call(">",List(a,b)) } | "<" ^^^ { (a:Expr, b:Expr) => Call("<",List(a,b)) } | "==" ^^^ { (a:Expr, b:Expr) => Call("==",List(a,b)) } | "<=" ^^^ { (a:Expr, b:Expr) => Call("<=",List(a,b)) } | ">=" ^^^ { (a:Expr, b:Expr) => Call(">=",List(a,b)) } | "!=" ^^^ { (a:Expr, b:Expr) => Call("!=",List(a,b)) } ) // I'm sure there's a super-elegant way to do this, // but my Scala chops aren't up to it yet def sum = product * ( "+" ^^^ { (a:Expr, b:Expr) => Call("+",List(a,b)) } | "-" ^^^ { (a:Expr, b:Expr) => Call("-",List(a,b)) } ) def product = atom * ( "*" ^^^ { (a:Expr, b:Expr) => Call("*",List(a,b)) } | "/" ^^^ { (a:Expr, b:Expr) => Call("/",List(a,b)) } ) def atom = ( int | list | string | call | parenthesizedExpr | unaryMinus | unaryNot ) // todo: char lit (not in standardtokenparsers...) def list = "[" ~> repsep(expr,",") <~ "]" ^^ concatIze def string = stringLit ^^ { (s:String) => concatIze(new RichString(s) map { CharLit(_) }) } def concatIze(items:Seq[Expr]):Expr = items.foldRight(Call("EmptyList",Nil).asInstanceOf[Expr]){ (i,a) => Call(":",List(i,a)) } def parenthesizedExpr = "(" ~> expr <~ ")" def unaryNot:Parser[Expr] = "not" ~> atom ^^ { a => Call("not",List(a)) } def unaryMinus:Parser[Expr] = "-" ~> atom ^^ { a => Call("*",List(a,IntLit(-1))) } def int = numericLit ^^ { s => IntLit(s.toInt) } def call = ident ~ (args ?) ^^ { case i ~ Some(a) => Call(i,a) case i ~ None => Call(i,Nil) } def args = "(" ~> repsep(expr,",") <~ ")" // END OF RULES def parse(s:String) = phrase(program)(new lexical.Scanner(s)) def parseTypeExpr(t:String) = phrase(typeExpr)(new lexical.Scanner(t)) match { case Success(t, _) => t case e: NoSuccess => throw new ParserError(e.toString) } def parseIPromptStmt(s:String) = { phrase(iPromptStmt)(new lexical.Scanner(s)) match { case Success(t, _) => t case e: NoSuccess => throw ParserError(e.toString) } } def parseExpr(s:String) = phrase(expr)(new lexical.Scanner(s)) match { case Success(t, _) => t case e: NoSuccess => throw new ParserError(e.toString) } def apply(s:String) = { parse(s) match { case Success(tree, _) => tree case e: NoSuccess => throw ParserError(e.toString) } } } diff --git a/src/vmlang/compiler/Simplify.scala b/src/vmlang/compiler/Simplify.scala index 05ddcfd..f552f1c 100644 --- a/src/vmlang/compiler/Simplify.scala +++ b/src/vmlang/compiler/Simplify.scala @@ -1,47 +1,47 @@ package vmlang.compiler import vmlang.compiler.ast._ import collection.immutable.HashSet // TODO: inline calls to functions like "a:Int = 2" object Simplify { - def apply(prog:Map[String,CheckedDef]) = - Map[String,CheckedDef]() ++ - (prog map { m => (m._1 -> CheckedDef(m._2.params, simplify(m._2.body))) }) + def apply(prog:Map[String,Def]):Map[String,Def] = + Map[String,Def]() ++ + (prog map { case (name, d) => (name, Def(d.name, d.params, d.returnType, simplify(d.body))) }) def simplify(e:Expr):Expr = e match { case a:Atom => a case IfExpr(c,i,e) => (simplify(c), simplify(i), simplify(e)) match { case (Call("true",Nil), i, e) => i case (Call("false",Nil), i, e) => e case (c, i, e) => IfExpr(c, i, e) } case Call(n,args) => (n, args map simplify) match { case ("+" , List(IntLit(a),IntLit(b))) => IntLit(a + b) case ("-" , List(IntLit(a),IntLit(b))) => IntLit(a - b) case ("*" , List(IntLit(a),IntLit(b))) => IntLit(a * b) case ("/" , List(IntLit(a),IntLit(b))) => IntLit(a / b) case (">" , List(IntLit(a),IntLit(b))) => Call(if(a > b) "true" else "false", Nil) case (">=", List(IntLit(a),IntLit(b))) => Call(if(a >= b) "true" else "false", Nil) case ("<" , List(IntLit(a),IntLit(b))) => Call(if(a < b) "true" else "false", Nil) case ("<=", List(IntLit(a),IntLit(b))) => Call(if(a <= b) "true" else "false", Nil) case ("==", List(IntLit(a),IntLit(b))) => Call(if(a == b) "true" else "false", Nil) case ("not", List(Call("true",Nil))) => Call("false", Nil) case ("not", List(Call("false",Nil))) => Call("true", Nil) case ("and", List(Call(a,Nil),Call(b,Nil))) => Call(if(a == "true" && b == "true") "true" else "false", Nil) case ("or", List(Call(a,Nil),Call(b,Nil))) => Call(if(a == "true" || b == "true") "true" else "false", Nil) case (n, args) => Call(n, args) } } } diff --git a/src/vmlang/compiler/typecheck/TypeCheck.scala b/src/vmlang/compiler/typecheck/TypeCheck.scala index a7010d6..357d344 100644 --- a/src/vmlang/compiler/typecheck/TypeCheck.scala +++ b/src/vmlang/compiler/typecheck/TypeCheck.scala @@ -1,138 +1,161 @@ package vmlang.compiler.typecheck import vmlang.compiler.ast._ import collection.immutable.{ Map, HashMap } object TypeCheck { val typeTree = TypeTree(AbsType("Value",0),List( TypeTree(AbsType("Function",0),List( TypeTree(RefType("Function0",1),Nil), TypeTree(RefType("Function1",2),Nil), TypeTree(RefType("Function2",3),Nil), TypeTree(RefType("Function3",4),Nil), TypeTree(RefType("Function4",5),Nil), TypeTree(RefType("Function5",6),Nil), TypeTree(RefType("Function6",7),Nil), TypeTree(RefType("Function7",8),Nil), TypeTree(RefType("Function8",9),Nil), TypeTree(RefType("Function9",10),Nil))), TypeTree(PrimType("Int",4),Nil), TypeTree(PrimType("Bool",1),Nil), TypeTree(PrimType("Null",0),Nil))) type FuncTable = Map[String,TypeExpr] type Scope = Map[String,TypeExpr] val rootFuncTypes = new HashMap[String, TypeExpr] ++ (List( ("+" , "(Int, Int) => Int" ), ("-" , "(Int, Int) => Int" ), ("*" , "(Int, Int) => Int" ), ("/" , "(Int, Int) => Int" ), ("==" , "(Int, Int) => Bool" ), ("!=" , "(Int, Int) => Bool" ), (">" , "(Int, Int) => Bool" ), (">=" , "(Int, Int) => Bool" ), ("<" , "(Int, Int) => Bool" ), ("<=" , "(Int, Int) => Bool" ), ("true" , "() => Bool" ), ("false" , "() => Bool" ), ("null" , "() => Null" ), ("and" , "(Bool, Bool) => Bool" ), ("or" , "(Bool, Bool) => Bool" ), ("not" , "(Bool) => Bool" ), ("printInt" , "(Int) => Null" ) ) map { tp => (tp._1, Parse.parseTypeExpr(tp._2)) }) - def apply(prog:Prog):Map[String,CheckedDef] = - apply(prog, rootFuncTypes, typeTree) - - def apply(prog:Prog, ft:FuncTable, tt:TypeTree):Map[String,CheckedDef] = - (checkForMain(prog) ::: checkCompliance(prog, addTypeSigs(ft, prog), tt)) match { - case Nil => Map[String,CheckedDef]() ++ (prog.defs map { - case (n, d) => (n -> CheckedDef(d.params map { ps => { - (ps.name, (tt find ps.argType.name).size) - } }, d.body) ) - }) - case l => throw new TypeErrors(l) + def apply(defs:List[Def]):Map[String,Def] = + apply(defs, rootFuncTypes, typeTree) + + def apply(defs:List[Def], ft:FuncTable, tt:TypeTree):Map[String,Def] = { + val (ds, dupErrors) = checkForDuplicates(defs) + (dupErrors ::: checkForValidMain(ds) ::: checkCompliance(ds, addTypeSigs(ft, defs), tt)) match { + case Nil => Map[String,Def]() ++ (ds map { d => (d.name, d) }) + case es => throw new TypeErrors(es.removeDuplicates) + } + } + + private def checkForDuplicates(defs:List[Def]):(List[Def], List[TypeError]) = { + val (nonDups, dups) = checkForDuplicates(Nil, defs) + (nonDups, dups map { d => DuplicateDefError(d.name) }) + } + + private def checkForDuplicates(alreadyDefined:List[Def], defs:List[Def]):(List[Def], List[Def]) = + defs match { + case Nil => (alreadyDefined, Nil) + case first :: rest => { + if(alreadyDefined exists { _.name == first.name }) { + val (restNonDups, restDups) = checkForDuplicates(alreadyDefined, rest) + (restNonDups, first :: restDups) + } else { + checkForDuplicates(first :: alreadyDefined, rest) + } + } } - private def checkForMain(prog:Prog):List[TypeError] = - (prog.defs get "main") match { + private def checkForValidMain(defs:List[Def]):List[TypeError] = + // check that main exists and is () => Null + (defs find { _.name == "main" }) match { case Some(d) => (d.returnType == TypeExpr("Null",Nil) && d.params == Nil) match { case true => Nil case false => List(InvalidMainError(mkFuncTypeExpr(d))) } case None => List(NoMainError) } - private def addTypeSigs(ft:FuncTable, p:Prog):FuncTable = - p.defs.foldLeft(ft){ (ft, d) => ft + (d._1 -> mkFuncTypeExpr(d._2)) } + def addTypeSigs(ft:FuncTable, defs:List[Def]):FuncTable = + defs.foldLeft(ft){ (ft, d) => ft + (d.name -> mkFuncTypeExpr(d)) } private def mkFuncTypeExpr(d:Def):TypeExpr = TypeExpr("Function" + d.params.length, (d.params map { _.argType }) ::: List(d.returnType)) - private def checkCompliance(p:Prog, ft:FuncTable, tt:TypeTree):List[TypeError] = - p.defs.toList flatMap { m => checkDef(m._2, ft, tt) } + private def checkCompliance(defs:List[Def], ft:FuncTable, tt:TypeTree):List[TypeError] = + defs flatMap { d => checkDef(d, ft, tt) } - private def checkDef(d:Def, ft:FuncTable, tt:TypeTree):List[TypeError] = { - val s = Map() ++ (d.params map { ps => (ps.name, ps.argType) }) - checkCalls(d.body, s, ft, tt) match { - case Nil => tt.complies(d.returnType, inferType(d.body, s, ft, tt)) + def checkDef(d:Def, ft:FuncTable, tt:TypeTree):List[TypeError] = { + val scope = Map() ++ (d.params map { ps => (ps.name, ps.argType) }) + (d.params flatMap { ps => tt.checkValidTypeExpr(ps.argType) }) ::: + (tt.checkValidTypeExpr(d.returnType)) ::: + (checkCalls(d.body, scope, ft, tt) match { + case Nil => tt.complies(d.returnType, inferType(d.body, scope, ft, tt)) case l => l - } + }) } - private def checkCalls(e:Expr, s:Scope, ft:FuncTable, tt:TypeTree):List[TypeError] = + def checkCalls(e:Expr, s:Scope, ft:FuncTable, tt:TypeTree):List[TypeError] = e match { case a:Atom => Nil case IfExpr(i, c, e) => checkCalls(List(i, c, e), s, ft, tt) case c:Call => checkCall(c, s, ft, tt) } - private def checkCalls(es:List[Expr], s:Scope, ft:FuncTable, tt:TypeTree):List[TypeError] = + def checkCalls(es:List[Expr], s:Scope, ft:FuncTable, tt:TypeTree):List[TypeError] = es flatMap { e => checkCalls(e, s, ft, tt) } def checkCall(call:Call, scope:Scope, ft:FuncTable, tt:TypeTree):List[TypeError] = { val giv = call.args (scope get call.name) match { case Some(_) => Nil case None => (ft get call.name) match { case Some(funcType) => { val exp = funcType.args.init - (if(exp.length == giv.length) Nil else List(WrongNumCallArgs(exp.length, giv.length))) ::: - checkArgCompliance(exp, giv, scope, ft, tt) + if(exp.length == giv.length) + Nil + else + WrongNumCallArgs(call.name, exp.length, giv.length) :: + checkArgCompliance(exp, giv, scope, ft, tt) } - case None => List(NonexistentFuncError(call.name)) + case None => NonexistentFuncError(call.name) :: checkCalls(call.args, scope, ft, tt) } } } - private def checkArgCompliance(expTypes:List[TypeExpr], args:List[Expr], + def checkArgCompliance(expTypes:List[TypeExpr], args:List[Expr], s:Scope, ft:FuncTable, tt:TypeTree):List[TypeError] = - (expTypes zip args) flatMap { case (et, e) => checkCalls(e, s, ft, tt) match { + checkCalls(args.dropRight(expTypes.length - args.length), s, ft, tt) ::: + ((expTypes zip args) flatMap { case (et, e) => checkCalls(e, s, ft, tt) match { case Nil => tt.complies(et, inferType(e, s, ft, tt)) case l => l - } } + } }) def inferType(expr:Expr):TypeExpr = // for outside use checkCalls(expr, Map[String,TypeExpr](), rootFuncTypes, typeTree) match { case Nil => inferType(expr, Map(), rootFuncTypes, typeTree) case es => throw TypeErrors(es) } - private def inferType(expr:Expr, s:Scope, ft:FuncTable, tt:TypeTree):TypeExpr = { + def inferType(expr:Expr, s:Scope, ft:FuncTable, tt:TypeTree):TypeExpr = { expr match { case IntLit(_) => TypeExpr("Int",Nil) case CharLit(_) => TypeExpr("Char",Nil) case FloatLit(_) => TypeExpr("Float",Nil) case IfExpr(_, i, t) => tt.deepestCommonAncestor(inferType(i, s, ft, tt), inferType(t, s, ft, tt)) case c:Call => if(isParam(c, s)) s(c.name) else ft(c.name).args.last } } private def isParam(call:Call, scope:Scope):Boolean = call.args.isEmpty && (scope isDefinedAt call.name) } diff --git a/src/vmlang/compiler/typecheck/TypeErrors.scala b/src/vmlang/compiler/typecheck/TypeErrors.scala index 170c07f..7e11335 100644 --- a/src/vmlang/compiler/typecheck/TypeErrors.scala +++ b/src/vmlang/compiler/typecheck/TypeErrors.scala @@ -1,39 +1,39 @@ package vmlang.compiler.typecheck import vmlang.compiler.ast.TypeExpr case class TypeErrors(errors:List[CompilerError]) extends CompoundCompilerError(errors) abstract class TypeError extends NormalCompilerError case class NonexistentType(name:String) extends TypeError { val repr = "Nonexistent type: \"" + name + "\"" } case class Mismatch(expected:TypeExpr, given:TypeExpr) extends TypeError { val repr = "Type mismatch. Expected: " + expected.repr + "; given: " + given.repr } case class WrongNumTypeArgs(expected:Int, given:Int) extends TypeError { val repr = "Wrong number of type arguments. Expected: " + expected + "; given: " + given } -case class WrongNumCallArgs(expected:Int, given:Int) extends TypeError { - val repr = "Wrong number of arguments. Expected: " + expected + "; given: " + given +case class WrongNumCallArgs(func:String, expected:Int, given:Int) extends TypeError { + val repr = "Wrong number of arguments for " + func + ". Expected: " + expected + "; given: " + given } case class NonexistentFuncError(funcName:String) extends TypeError { val repr = "Call to nonexistent function " + funcName } case class DuplicateDefError(name:String) extends TypeError { - val repr = "Two definitions with same name: " + name + val repr = "Function " + name + " already defined. Taking first definition." } case object NoMainError extends TypeError { val repr = "No main function. (Must be () => Null)" } case class InvalidMainError(te:TypeExpr) extends TypeError { val repr = "Function main is " + te + "; must be () => Null" } diff --git a/src/vmlang/compiler/typecheck/TypeTree.scala b/src/vmlang/compiler/typecheck/TypeTree.scala index 8185bee..d14c3f2 100644 --- a/src/vmlang/compiler/typecheck/TypeTree.scala +++ b/src/vmlang/compiler/typecheck/TypeTree.scala @@ -1,101 +1,102 @@ package vmlang.compiler.typecheck import vmlang.compiler.ast.TypeExpr // todo: make it work w/ type vars case class TypeTree(t:Type, subTypes:List[TypeTree]) { def complies(exp:TypeExpr, giv:TypeExpr):List[TypeError] = (checkValidTypeExpr(exp) ::: checkValidTypeExpr(giv)) match { case Nil => descends(exp.name, giv.name) match { case true => (exp.args zip giv.args) flatMap { p => complies(p._1, p._2) } case false => List(Mismatch(exp, giv)) } case es => es } private def descends(e:String, g:String):Boolean = this findSubType e match { case Some(eTree) => eTree findSubType g match { case Some(gTree) => true case None => false } case None => throw new IllegalArgumentException("nonexistent type: " + e) } def deepestCommonAncestor(l:List[TypeExpr]):TypeExpr = l match { case Nil => throw new IllegalArgumentException("can't give DCA of empty list") case t :: Nil => t case t :: ts => deepestCommonAncestor(t,deepestCommonAncestor(ts)) } def deepestCommonAncestor(a:TypeExpr, b:TypeExpr):TypeExpr = { // TODO: this isn't really right for situations with different numbers of type args val (name, numArgs) = DCA(a.name, b.name) TypeExpr(name, ((a.args zip b.args) map { p => deepestCommonAncestor(p._1, p._2) }) take numArgs) } private def DCA(a:String, b:String):(String,Int) = ((path(a) zip path(b)) takeWhile { p => p._1 == p._2 }).last._1 private def path(tn:String):List[(String,Int)] = path(Nil,tn) match { case Some(l) => l case None => throw new NonexistentType(tn) } private def path(path:List[(String,Int)], tn:String):Option[List[(String,Int)]] = if(tn == t.name) Some(path ::: List((t.name,t.numParams))) else if(isLeaf) None else subTypes.map(_.path(path,tn)).find(_.isInstanceOf[Some[List[String]]]) match { case Some(Some(p)) => Some(path ::: List((t.name,t.numParams)) ::: p) case Some(None) => None // would never happen... case None => None } - private def checkValidTypeExpr(te:TypeExpr):List[TypeError] = - checkExistentAndNumArgs(te.name, te.args.length) ::: (te.args flatMap { a => checkValidTypeExpr(a) }) + def checkValidTypeExpr(te:TypeExpr):List[TypeError] = + checkExistentAndNumArgs(te.name, te.args.length) ::: + (te.args flatMap { a => checkValidTypeExpr(a) }) private def checkExistentAndNumArgs(tn:String, numArgs:Int):List[TypeError] = findSubType(tn) match { case None => List(NonexistentType(tn)) case Some(tree) => { val expNum = tree.t.numParams if(numArgs == expNum) Nil else List(WrongNumTypeArgs(expNum, numArgs)) } } private def findSubType(tn:String):Option[TypeTree] = { if(tn == t.name) Some(this) else if(isLeaf) None else subTypes.map(_ findSubType tn).find(_.isInstanceOf[Some[TypeTree]]) match { case Some(tree) => tree case None => None } } def find(tn:String):Type = { findSubType(tn) match { case Some(tt) => tt.t case None => throw NonexistentType(tn) } } def isLeaf = subTypes.isEmpty def prettyPrint:String = prettyPrint(0).mkString def prettyPrint(indent:Int):List[Char] = (" " * indent).toList ::: t.name.toList ::: List('\n') ::: ( subTypes flatMap { _ prettyPrint (indent + 2) }) } diff --git a/src/vmlang/disassembler/Main.scala b/src/vmlang/disassembler/Main.scala index 9ef0413..d0d1f2e 100644 --- a/src/vmlang/disassembler/Main.scala +++ b/src/vmlang/disassembler/Main.scala @@ -1,46 +1,47 @@ package vmlang.disassembler -import vmlang.common.{OptParser, FatalError, Opcodes} +import vmlang.common.optparser._ +import vmlang.common.Opcodes import vmlang.common.Opcodes._ import java.io.{File, FileInputStream, DataInputStream, FileNotFoundException, IOException, EOFException} object Main extends OptParser { def numArgs(n:Int) = n == 1 val argErrorMsg = "supply 1 bytecode file to disassemble" val knownFlags = List() val defaultOpts = Map[String,String]() val help = "usage: vmld <bytecode file>\n" def run(args:List[String], flags:List[String], opts:Map[String,String]):Unit = disassemble(args.head) def disassemble(fileName:String) = try { var addr = 0 val in = new DataInputStream(new FileInputStream(new File(fileName))) val ocs = Opcodes.values while(in.available > 0) { print(addr + "\t") val oc = ocs(in.readByte) addr += 1 print(oc + "\t") oc match { case I_CONST_A => print(in.readInt); addr += 4 case I_CONST_B => print(in.readInt); addr += 4 case B_CONST_A => print(in.readByte); addr += 1 case B_CONST_B => print(in.readByte); addr += 1 case GOTO => print(in.readInt); addr += 4 case _ => } println } } catch { case e:FileNotFoundException => throw FatalError("File not found: " + fileName) case e:EOFException => throw FatalError("malformed program") case e:ArrayIndexOutOfBoundsException => throw FatalError("malformed program") case e:IOException => throw FatalError("Error reading file " + fileName) } } diff --git a/src/vmlang/vm/Main.scala b/src/vmlang/vm/Main.scala index adde4c2..11d2aca 100644 --- a/src/vmlang/vm/Main.scala +++ b/src/vmlang/vm/Main.scala @@ -1,51 +1,36 @@ package vmlang.vm -import java.io.{File, FileInputStream, FileNotFoundException, IOException} -import vmlang.common.{OptParser, FatalError} +import vmlang.common.optparser._ object Main extends OptParser { def numArgs(n:Int) = n == 1 val argErrorMsg = "supply 1 bytecode file to run" val knownFlags = List() val defaultOpts = Map("heap_size" -> "1024", "stack_size" -> "1024") val help = "usage: vml <bytecode file> <options>\n" + "-heap_size=<num bytes> heap size in bytes\n" + "-stack_size=<num bytes> stack size in bytes" def run(args:List[String], flags:List[String], opts:Map[String,String]):Unit = { val heapSize = try { opts("heap_size").toInt } catch { case e:NumberFormatException => throw FatalError("Invalid heap size argument") } val stackSize = try { opts("stack_size").toInt } catch { case e:NumberFormatException => throw FatalError("Invalid stack size argument") } // business time try { new VM(loadFileBytes(args(0)), heapSize, stackSize).run } catch { case e:InitError => throw FatalError("Couldn't start VM: " + e.message) case e:MalformedProgramError => throw FatalError("VM error: malformed program") case e:StackOverflowError => throw FatalError("VM error: stack overflow") } } - def loadFileBytes(fileName:String):Array[Byte] = { - try { - val in = new FileInputStream(new File(fileName)) - val result = new Array[Byte](in.available) - in.read(result) - result - } catch { - case e:FileNotFoundException => - throw FatalError("File not found: " + fileName) - case e:IOException => - throw FatalError("Error reading file " + fileName) - } - } - }
vilterp/VMLang
ffe69350b9281d879ba4ed442c5f707ecc0b40de
added simple assembler
diff --git a/examples/test.vmla b/examples/test.vmla new file mode 100644 index 0000000..8b0cde2 --- /dev/null +++ b/examples/test.vmla @@ -0,0 +1,3 @@ +I_CONST_A 42 +PRINT_INT_A +STOP diff --git a/examples/test.vmlc b/examples/test.vmlc index 6725108..9c7d118 100644 Binary files a/examples/test.vmlc and b/examples/test.vmlc differ diff --git a/examples/test2.vmla b/examples/test2.vmla new file mode 100644 index 0000000..43085fd --- /dev/null +++ b/examples/test2.vmla @@ -0,0 +1,65 @@ +MOVE_FP_A +I_STORE_A_SP +MOVE_SP_FP +INC_SP_INT +MOVE_COUNTER_A +I_CONST_B 13 +I_ADD +I_STORE_A_SP +INC_SP_INT +GOTO 47 +INC_SP_INT +I_LOAD_FP_SP +MOVE_SP_A +I_CONST_B 8 +I_SUB +MOVE_A_SP +I_STORE_FP_SP +MOVE_SP_A +I_CONST_B 0 +I_ADD +MOVE_A_SP +I_LOAD_FP_SP +MOVE_SP_A +I_CONST_B 0 +I_SUB +MOVE_A_SP +STOP +MOVE_FP_A +I_STORE_A_SP +MOVE_SP_FP +INC_SP_INT +MOVE_COUNTER_A +I_CONST_B 13 +I_ADD +I_STORE_A_SP +INC_SP_INT +GOTO 99 +INC_SP_INT +I_LOAD_FP_SP +MOVE_SP_A +I_CONST_B 8 +I_SUB +MOVE_A_SP +I_STORE_FP_SP +MOVE_SP_A +I_CONST_B 0 +I_ADD +MOVE_A_SP +I_LOAD_FP_SP +MOVE_SP_A +I_CONST_B 0 +I_SUB +MOVE_A_SP +DEC_SP_INT +I_LOAD_A_SP +PRINT_INT_A +DEC_SP_INT +I_LOAD_A_SP +GOTO_A +I_CONST_A 2 +I_STORE_A_SP +INC_SP_INT +DEC_SP_INT +I_LOAD_A_SP +GOTO_A diff --git a/src/vmlang/assembler/Assemble.scala b/src/vmlang/assembler/Assemble.scala new file mode 100644 index 0000000..6f61027 --- /dev/null +++ b/src/vmlang/assembler/Assemble.scala @@ -0,0 +1,43 @@ +package vmlang.assembler + +import vmlang.common.Opcodes._ +import vmlang.common.Opcodes + +case class AssemblyError(msg:String) extends Exception + +object Assemble { + + val opcodes = Map[String,Byte]() ++ (Opcodes.values map { oc => (oc.toString, oc.toByte) }) + + def apply(prog:Prog):List[Byte] = + prog.instrs flatMap { case Instr(opcode, arg) => (opcodes get opcode) match { + case Some(byte) => opcode match { + case "I_CONST_A" | + "I_CONST_B" | + "GOTO" => byte :: (arg match { + case Some(i) => i match { + case i:Int => intBytes(i) + case _ => throw AssemblyError("opcode " + opcode + " takes an int argument") + } + case None => throw AssemblyError("opcode " + opcode + " takes an int argument") + }) + case "B_CONST_A" | + "B_CONST_B" => byte :: (arg match { + case Some(b) => b match { + case b:Byte => b :: Nil + case _ => throw AssemblyError("opcode " + opcode + " takes a byte argument") + } + case None => throw AssemblyError("opcode " + opcode + " takes a byte argument") + }) + case _ => List(byte) + } + case None => throw AssemblyError("nonexistent opcode: " + opcode) + } } + + def intBytes(i:Int):List[Byte] = + (0xff & (i << 24)).asInstanceOf[Byte] :: + (0xff & (i << 16)).asInstanceOf[Byte] :: + (0xff & (i << 8)).asInstanceOf[Byte] :: + (0xff & i).asInstanceOf[Byte] :: Nil + +} diff --git a/src/vmlang/assembler/Main.scala b/src/vmlang/assembler/Main.scala new file mode 100644 index 0000000..74ede50 --- /dev/null +++ b/src/vmlang/assembler/Main.scala @@ -0,0 +1,40 @@ +package vmlang.assembler + +import vmlang.common.{OptParser, FatalError} + +import java.io.{File, FileOutputStream, FileNotFoundException, IOException} +import io.Source + +object Main extends OptParser { + + def numArgs(n:Int) = n == 1 + val argErrorMsg = "supply 1 file to assemble" + val knownFlags = List() + val defaultOpts = Map[String,String]() + val help = "usage: vmla <file to assemble>" + + def run(args:List[String], flags:List[String], opts:Map[String,String]):Unit = + try { + writeFile(Assemble(Parse(loadFile(args.head))), (args.head split '.')(0) + ".vmlc") + } catch { + case ParserError(msg) => throw FatalError("Parser Error: " + msg) + case AssemblyError(msg) => throw FatalError("Assembly Error: " + msg) + } + + def writeFile(output:List[Byte], fileName:String):Unit = + try { + new FileOutputStream(new File(fileName)).write(output.toArray) + } catch { + case e:FileNotFoundException => throw FatalError("Error creating file " + fileName) + case e:IOException => throw FatalError("Error writing file " + fileName) + } + + def loadFile(fileName:String):String = + try { + Source.fromFile(fileName).getLines.mkString + } catch { + case e:FileNotFoundException => throw FatalError("File not found: " + fileName) + case e:IOException => throw FatalError("Error reading file " + fileName) + } + +} diff --git a/src/vmlang/assembler/Parse.scala b/src/vmlang/assembler/Parse.scala new file mode 100644 index 0000000..c29ee52 --- /dev/null +++ b/src/vmlang/assembler/Parse.scala @@ -0,0 +1,28 @@ +package vmlang.assembler + +import util.parsing.input.CharSequenceReader +import util.parsing.combinator.JavaTokenParsers + +object Parse extends JavaTokenParsers { + + def prog = (instr+) ^^ { is => Prog(is) } + + def instr = opcode ~ (arg?) ^^ { case oc ~ a => Instr(oc, a) } + + def opcode = ident + + def arg = wholeNumber ^^ { _.toInt } + + def apply(input:String):Prog = + phrase(prog)(new CharSequenceReader(input)) match { + case Success(t, _) => t + case e:NoSuccess => throw ParserError(e.toString) + } + +} + +case class ParserError(msg:String) extends Exception + +abstract class ASTNode +case class Prog(instrs:List[Instr]) extends ASTNode +case class Instr(opcode:String, arg:Option[AnyVal]) diff --git a/src/vmlang/common/Opcodes.java b/src/vmlang/common/Opcodes.java index 111ea5f..0a64be7 100644 --- a/src/vmlang/common/Opcodes.java +++ b/src/vmlang/common/Opcodes.java @@ -1,63 +1,63 @@ package vmlang.common; public enum Opcodes { STOP, GOTO, GOTO_A, IF_EQ, IF_LT, I_CONST_A, I_CONST_B, B_CONST_A, B_CONST_B, I_LOAD_A_SP, I_LOAD_A_A, - I_LOAD_BP_SP, + I_LOAD_FP_SP, I_LOAD_B_SP, I_LOAD_SP_SP, B_LOAD_A_SP, B_LOAD_A_A, B_LOAD_B_SP, I_STORE_A_SP, - I_STORE_BP_SP, + I_STORE_FP_SP, B_STORE_A_SP, MOVE_COUNTER_A, MOVE_SP_A, - MOVE_BP_A, + MOVE_FP_A, MOVE_A_SP, - MOVE_A_BP, - MOVE_SP_BP, + MOVE_A_FP, + MOVE_SP_FP, I_ADD, I_SUB, I_MUL, I_DIV, I_MOD, F_ADD, F_SUB, F_MUL, F_DIV, F_MOD, INC_A, INC_B, INC_SP, INC_SP_INT, DEC_A, DEC_B, DEC_SP, DEC_SP_INT, NEG_A, EQ_A, LT_A, GT_A, AND, OR, PRINT_CHAR_A, PRINT_INT_A, READ_CHAR_A, STACK_START; public byte toByte() { return (byte)ordinal(); } } diff --git a/src/vmlang/compiler/AST.scala b/src/vmlang/compiler/AST.scala index 5e84fa1..ba5855d 100644 --- a/src/vmlang/compiler/AST.scala +++ b/src/vmlang/compiler/AST.scala @@ -1,29 +1,32 @@ package vmlang.compiler.ast +import vmlang.compiler.typecheck.Type + abstract class ASTNode case class Prog(defs:Map[String, Def]) extends ASTNode case class ParamSpec(name:String, argType:TypeExpr) extends ASTNode case class TypeExpr(name:String, args:List[TypeExpr]) extends ASTNode { val isFunctionType = (name startsWith "Function") && !(name endsWith("Function")) override val toString = if(isFunctionType) args.init.mkString("(",",",")") + " => " + args.last else name + (if(args.isEmpty) "" else args.mkString("[",",","]")) val repr = if(isFunctionType) toString else name } abstract class IPromptStmt extends ASTNode case class Def(name:String, params:List[ParamSpec], returnType:TypeExpr, body:Expr) extends IPromptStmt abstract class Expr extends IPromptStmt case class IfExpr(condition:Expr, ifExpr:Expr, thenExpr:Expr) extends Expr case class Call(name:String, args:List[Expr]) extends Expr +case class TypedCall(call:Call, types:List[Type]) abstract class Atom extends Expr case class IntLit(value:Int) extends Atom case class FloatLit(value:Float) extends Atom case class CharLit(value:Char) extends Atom diff --git a/src/vmlang/compiler/Linearize.scala b/src/vmlang/compiler/Linearize.scala index 6f1517e..82ce69c 100644 --- a/src/vmlang/compiler/Linearize.scala +++ b/src/vmlang/compiler/Linearize.scala @@ -1,191 +1,188 @@ -package vmlang.compiler - -import java.io.{DataOutputStream, ByteArrayOutputStream} -import collection.mutable.HashMap - - -import vmlang.common.Opcodes -import vmlang.common.Opcodes._ -import vmlang.compiler.ast._ - -case class CheckedDef(params:List[(String,Int)], body:Expr) - -// shameful imperative code... - -object Linearize { - - def apply(prog:Map[String,CheckedDef]):Array[Byte] = new Linearizer(prog).run - -} - -class Linearizer(prog:Map[String,CheckedDef]) { - - type Scope = List[(String,Int)] - - private val baos = new ByteArrayOutputStream - private val out = new DataOutputStream(baos) - private val refs = new HashMap[Int,String] - private val startingPoints = new HashMap[String,Int] - - def run:Array[Byte] = { - wExpr(Call("main", Nil), Nil) - w(STOP) - for((n, d) <- prog) { - startingPoints += (n -> out.size) - wExpr(d.body, d.params) - // goto return address (on stack) - w(DEC_SP_INT) - w(I_LOAD_A_SP) - w(GOTO_A) - } - resolveGotos - } - - private def resolveGotos:Array[Byte] = { - val result = baos.toByteArray - for((ind, ref) <- refs) { - val refInd = startingPoints(ref) - // write program index (integer) to result array - result(ind+1) = (0xff & (refInd << 24)).asInstanceOf[Byte] - result(ind+2) = (0xff & (refInd << 16)).asInstanceOf[Byte] - result(ind+3) = (0xff & (refInd << 8)).asInstanceOf[Byte] - result(ind+4) = (0xff & refInd).asInstanceOf[Byte] - } - result - } - - private def w(oc:Opcodes):Unit = out.write(oc.toByte) - private def w(oc:Opcodes, arg:Int):Unit = { w(oc); out.writeInt(arg) } - private def w(oc:Opcodes, arg:Float):Unit = { w(oc); out.writeFloat(arg) } - private def w(oc:Opcodes, arg:Byte):Unit = { w(oc); out.writeByte(arg) } - - private def wExpr(e:Expr, s:Scope):Unit = e match { - - case IntLit(i) => w(I_CONST_A, i); w(I_STORE_A_SP); w(INC_SP_INT) - case CharLit(c) => w(B_CONST_A, c.toByte); w(B_STORE_A_SP); w(INC_SP) - case FloatLit(f) => w(I_CONST_A, java.lang.Float.floatToIntBits(f)); w(I_STORE_A_SP); w(INC_SP_INT) - - case Call("+", List(a, b)) => intOp(a, b, s, ()=>{ w(I_ADD) }) - case Call("-", List(a, b)) => intOp(a, b, s, ()=>{ w(I_SUB) }) - case Call("*", List(a, b)) => intOp(a, b, s, ()=>{ w(I_MUL) }) - case Call("/", List(a, b)) => intOp(a, b, s, ()=>{ w(I_DIV) }) - case Call("%", List(a, b)) => intOp(a, b, s, ()=>{ w(I_MOD) }) - - case Call("==", List(a, b)) => cmpOp(a, b, s, ()=>{ w(EQ_A) }) - case Call(">" , List(a, b)) => cmpOp(a, b, s, ()=>{ w(GT_A) }) - case Call("<" , List(a, b)) => cmpOp(a, b, s, ()=>{ w(LT_A) }) - case Call(">=", List(a, b)) => cmpOp(a, b, s, ()=>{ w(LT_A); w(NEG_A) }) - case Call("<=", List(a, b)) => cmpOp(a, b, s, ()=>{ w(GT_A); w(NEG_A) }) - - case Call("and", List(a, b)) => byteOp(a, b, s, ()=>{ w(AND) }) - case Call("or" , List(a, b)) => byteOp(a, b, s, ()=>{ w(OR) }) - case Call("not", List(a)) => wExpr(a, s); wPopByteA; w(NEG_A); wPushByte() - - case Call("true" , Nil) => w(B_CONST_A, 1:Byte); wPushByte - case Call("false", Nil) => w(B_CONST_A, 0:Byte); wPushByte - case Call("null" , Nil) => // do nothing - - case Call("printInt", List(a)) => wExpr(a, s); wPopIntA; w(PRINT_INT_A) - - case Call(name, args) => argOffset(name, s) match { - case Some(offset) => - w(MOVE_BP_A) - w(I_CONST_B, offset) - w(I_SUB) - w(I_LOAD_A_A) - w(I_STORE_A_SP) - w(INC_SP_INT) - case None => - (args foreach { wExpr(_, s) }) - wCallPrelude - wGoto(name) - wCallPostlude(prog(name).params.foldLeft(0){ _ + _._2}) // retrieve returned value - } - - } - - private def argOffset(name:String, scope:Scope):Option[Int] = - (scope findIndexOf { _._1 == name }) match { - case -1 => None - case index => Some((scope drop index).foldLeft(0){ _ + _._2 }) - } - - private def wCallPrelude = { - // push base pointer - w(MOVE_BP_A) - w(I_STORE_A_SP) - w(MOVE_SP_BP) - w(INC_SP_INT) - // push (program address+13) - // so it will return to the instruction right after the GOTO - w(MOVE_COUNTER_A) - w(I_CONST_B, 13) - w(I_ADD) - w(I_STORE_A_SP) - w(INC_SP_INT) - } - - private def wGoto(ref:String) { - refs += (out.size -> ref) - w(GOTO, 0) // the 0 will be replaced in resolveGotos - } - - private def wCallPostlude(paramSize:Int) = { - // load answer into BP - w(INC_SP_INT) - w(I_LOAD_BP_SP) - // save answer from BP to stack - w(MOVE_SP_A) - w(I_CONST_B, paramSize + 8) - w(I_SUB) - w(MOVE_A_SP) - w(I_STORE_BP_SP) - // get BP from stack - w(MOVE_SP_A) - w(I_CONST_B, paramSize) - w(I_ADD) - w(MOVE_A_SP) - w(I_LOAD_BP_SP) - // move SP back to operand stack - w(MOVE_SP_A) - w(I_CONST_B, paramSize) - w(I_SUB) - w(MOVE_A_SP) - } - - private def cmpOp(a:Expr, b:Expr, s:Scope, cmp:()=>Unit) = - intOp(a, b, s, { w(I_SUB); cmp(); wPushByte }) - - private def intOp(a:Expr, b:Expr, s:Scope, ops:()=>Unit) = { - intOpNoPush(a, b, s, ops) - wPushInt - } - private def intOpNoPush(a:Expr, b:Expr, s:Scope, ops:()=>Unit) = { - wExpr(a, s) - wExpr(b, s) - wPopIntB - wPopIntA - ops() - } - - private def byteOp(a:Expr, b:Expr, s:Scope, ops:()=>Unit) = { - byteOpNoPush(a, b, s, ops) - wPushByte - } - private def byteOpNoPush(a:Expr, b:Expr, s:Scope, ops:()=>Unit) = { - wExpr(a, s) - wExpr(b, s) - wPopByteB - wPopByteA - ops() - } - - private def wPopIntA = { w(DEC_SP_INT); w(I_LOAD_A_SP) } - private def wPopIntB = { w(DEC_SP_INT); w(I_LOAD_B_SP) } - private def wPushInt = { w(I_STORE_A_SP); w(INC_SP_INT) } - - private def wPopByteA = { w(DEC_SP); w(B_LOAD_A_SP) } - private def wPopByteB = { w(DEC_SP); w(B_LOAD_B_SP) } - private def wPushByte() = { w(DEC_SP); w(B_STORE_A_SP); } - -} +// package vmlang.compiler +// +// import java.io.{DataOutputStream, ByteArrayOutputStream} +// import collection.mutable.HashMap +// +// +// import vmlang.common.Opcodes +// import vmlang.common.Opcodes._ +// import vmlang.compiler.ast._ +// +// // shameful imperative code... +// +// object Linearize { +// +// def apply(prog:Prog):Array[Byte] = new Linearizer(prog).run +// +// } +// +// class Linearizer(prog:Prog) { +// +// private val baos = new ByteArrayOutputStream +// private val out = new DataOutputStream(baos) +// private val refs = new HashMap[Int,String] +// private val startingPoints = new HashMap[String,Int] +// +// def run:Array[Byte] = { +// wExpr(Call("main", Nil), Nil) +// w(STOP) +// for((n, d) <- prog.defs) { +// startingPoints += (n -> out.size) +// wExpr(d.body, d.params) +// // goto return address (on stack) +// w(MOVE_A_FP) +// w(DEC_SP_INT) +// w(I_LOAD_A_SP) +// w(GOTO_A) +// } +// resolveGotos +// } +// +// private def resolveGotos:Array[Byte] = { +// val result = baos.toByteArray +// for((ind, ref) <- refs) { +// val refInd = startingPoints(ref) +// // write program index (integer) to result array +// result(ind+1) = (0xff & (refInd << 24)).asInstanceOf[Byte] +// result(ind+2) = (0xff & (refInd << 16)).asInstanceOf[Byte] +// result(ind+3) = (0xff & (refInd << 8)).asInstanceOf[Byte] +// result(ind+4) = (0xff & refInd).asInstanceOf[Byte] +// } +// result +// } +// +// private def w(oc:Opcodes):Unit = out.write(oc.toByte) +// private def w(oc:Opcodes, arg:Int):Unit = { w(oc); out.writeInt(arg) } +// private def w(oc:Opcodes, arg:Float):Unit = { w(oc); out.writeFloat(arg) } +// private def w(oc:Opcodes, arg:Byte):Unit = { w(oc); out.writeByte(arg) } +// +// private def wExpr(e:Expr, s:Scope):Unit = e match { +// +// case IntLit(i) => w(I_CONST_A, i); w(I_STORE_A_SP); w(INC_SP_INT) +// case CharLit(c) => w(B_CONST_A, c.toByte); w(B_STORE_A_SP); w(INC_SP) +// case FloatLit(f) => w(I_CONST_A, java.lang.Float.floatToIntBits(f)); w(I_STORE_A_SP); w(INC_SP_INT) +// +// case Call("+", List(a, b)) => intOp(a, b, s, ()=>{ w(I_ADD) }) +// case Call("-", List(a, b)) => intOp(a, b, s, ()=>{ w(I_SUB) }) +// case Call("*", List(a, b)) => intOp(a, b, s, ()=>{ w(I_MUL) }) +// case Call("/", List(a, b)) => intOp(a, b, s, ()=>{ w(I_DIV) }) +// case Call("%", List(a, b)) => intOp(a, b, s, ()=>{ w(I_MOD) }) +// +// case Call("==", List(a, b)) => cmpOp(a, b, s, ()=>{ w(EQ_A) }) +// case Call(">" , List(a, b)) => cmpOp(a, b, s, ()=>{ w(GT_A) }) +// case Call("<" , List(a, b)) => cmpOp(a, b, s, ()=>{ w(LT_A) }) +// case Call(">=", List(a, b)) => cmpOp(a, b, s, ()=>{ w(LT_A); w(NEG_A) }) +// case Call("<=", List(a, b)) => cmpOp(a, b, s, ()=>{ w(GT_A); w(NEG_A) }) +// +// case Call("and", List(a, b)) => byteOp(a, b, s, ()=>{ w(AND) }) +// case Call("or" , List(a, b)) => byteOp(a, b, s, ()=>{ w(OR) }) +// case Call("not", List(a)) => wExpr(a, s); wPopByteA; w(NEG_A); wPushByte() +// +// case Call("true" , Nil) => w(B_CONST_A, 1:Byte); wPushByte +// case Call("false", Nil) => w(B_CONST_A, 0:Byte); wPushByte +// case Call("null" , Nil) => // do nothing +// +// case Call("printInt", List(a)) => wExpr(a, s); wPopIntA; w(PRINT_INT_A) +// +// case Call(name, args) => argOffset(name, s) match { +// case Some(offset) => +// w(MOVE_FP_A) +// w(I_CONST_B, offset) +// w(I_SUB) +// w(I_LOAD_A_A) +// w(I_STORE_A_SP) +// w(INC_SP_INT) +// case None => +// (args foreach { wExpr(_, s) }) +// wCallPrelude +// wGoto(name) +// wCallPostlude(prog(name).params.foldLeft(0){ _ + _._2}) // retrieve returned value +// } +// +// } +// +// private def argOffset(name:String, scope:Scope):Option[Int] = +// (scope findIndexOf { _._1 == name }) match { +// case -1 => None +// case index => Some((scope drop index).foldLeft(0){ _ + _._2 }) +// } +// +// private def wCallPrelude = { +// // push base pointer +// w(MOVE_FP_A) +// w(I_STORE_A_SP) +// w(MOVE_SP_FP) +// w(INC_SP_INT) +// // push (program address+13) +// // so it will return to the instruction right after the GOTO +// w(MOVE_COUNTER_A) +// w(I_CONST_B, 13) +// w(I_ADD) +// w(I_STORE_A_SP) +// w(INC_SP_INT) +// } +// +// private def wGoto(ref:String) { +// refs += (out.size -> ref) +// w(GOTO, 0) // the 0 will be replaced in resolveGotos +// } +// +// private def wCallPostlude(paramSize:Int) = { +// // load answer into FP +// w(INC_SP_INT) +// w(I_LOAD_FP_SP) +// // save answer from FP to stack +// w(MOVE_SP_A) +// w(I_CONST_B, paramSize + 8) +// w(I_SUB) +// w(MOVE_A_SP) +// w(I_STORE_FP_SP) +// // get FP from stack +// w(MOVE_SP_A) +// w(I_CONST_B, paramSize) +// w(I_ADD) +// w(MOVE_A_SP) +// w(I_LOAD_FP_SP) +// // move SP back to operand stack +// w(MOVE_SP_A) +// w(I_CONST_B, paramSize) +// w(I_SUB) +// w(MOVE_A_SP) +// } +// +// private def cmpOp(a:Expr, b:Expr, s:Scope, cmp:()=>Unit) = +// intOp(a, b, s, { w(I_SUB); cmp(); wPushByte }) +// +// private def intOp(a:Expr, b:Expr, s:Scope, ops:()=>Unit) = { +// intOpNoPush(a, b, s, ops) +// wPushInt +// } +// private def intOpNoPush(a:Expr, b:Expr, s:Scope, ops:()=>Unit) = { +// wExpr(a, s) +// wExpr(b, s) +// wPopIntB +// wPopIntA +// ops() +// } +// +// private def byteOp(a:Expr, b:Expr, s:Scope, ops:()=>Unit) = { +// byteOpNoPush(a, b, s, ops) +// wPushByte +// } +// private def byteOpNoPush(a:Expr, b:Expr, s:Scope, ops:()=>Unit) = { +// wExpr(a, s) +// wExpr(b, s) +// wPopByteB +// wPopByteA +// ops() +// } +// +// private def wPopIntA = { w(DEC_SP_INT); w(I_LOAD_A_SP) } +// private def wPopIntB = { w(DEC_SP_INT); w(I_LOAD_B_SP) } +// private def wPushInt = { w(I_STORE_A_SP); w(INC_SP_INT) } +// +// private def wPopByteA = { w(DEC_SP); w(B_LOAD_A_SP) } +// private def wPopByteB = { w(DEC_SP); w(B_LOAD_B_SP) } +// private def wPushByte() = { w(DEC_SP); w(B_STORE_A_SP); } +// +// } diff --git a/src/vmlang/compiler/Main.scala b/src/vmlang/compiler/Main.scala index 27fdfbb..e186072 100644 --- a/src/vmlang/compiler/Main.scala +++ b/src/vmlang/compiler/Main.scala @@ -1,80 +1,80 @@ package vmlang.compiler import vmlang.common.{OptParser, FatalError} import vmlang.compiler.typecheck.TypeCheck import vmlang.compiler.ast._ import vmlang.vm.{VM, VMError} import collection.mutable.HashMap import java.util.Scanner import java.io.{File, FileOutputStream, FileNotFoundException, IOException} import io.Source object Main extends OptParser { def numArgs(n:Int) = n == 0 || n == 1 val argErrorMsg = "supply 1 file to compile, or no argument for interactive prompt" val knownFlags = List("v") val defaultOpts = Map[String,String]() - val help = "usage: vmlangc <optional source file> <options>\n" + - "-v print out messages about what the compiler is doing" + val help = "usage: vmlc <optional source file> <options>\n" + + "-v print out messages about what the compiler is doing" def run(args:List[String], flags:List[String], opts:Map[String,String]):Unit = args match { case Nil => runIPrompt case List(fn) => try { writeFile(Compile(loadFile(fn)), (fn split '.')(0) + ".vmlc") } catch { case e:CompilerError => throw FatalError(e.repr) } } def runIPrompt = { val s = new Scanner(System.in) var counter = 0 var defs = Map[String,Def]() while(true) { print(">> ") try { val input = s.nextLine if(input startsWith ":t ") { println(TypeCheck.inferType(Parse.parseExpr(input substring 3))) } else { Parse.parseIPromptStmt(input) match { case e:Expr => defs = defs + ("main" -> Def("main", Nil, TypeExpr("Null",Nil), e match { case Call("printInt",args) => e case expr => Call("printInt",List(expr)) })) case d:Def => defs = defs + (d.name -> d) } val code = Linearize(Simplify(TypeCheck(Prog(defs)))) new VM(code, 1024, 1024).run } } catch { case e:CompilerError => println(e.repr) case e:VMError => println(e.getMessage) } } } def writeFile(output:Array[Byte], fileName:String):Unit = try { new FileOutputStream(new File(fileName)).write(output) } catch { case e:FileNotFoundException => throw FatalError("Error creating file " + fileName) case e:IOException => throw FatalError("Error writing file " + fileName) } def loadFile(fileName:String):String = try { Source.fromFile(fileName).getLines.mkString } catch { case e:FileNotFoundException => throw FatalError("File not found: " + fileName) case e:IOException => throw FatalError("Error reading file " + fileName) } } diff --git a/src/vmlang/compiler/Simplify.scala b/src/vmlang/compiler/Simplify.scala index 4d5939f..05ddcfd 100644 --- a/src/vmlang/compiler/Simplify.scala +++ b/src/vmlang/compiler/Simplify.scala @@ -1,45 +1,47 @@ package vmlang.compiler import vmlang.compiler.ast._ import collection.immutable.HashSet +// TODO: inline calls to functions like "a:Int = 2" + object Simplify { def apply(prog:Map[String,CheckedDef]) = Map[String,CheckedDef]() ++ (prog map { m => (m._1 -> CheckedDef(m._2.params, simplify(m._2.body))) }) def simplify(e:Expr):Expr = e match { case a:Atom => a case IfExpr(c,i,e) => (simplify(c), simplify(i), simplify(e)) match { case (Call("true",Nil), i, e) => i case (Call("false",Nil), i, e) => e case (c, i, e) => IfExpr(c, i, e) } case Call(n,args) => (n, args map simplify) match { case ("+" , List(IntLit(a),IntLit(b))) => IntLit(a + b) case ("-" , List(IntLit(a),IntLit(b))) => IntLit(a - b) case ("*" , List(IntLit(a),IntLit(b))) => IntLit(a * b) case ("/" , List(IntLit(a),IntLit(b))) => IntLit(a / b) case (">" , List(IntLit(a),IntLit(b))) => Call(if(a > b) "true" else "false", Nil) case (">=", List(IntLit(a),IntLit(b))) => Call(if(a >= b) "true" else "false", Nil) case ("<" , List(IntLit(a),IntLit(b))) => Call(if(a < b) "true" else "false", Nil) case ("<=", List(IntLit(a),IntLit(b))) => Call(if(a <= b) "true" else "false", Nil) case ("==", List(IntLit(a),IntLit(b))) => Call(if(a == b) "true" else "false", Nil) case ("not", List(Call("true",Nil))) => Call("false", Nil) case ("not", List(Call("false",Nil))) => Call("true", Nil) case ("and", List(Call(a,Nil),Call(b,Nil))) => Call(if(a == "true" && b == "true") "true" else "false", Nil) case ("or", List(Call(a,Nil),Call(b,Nil))) => Call(if(a == "true" || b == "true") "true" else "false", Nil) case (n, args) => Call(n, args) } } } diff --git a/src/vmlang/compiler/typecheck/Type.scala b/src/vmlang/compiler/typecheck/Type.scala index 52a5556..40f79da 100644 --- a/src/vmlang/compiler/typecheck/Type.scala +++ b/src/vmlang/compiler/typecheck/Type.scala @@ -1,28 +1,27 @@ package vmlang.compiler.typecheck abstract class Type { val name:String val numParams:Int - val size:Int override def toString = name } -case class AbsType(name:String, numParams:Int) extends Type { - val size = 4 // TODO: this is not right +case class AbsType(name:String, numParams:Int) extends Type +abstract class ConcreteType extends Type { + val size:Int } -abstract class ConcreteType extends Type case class RefType(name:String, numParams:Int) extends ConcreteType { val size = 4 } case class PrimType(name:String, size:Int) extends ConcreteType { val numParams = 0 } /* Type [AbsType] ConcreteType [RefType] [PrimType] */ diff --git a/src/vmlang/disassembler/Main.scala b/src/vmlang/disassembler/Main.scala index d1e5541..9ef0413 100644 --- a/src/vmlang/disassembler/Main.scala +++ b/src/vmlang/disassembler/Main.scala @@ -1,46 +1,46 @@ package vmlang.disassembler import vmlang.common.{OptParser, FatalError, Opcodes} import vmlang.common.Opcodes._ import java.io.{File, FileInputStream, DataInputStream, FileNotFoundException, IOException, EOFException} object Main extends OptParser { def numArgs(n:Int) = n == 1 val argErrorMsg = "supply 1 bytecode file to disassemble" val knownFlags = List() val defaultOpts = Map[String,String]() - val help = "usage: vmlangd <bytecode file>\n" + val help = "usage: vmld <bytecode file>\n" def run(args:List[String], flags:List[String], opts:Map[String,String]):Unit = disassemble(args.head) def disassemble(fileName:String) = try { var addr = 0 val in = new DataInputStream(new FileInputStream(new File(fileName))) val ocs = Opcodes.values while(in.available > 0) { print(addr + "\t") val oc = ocs(in.readByte) addr += 1 print(oc + "\t") oc match { case I_CONST_A => print(in.readInt); addr += 4 case I_CONST_B => print(in.readInt); addr += 4 case B_CONST_A => print(in.readByte); addr += 1 case B_CONST_B => print(in.readByte); addr += 1 case GOTO => print(in.readInt); addr += 4 case _ => } println } } catch { case e:FileNotFoundException => throw FatalError("File not found: " + fileName) case e:EOFException => throw FatalError("malformed program") case e:ArrayIndexOutOfBoundsException => throw FatalError("malformed program") case e:IOException => throw FatalError("Error reading file " + fileName) } } diff --git a/src/vmlang/vm/Main.scala b/src/vmlang/vm/Main.scala index 8e9d5d3..adde4c2 100644 --- a/src/vmlang/vm/Main.scala +++ b/src/vmlang/vm/Main.scala @@ -1,51 +1,51 @@ package vmlang.vm import java.io.{File, FileInputStream, FileNotFoundException, IOException} import vmlang.common.{OptParser, FatalError} object Main extends OptParser { def numArgs(n:Int) = n == 1 val argErrorMsg = "supply 1 bytecode file to run" val knownFlags = List() val defaultOpts = Map("heap_size" -> "1024", "stack_size" -> "1024") - val help = "usage: vmlang <bytecode file> <options>\n" + + val help = "usage: vml <bytecode file> <options>\n" + "-heap_size=<num bytes> heap size in bytes\n" + "-stack_size=<num bytes> stack size in bytes" def run(args:List[String], flags:List[String], opts:Map[String,String]):Unit = { val heapSize = try { opts("heap_size").toInt } catch { case e:NumberFormatException => throw FatalError("Invalid heap size argument") } val stackSize = try { opts("stack_size").toInt } catch { case e:NumberFormatException => throw FatalError("Invalid stack size argument") } // business time try { new VM(loadFileBytes(args(0)), heapSize, stackSize).run } catch { case e:InitError => throw FatalError("Couldn't start VM: " + e.message) case e:MalformedProgramError => throw FatalError("VM error: malformed program") case e:StackOverflowError => throw FatalError("VM error: stack overflow") } } def loadFileBytes(fileName:String):Array[Byte] = { try { val in = new FileInputStream(new File(fileName)) val result = new Array[Byte](in.available) in.read(result) result } catch { case e:FileNotFoundException => throw FatalError("File not found: " + fileName) case e:IOException => throw FatalError("Error reading file " + fileName) } } } diff --git a/src/vmlang/vm/VM.java b/src/vmlang/vm/VM.java index 7c8fc16..ab8a34b 100644 --- a/src/vmlang/vm/VM.java +++ b/src/vmlang/vm/VM.java @@ -1,325 +1,325 @@ package vmlang.vm; import java.io.IOException; import java.io.PrintStream; import java.io.InputStream; import vmlang.common.Opcodes; public class VM { // registers - private int A, B, SP, BP; + private int A, B, SP, FP; private int counter; // memory private byte[] program; private byte[] memory; // io private InputStream in; private PrintStream out; private int stackStart; private static final Opcodes[] opcodes = Opcodes.values(); // inefficient? public VM(byte[] prog, int heapSize, int stackSize) throws InitError { this(prog, heapSize, stackSize, System.in, System.out); } public VM(byte[] prog, int heapSize, int stackSize, InputStream is, PrintStream os) throws InitError { if(heapSize % 8 != 0) throw new InitError("Heap size must be divisible by 8 (for malloc)"); program = prog; memory = new byte[heapSize + stackSize]; stackStart = heapSize; in = is; out = os; } public void run() throws VMError { int nextAddr; while(true) { Opcodes opcode; try { opcode = opcodes[progReadByte()]; } catch(ArrayIndexOutOfBoundsException e) { throw getMalfProgEx(); } switch(opcode) { // FLOW CONTROL // basic case STOP: return; case GOTO: counter = progReadInt(); break; case GOTO_A: counter = A; break; // conditional jumps: based on post-SUB state of register A case IF_EQ: nextAddr = progReadInt(); if(A != 0) counter = nextAddr; break; case IF_LT: nextAddr = progReadInt(); if(A >= 0) counter = nextAddr; break; // LOAD & STORE (Von-Neumann bottleneck) // int constants case I_CONST_A: A = progReadInt(); break; case I_CONST_B: B = progReadInt(); break; // byte constants case B_CONST_A: A = progReadByte(); break; case B_CONST_B: B = progReadByte(); break; // load int case I_LOAD_A_SP: A = memReadInt(SP); break; case I_LOAD_A_A: A = memReadInt(A); break; - case I_LOAD_BP_SP: - BP = memReadInt(SP); + case I_LOAD_FP_SP: + FP = memReadInt(SP); break; case I_LOAD_B_SP: B = memReadInt(SP); break; case I_LOAD_SP_SP: SP = memReadInt(SP); break; // load byte case B_LOAD_A_SP: A = memReadByte(SP); break; case B_LOAD_A_A: A = memReadByte(A); break; case B_LOAD_B_SP: B = memReadByte(SP); break; // store int case I_STORE_A_SP: memWriteInt(SP,A); break; - case I_STORE_BP_SP: - memWriteInt(SP,BP); + case I_STORE_FP_SP: + memWriteInt(SP,FP); break; // store byte case B_STORE_A_SP: memWriteByte(SP,(byte)A); break; // moves case MOVE_COUNTER_A: A = counter; break; case MOVE_SP_A: A = SP; break; - case MOVE_BP_A: - A = BP; + case MOVE_FP_A: + A = FP; break; case MOVE_A_SP: SP = A; break; - case MOVE_A_BP: - BP = A; + case MOVE_A_FP: + FP = A; break; - case MOVE_SP_BP: - BP = SP; + case MOVE_SP_FP: + FP = SP; break; // REGISTER OPERATIONS // int arithmetic case I_ADD: A = A + B; break; case I_SUB: A = A - B; break; case I_MUL: A = A * B; break; case I_DIV: A = A / B; break; case I_MOD: A = A % B; break; case INC_A: A++; break; // float arithmetic case F_ADD: A = Float.floatToIntBits(Float.intBitsToFloat(A) + Float.intBitsToFloat(B)); break; case F_SUB: A = Float.floatToIntBits(Float.intBitsToFloat(A) - Float.intBitsToFloat(B)); break; case F_MUL: A = A = Float.floatToIntBits(Float.intBitsToFloat(A) * Float.intBitsToFloat(B)); break; case F_DIV: A = Float.floatToIntBits(Float.intBitsToFloat(A) / Float.intBitsToFloat(B)); break; case F_MOD: A = Float.floatToIntBits(Float.intBitsToFloat(A) % Float.intBitsToFloat(B)); break; // inc/dec case INC_B: B++; break; case INC_SP: SP++; break; case INC_SP_INT: SP += 4; break; case DEC_A: A--; break; case DEC_B: B--; break; case DEC_SP: SP--; break; case DEC_SP_INT: SP -= 4; break; // logic (0: false; non-0: true) case NEG_A: if(A == 0) A = 1; else A = 0; break; case EQ_A: if(A == 0) A = 1; else A = 0; break; case LT_A: if(A < 0) A = 1; else A = 0; break; case GT_A: if(A > 0) A = 1; else A = 0; break; case AND: if(A != 0 && B != 0) A = 1; else A = 0; break; case OR: if(A != 0 || B != 0) A = 1; else A = 0; break; case STACK_START: A = stackStart; break; // io case PRINT_CHAR_A: out.print((char)A); break; case PRINT_INT_A: out.println(A); break; case READ_CHAR_A: try { A = in.read(); } catch(IOException e) { out.println(e.getMessage()); } break; } } } // PROGRAM READERS private byte progReadByte() throws MalformedProgramError { byte result; try { result = program[counter]; } catch(ArrayIndexOutOfBoundsException e) { throw getMalfProgEx(); } counter++; return result; } private int progReadInt() throws MalformedProgramError { return ((progReadByte() & 0xff) << 24) | ((progReadByte() & 0xff) << 16) | ((progReadByte() & 0xff) << 8) | (progReadByte() & 0xff); } // MEMORY READERS & WRITERS private byte memReadByte(int addr) throws StackOverflowError { try { return memory[addr]; } catch(ArrayIndexOutOfBoundsException e) { throw new StackOverflowError(); } } private int memReadInt(int addr) throws StackOverflowError { return ((memReadByte(addr) & 0xff) << 24) | ((memReadByte(addr+1) & 0xff) << 16) | ((memReadByte(addr+2) & 0xff) << 8) | (memReadByte(addr+3) & 0xff); } private void memWriteByte(int addr, byte val) throws StackOverflowError { try { memory[addr] = val; } catch(ArrayIndexOutOfBoundsException e) { throw new StackOverflowError(); } } private void memWriteInt(int addr, int val) throws StackOverflowError { memWriteByte(addr ,(byte)(0xff & (val >> 24))); memWriteByte(addr+1,(byte)(0xff & (val >> 16))); memWriteByte(addr+2,(byte)(0xff & (val >> 8))); memWriteByte(addr+3,(byte)(0xff & val)); } private MalformedProgramError getMalfProgEx() { return new MalformedProgramError(); } } \ No newline at end of file
vilterp/VMLang
39e9c81bd13cdf12b8a57f37e5e3f52651f22201
added bugs file, started fixing compiler
diff --git a/bugs.txt b/bugs.txt index 73c020f..c221047 100644 --- a/bugs.txt +++ b/bugs.txt @@ -1,13 +1,29 @@ COMPILER -- function calls don't work -- if statements aren't implemented -- should be object-oriented -- will take care of overloading -- linearizer uses Type#size to compute instructions, but defs that take parameters with abstract types don't know what they will be called with! this computation must take place on a per-call basis, when argument types are known (note this makes CheckedDef useless) +Overall + + - should be object-oriented -- will take care of overloading + - definitions with same name don't cause error + +Parser + + - can't parse floats or chars + - use RegexParsers to make custom scanner + - error messages will be hard + - give location info to tokens, if possible + - maybe use scala.io.Source (has fromString method) + - then use custom scanner in existing parser + - unary "not"s aren't parsed right + +Linearizer + + - function calls don't work + - if statements aren't implemented + - uses Type#size to compute instructions, but defs that take parameters with abstract types don't know what they will be called with! this computation must take place on a per-call basis, when argument types are known (note this makes CheckedDef useless) INTERACTIVE PROMPT - ":t <expr>" doesn't take user-defined functions into account - defining a function yields "No main function. (Must be () => Null)" - ":t myFunction" should give myFunction's type signature, not parse it as an expression - should save expressions typed in as "res{n}" diff --git a/examples/test2.bytecode b/examples/test2.bytecode index b1a4b13..b5245a0 100644 --- a/examples/test2.bytecode +++ b/examples/test2.bytecode @@ -1,63 +1,65 @@ 0 MOVE_BP_A 1 I_STORE_A_SP -2 INC_SP_INT -3 MOVE_COUNTER_A -4 I_CONST_B 12 -9 I_ADD -10 I_STORE_A_SP -11 INC_SP_INT -12 GOTO 46 -17 INC_SP_INT -18 I_LOAD_BP_SP -19 MOVE_SP_A -20 I_CONST_B 8 -25 I_SUB -26 MOVE_A_SP -27 I_STORE_BP_SP -28 MOVE_SP_A -29 I_CONST_B 0 -34 I_ADD -35 MOVE_A_SP -36 I_LOAD_BP_SP -37 MOVE_SP_A -38 I_CONST_B 0 -43 I_SUB -44 MOVE_A_SP -45 STOP -46 MOVE_BP_A -47 I_STORE_A_SP -48 INC_SP_INT -49 MOVE_COUNTER_A -50 I_CONST_B 12 -55 I_ADD -56 I_STORE_A_SP -57 INC_SP_INT -58 GOTO 97 -63 INC_SP_INT -64 I_LOAD_BP_SP -65 MOVE_SP_A -66 I_CONST_B 8 -71 I_SUB -72 MOVE_A_SP -73 I_STORE_BP_SP -74 MOVE_SP_A -75 I_CONST_B 0 -80 I_ADD -81 MOVE_A_SP -82 I_LOAD_BP_SP -83 MOVE_SP_A -84 I_CONST_B 0 -89 I_SUB -90 MOVE_A_SP -91 DEC_SP_INT -92 I_LOAD_A_SP -93 PRINT_INT_A -94 DEC_SP_INT -95 I_LOAD_A_SP -96 GOTO_A -97 I_CONST_A 2 -102 I_STORE_A_SP -103 INC_SP_INT -104 DEC_SP_INT -105 I_LOAD_A_SP -106 GOTO_A +2 MOVE_SP_BP +3 INC_SP_INT +4 MOVE_COUNTER_A +5 I_CONST_B 13 +10 I_ADD +11 I_STORE_A_SP +12 INC_SP_INT +13 GOTO 47 +18 INC_SP_INT +19 I_LOAD_BP_SP +20 MOVE_SP_A +21 I_CONST_B 8 +26 I_SUB +27 MOVE_A_SP +28 I_STORE_BP_SP +29 MOVE_SP_A +30 I_CONST_B 0 +35 I_ADD +36 MOVE_A_SP +37 I_LOAD_BP_SP +38 MOVE_SP_A +39 I_CONST_B 0 +44 I_SUB +45 MOVE_A_SP +46 STOP +47 MOVE_BP_A +48 I_STORE_A_SP +49 MOVE_SP_BP +50 INC_SP_INT +51 MOVE_COUNTER_A +52 I_CONST_B 13 +57 I_ADD +58 I_STORE_A_SP +59 INC_SP_INT +60 GOTO 99 +65 INC_SP_INT +66 I_LOAD_BP_SP +67 MOVE_SP_A +68 I_CONST_B 8 +73 I_SUB +74 MOVE_A_SP +75 I_STORE_BP_SP +76 MOVE_SP_A +77 I_CONST_B 0 +82 I_ADD +83 MOVE_A_SP +84 I_LOAD_BP_SP +85 MOVE_SP_A +86 I_CONST_B 0 +91 I_SUB +92 MOVE_A_SP +93 DEC_SP_INT +94 I_LOAD_A_SP +95 PRINT_INT_A +96 DEC_SP_INT +97 I_LOAD_A_SP +98 GOTO_A +99 I_CONST_A 2 +104 I_STORE_A_SP +105 INC_SP_INT +106 DEC_SP_INT +107 I_LOAD_A_SP +108 GOTO_A diff --git a/examples/test2.vmlc b/examples/test2.vmlc index b71f2b9..76f369e 100644 Binary files a/examples/test2.vmlc and b/examples/test2.vmlc differ diff --git a/src/vmlang/common/Opcodes.java b/src/vmlang/common/Opcodes.java index 9d7e04e..111ea5f 100644 --- a/src/vmlang/common/Opcodes.java +++ b/src/vmlang/common/Opcodes.java @@ -1,62 +1,63 @@ package vmlang.common; public enum Opcodes { STOP, GOTO, GOTO_A, IF_EQ, IF_LT, I_CONST_A, I_CONST_B, B_CONST_A, B_CONST_B, I_LOAD_A_SP, I_LOAD_A_A, I_LOAD_BP_SP, I_LOAD_B_SP, I_LOAD_SP_SP, B_LOAD_A_SP, B_LOAD_A_A, B_LOAD_B_SP, I_STORE_A_SP, I_STORE_BP_SP, B_STORE_A_SP, MOVE_COUNTER_A, MOVE_SP_A, MOVE_BP_A, MOVE_A_SP, MOVE_A_BP, + MOVE_SP_BP, I_ADD, I_SUB, I_MUL, I_DIV, I_MOD, F_ADD, F_SUB, F_MUL, F_DIV, F_MOD, INC_A, INC_B, INC_SP, INC_SP_INT, DEC_A, DEC_B, DEC_SP, DEC_SP_INT, NEG_A, EQ_A, LT_A, GT_A, AND, OR, PRINT_CHAR_A, PRINT_INT_A, READ_CHAR_A, STACK_START; public byte toByte() { return (byte)ordinal(); } } diff --git a/src/vmlang/compiler/Compile.scala b/src/vmlang/compiler/Compile.scala index 0ea4781..c6cca61 100644 --- a/src/vmlang/compiler/Compile.scala +++ b/src/vmlang/compiler/Compile.scala @@ -1,9 +1,9 @@ package vmlang.compiler import vmlang.compiler.typecheck.TypeCheck object Compile { - def apply(prog:String):Array[Byte] = Linearize(TypeCheck(Parse(prog))) + def apply(prog:String):Array[Byte] = Linearize(Simplify(TypeCheck(Parse(prog)))) } diff --git a/src/vmlang/compiler/Linearize.scala b/src/vmlang/compiler/Linearize.scala index a3cd391..6f1517e 100644 --- a/src/vmlang/compiler/Linearize.scala +++ b/src/vmlang/compiler/Linearize.scala @@ -1,189 +1,191 @@ package vmlang.compiler import java.io.{DataOutputStream, ByteArrayOutputStream} import collection.mutable.HashMap import vmlang.common.Opcodes import vmlang.common.Opcodes._ import vmlang.compiler.ast._ case class CheckedDef(params:List[(String,Int)], body:Expr) // shameful imperative code... object Linearize { def apply(prog:Map[String,CheckedDef]):Array[Byte] = new Linearizer(prog).run } class Linearizer(prog:Map[String,CheckedDef]) { type Scope = List[(String,Int)] private val baos = new ByteArrayOutputStream private val out = new DataOutputStream(baos) private val refs = new HashMap[Int,String] private val startingPoints = new HashMap[String,Int] def run:Array[Byte] = { wExpr(Call("main", Nil), Nil) w(STOP) for((n, d) <- prog) { startingPoints += (n -> out.size) wExpr(d.body, d.params) // goto return address (on stack) w(DEC_SP_INT) w(I_LOAD_A_SP) w(GOTO_A) } resolveGotos } private def resolveGotos:Array[Byte] = { val result = baos.toByteArray for((ind, ref) <- refs) { val refInd = startingPoints(ref) // write program index (integer) to result array result(ind+1) = (0xff & (refInd << 24)).asInstanceOf[Byte] result(ind+2) = (0xff & (refInd << 16)).asInstanceOf[Byte] result(ind+3) = (0xff & (refInd << 8)).asInstanceOf[Byte] result(ind+4) = (0xff & refInd).asInstanceOf[Byte] } result } private def w(oc:Opcodes):Unit = out.write(oc.toByte) private def w(oc:Opcodes, arg:Int):Unit = { w(oc); out.writeInt(arg) } private def w(oc:Opcodes, arg:Float):Unit = { w(oc); out.writeFloat(arg) } private def w(oc:Opcodes, arg:Byte):Unit = { w(oc); out.writeByte(arg) } private def wExpr(e:Expr, s:Scope):Unit = e match { case IntLit(i) => w(I_CONST_A, i); w(I_STORE_A_SP); w(INC_SP_INT) case CharLit(c) => w(B_CONST_A, c.toByte); w(B_STORE_A_SP); w(INC_SP) case FloatLit(f) => w(I_CONST_A, java.lang.Float.floatToIntBits(f)); w(I_STORE_A_SP); w(INC_SP_INT) case Call("+", List(a, b)) => intOp(a, b, s, ()=>{ w(I_ADD) }) case Call("-", List(a, b)) => intOp(a, b, s, ()=>{ w(I_SUB) }) case Call("*", List(a, b)) => intOp(a, b, s, ()=>{ w(I_MUL) }) case Call("/", List(a, b)) => intOp(a, b, s, ()=>{ w(I_DIV) }) case Call("%", List(a, b)) => intOp(a, b, s, ()=>{ w(I_MOD) }) case Call("==", List(a, b)) => cmpOp(a, b, s, ()=>{ w(EQ_A) }) case Call(">" , List(a, b)) => cmpOp(a, b, s, ()=>{ w(GT_A) }) case Call("<" , List(a, b)) => cmpOp(a, b, s, ()=>{ w(LT_A) }) case Call(">=", List(a, b)) => cmpOp(a, b, s, ()=>{ w(LT_A); w(NEG_A) }) case Call("<=", List(a, b)) => cmpOp(a, b, s, ()=>{ w(GT_A); w(NEG_A) }) case Call("and", List(a, b)) => byteOp(a, b, s, ()=>{ w(AND) }) case Call("or" , List(a, b)) => byteOp(a, b, s, ()=>{ w(OR) }) case Call("not", List(a)) => wExpr(a, s); wPopByteA; w(NEG_A); wPushByte() case Call("true" , Nil) => w(B_CONST_A, 1:Byte); wPushByte case Call("false", Nil) => w(B_CONST_A, 0:Byte); wPushByte case Call("null" , Nil) => // do nothing case Call("printInt", List(a)) => wExpr(a, s); wPopIntA; w(PRINT_INT_A) case Call(name, args) => argOffset(name, s) match { case Some(offset) => w(MOVE_BP_A) w(I_CONST_B, offset) w(I_SUB) w(I_LOAD_A_A) w(I_STORE_A_SP) w(INC_SP_INT) case None => (args foreach { wExpr(_, s) }) wCallPrelude wGoto(name) wCallPostlude(prog(name).params.foldLeft(0){ _ + _._2}) // retrieve returned value } } private def argOffset(name:String, scope:Scope):Option[Int] = (scope findIndexOf { _._1 == name }) match { case -1 => None case index => Some((scope drop index).foldLeft(0){ _ + _._2 }) } private def wCallPrelude = { // push base pointer w(MOVE_BP_A) w(I_STORE_A_SP) + w(MOVE_SP_BP) w(INC_SP_INT) - // push program address + // push (program address+13) + // so it will return to the instruction right after the GOTO w(MOVE_COUNTER_A) - w(I_CONST_B, 12) + w(I_CONST_B, 13) w(I_ADD) w(I_STORE_A_SP) w(INC_SP_INT) } private def wGoto(ref:String) { refs += (out.size -> ref) w(GOTO, 0) // the 0 will be replaced in resolveGotos } private def wCallPostlude(paramSize:Int) = { // load answer into BP w(INC_SP_INT) w(I_LOAD_BP_SP) // save answer from BP to stack w(MOVE_SP_A) w(I_CONST_B, paramSize + 8) w(I_SUB) w(MOVE_A_SP) w(I_STORE_BP_SP) // get BP from stack w(MOVE_SP_A) w(I_CONST_B, paramSize) w(I_ADD) w(MOVE_A_SP) w(I_LOAD_BP_SP) // move SP back to operand stack w(MOVE_SP_A) w(I_CONST_B, paramSize) w(I_SUB) w(MOVE_A_SP) } private def cmpOp(a:Expr, b:Expr, s:Scope, cmp:()=>Unit) = intOp(a, b, s, { w(I_SUB); cmp(); wPushByte }) private def intOp(a:Expr, b:Expr, s:Scope, ops:()=>Unit) = { intOpNoPush(a, b, s, ops) wPushInt } private def intOpNoPush(a:Expr, b:Expr, s:Scope, ops:()=>Unit) = { wExpr(a, s) wExpr(b, s) wPopIntB wPopIntA ops() } private def byteOp(a:Expr, b:Expr, s:Scope, ops:()=>Unit) = { byteOpNoPush(a, b, s, ops) wPushByte } private def byteOpNoPush(a:Expr, b:Expr, s:Scope, ops:()=>Unit) = { wExpr(a, s) wExpr(b, s) wPopByteB wPopByteA ops() } private def wPopIntA = { w(DEC_SP_INT); w(I_LOAD_A_SP) } private def wPopIntB = { w(DEC_SP_INT); w(I_LOAD_B_SP) } private def wPushInt = { w(I_STORE_A_SP); w(INC_SP_INT) } private def wPopByteA = { w(DEC_SP); w(B_LOAD_A_SP) } private def wPopByteB = { w(DEC_SP); w(B_LOAD_B_SP) } private def wPushByte() = { w(DEC_SP); w(B_STORE_A_SP); } } diff --git a/src/vmlang/vm/VM.java b/src/vmlang/vm/VM.java index cada7ab..7c8fc16 100644 --- a/src/vmlang/vm/VM.java +++ b/src/vmlang/vm/VM.java @@ -1,322 +1,325 @@ package vmlang.vm; import java.io.IOException; import java.io.PrintStream; import java.io.InputStream; import vmlang.common.Opcodes; public class VM { // registers private int A, B, SP, BP; private int counter; // memory private byte[] program; private byte[] memory; // io private InputStream in; private PrintStream out; private int stackStart; private static final Opcodes[] opcodes = Opcodes.values(); // inefficient? public VM(byte[] prog, int heapSize, int stackSize) throws InitError { this(prog, heapSize, stackSize, System.in, System.out); } public VM(byte[] prog, int heapSize, int stackSize, InputStream is, PrintStream os) throws InitError { if(heapSize % 8 != 0) throw new InitError("Heap size must be divisible by 8 (for malloc)"); program = prog; memory = new byte[heapSize + stackSize]; stackStart = heapSize; in = is; out = os; } public void run() throws VMError { int nextAddr; while(true) { Opcodes opcode; try { opcode = opcodes[progReadByte()]; } catch(ArrayIndexOutOfBoundsException e) { throw getMalfProgEx(); } switch(opcode) { // FLOW CONTROL // basic case STOP: return; case GOTO: counter = progReadInt(); break; case GOTO_A: counter = A; break; // conditional jumps: based on post-SUB state of register A case IF_EQ: nextAddr = progReadInt(); if(A != 0) counter = nextAddr; break; case IF_LT: nextAddr = progReadInt(); if(A >= 0) counter = nextAddr; break; // LOAD & STORE (Von-Neumann bottleneck) // int constants case I_CONST_A: A = progReadInt(); break; case I_CONST_B: B = progReadInt(); break; // byte constants case B_CONST_A: A = progReadByte(); break; case B_CONST_B: B = progReadByte(); break; // load int case I_LOAD_A_SP: A = memReadInt(SP); break; case I_LOAD_A_A: A = memReadInt(A); break; case I_LOAD_BP_SP: BP = memReadInt(SP); break; case I_LOAD_B_SP: B = memReadInt(SP); break; case I_LOAD_SP_SP: SP = memReadInt(SP); break; // load byte case B_LOAD_A_SP: A = memReadByte(SP); break; case B_LOAD_A_A: A = memReadByte(A); break; case B_LOAD_B_SP: B = memReadByte(SP); break; // store int case I_STORE_A_SP: memWriteInt(SP,A); break; case I_STORE_BP_SP: memWriteInt(SP,BP); break; // store byte case B_STORE_A_SP: memWriteByte(SP,(byte)A); break; // moves case MOVE_COUNTER_A: A = counter; break; case MOVE_SP_A: A = SP; break; case MOVE_BP_A: A = BP; break; case MOVE_A_SP: SP = A; break; case MOVE_A_BP: BP = A; break; + case MOVE_SP_BP: + BP = SP; + break; // REGISTER OPERATIONS // int arithmetic case I_ADD: A = A + B; break; case I_SUB: A = A - B; break; case I_MUL: A = A * B; break; case I_DIV: A = A / B; break; case I_MOD: A = A % B; break; case INC_A: A++; break; // float arithmetic case F_ADD: A = Float.floatToIntBits(Float.intBitsToFloat(A) + Float.intBitsToFloat(B)); break; case F_SUB: A = Float.floatToIntBits(Float.intBitsToFloat(A) - Float.intBitsToFloat(B)); break; case F_MUL: A = A = Float.floatToIntBits(Float.intBitsToFloat(A) * Float.intBitsToFloat(B)); break; case F_DIV: A = Float.floatToIntBits(Float.intBitsToFloat(A) / Float.intBitsToFloat(B)); break; case F_MOD: A = Float.floatToIntBits(Float.intBitsToFloat(A) % Float.intBitsToFloat(B)); break; // inc/dec case INC_B: B++; break; case INC_SP: SP++; break; case INC_SP_INT: SP += 4; break; case DEC_A: A--; break; case DEC_B: B--; break; case DEC_SP: SP--; break; case DEC_SP_INT: SP -= 4; break; // logic (0: false; non-0: true) case NEG_A: if(A == 0) A = 1; else A = 0; break; case EQ_A: if(A == 0) A = 1; else A = 0; break; case LT_A: if(A < 0) A = 1; else A = 0; break; case GT_A: if(A > 0) A = 1; else A = 0; break; case AND: if(A != 0 && B != 0) A = 1; else A = 0; break; case OR: if(A != 0 || B != 0) A = 1; else A = 0; break; case STACK_START: A = stackStart; break; // io case PRINT_CHAR_A: out.print((char)A); break; case PRINT_INT_A: out.println(A); break; case READ_CHAR_A: try { A = in.read(); } catch(IOException e) { out.println(e.getMessage()); } break; } } } // PROGRAM READERS private byte progReadByte() throws MalformedProgramError { byte result; try { result = program[counter]; } catch(ArrayIndexOutOfBoundsException e) { throw getMalfProgEx(); } counter++; return result; } private int progReadInt() throws MalformedProgramError { return ((progReadByte() & 0xff) << 24) | ((progReadByte() & 0xff) << 16) | ((progReadByte() & 0xff) << 8) | (progReadByte() & 0xff); } // MEMORY READERS & WRITERS private byte memReadByte(int addr) throws StackOverflowError { try { return memory[addr]; } catch(ArrayIndexOutOfBoundsException e) { throw new StackOverflowError(); } } private int memReadInt(int addr) throws StackOverflowError { return ((memReadByte(addr) & 0xff) << 24) | ((memReadByte(addr+1) & 0xff) << 16) | ((memReadByte(addr+2) & 0xff) << 8) | (memReadByte(addr+3) & 0xff); } private void memWriteByte(int addr, byte val) throws StackOverflowError { try { memory[addr] = val; } catch(ArrayIndexOutOfBoundsException e) { throw new StackOverflowError(); } } private void memWriteInt(int addr, int val) throws StackOverflowError { memWriteByte(addr ,(byte)(0xff & (val >> 24))); memWriteByte(addr+1,(byte)(0xff & (val >> 16))); memWriteByte(addr+2,(byte)(0xff & (val >> 8))); memWriteByte(addr+3,(byte)(0xff & val)); } private MalformedProgramError getMalfProgEx() { return new MalformedProgramError(); } } \ No newline at end of file
vilterp/VMLang
25fe342ce05b0fb25f386c70981217392cdba2ca
added disassembler and entry point for compiler w/ interactive prompt. many errors.
diff --git a/bugs.txt b/bugs.txt new file mode 100644 index 0000000..73c020f --- /dev/null +++ b/bugs.txt @@ -0,0 +1,13 @@ +COMPILER + +- function calls don't work +- if statements aren't implemented +- should be object-oriented -- will take care of overloading +- linearizer uses Type#size to compute instructions, but defs that take parameters with abstract types don't know what they will be called with! this computation must take place on a per-call basis, when argument types are known (note this makes CheckedDef useless) + +INTERACTIVE PROMPT + +- ":t <expr>" doesn't take user-defined functions into account +- defining a function yields "No main function. (Must be () => Null)" +- ":t myFunction" should give myFunction's type signature, not parse it as an expression +- should save expressions typed in as "res{n}" diff --git a/examples/test.vml b/examples/test.vml new file mode 100644 index 0000000..5750c02 --- /dev/null +++ b/examples/test.vml @@ -0,0 +1 @@ +main:Null = printInt(2+3) diff --git a/examples/test.vmlc b/examples/test.vmlc new file mode 100644 index 0000000..6725108 Binary files /dev/null and b/examples/test.vmlc differ diff --git a/examples/test2.bytecode b/examples/test2.bytecode new file mode 100644 index 0000000..b1a4b13 --- /dev/null +++ b/examples/test2.bytecode @@ -0,0 +1,63 @@ +0 MOVE_BP_A +1 I_STORE_A_SP +2 INC_SP_INT +3 MOVE_COUNTER_A +4 I_CONST_B 12 +9 I_ADD +10 I_STORE_A_SP +11 INC_SP_INT +12 GOTO 46 +17 INC_SP_INT +18 I_LOAD_BP_SP +19 MOVE_SP_A +20 I_CONST_B 8 +25 I_SUB +26 MOVE_A_SP +27 I_STORE_BP_SP +28 MOVE_SP_A +29 I_CONST_B 0 +34 I_ADD +35 MOVE_A_SP +36 I_LOAD_BP_SP +37 MOVE_SP_A +38 I_CONST_B 0 +43 I_SUB +44 MOVE_A_SP +45 STOP +46 MOVE_BP_A +47 I_STORE_A_SP +48 INC_SP_INT +49 MOVE_COUNTER_A +50 I_CONST_B 12 +55 I_ADD +56 I_STORE_A_SP +57 INC_SP_INT +58 GOTO 97 +63 INC_SP_INT +64 I_LOAD_BP_SP +65 MOVE_SP_A +66 I_CONST_B 8 +71 I_SUB +72 MOVE_A_SP +73 I_STORE_BP_SP +74 MOVE_SP_A +75 I_CONST_B 0 +80 I_ADD +81 MOVE_A_SP +82 I_LOAD_BP_SP +83 MOVE_SP_A +84 I_CONST_B 0 +89 I_SUB +90 MOVE_A_SP +91 DEC_SP_INT +92 I_LOAD_A_SP +93 PRINT_INT_A +94 DEC_SP_INT +95 I_LOAD_A_SP +96 GOTO_A +97 I_CONST_A 2 +102 I_STORE_A_SP +103 INC_SP_INT +104 DEC_SP_INT +105 I_LOAD_A_SP +106 GOTO_A diff --git a/examples/test2.vml b/examples/test2.vml new file mode 100644 index 0000000..4ab5091 --- /dev/null +++ b/examples/test2.vml @@ -0,0 +1,2 @@ +main:Null = printInt(a) +a:Int = 2 diff --git a/examples/test2.vmlc b/examples/test2.vmlc new file mode 100644 index 0000000..b71f2b9 Binary files /dev/null and b/examples/test2.vmlc differ diff --git a/examples/test3.vml b/examples/test3.vml new file mode 100644 index 0000000..8a3756d --- /dev/null +++ b/examples/test3.vml @@ -0,0 +1 @@ +main:Int = 2 diff --git a/src/vmlang/common/OptParser.scala b/src/vmlang/common/OptParser.scala index 75bcdd7..4a503b8 100644 --- a/src/vmlang/common/OptParser.scala +++ b/src/vmlang/common/OptParser.scala @@ -1,64 +1,64 @@ package vmlang.common import collection.immutable.HashMap abstract class OptParser { def numArgs(n:Int):Boolean val argErrorMsg:String val knownFlags:List[String] val defaultOpts:Map[String,String] val help:String def run(args:List[String], flags:List[String], opts:Map[String,String]):Unit def main(as:Array[String]) = { val (args, flags, opts) = parse(as) // check num args if(!numArgs(args.length)) { println(argErrorMsg) println(help) } else { // check for unknown flags flags -- knownFlags match { case Nil => { // check for unknown opts opts.keySet.toList -- defaultOpts.keySet.toList match { case Nil => { // get opts val allOpts = defaultOpts ++ opts // run try { run(args, flags, allOpts) } catch { case FatalError(msg) => println(msg) } } case l:List[String] => { println("Unknown options: " + (l mkString ", ")) println(help) } } } case l:List[String] => { println("Unkown flags: " + (l mkString ", ")) println(help) } } } } private def parse(as:Array[String]) = { val (dashStarts, args) = as.toList partition { _ startsWith "-" } val (optArgs, flags) = dashStarts partition { _ exists { _ == '=' } } val opts = new HashMap[String,String] ++ (optArgs map { a => { val s = (a substring 1) split '='; (s(0), s(1)) } } ) - (args, flags, opts) + (args, flags map { _ substring 1 }, opts) } } case class FatalError(msg:String) extends Exception diff --git a/src/vmlang/compiler/AST.scala b/src/vmlang/compiler/AST.scala index 5491f0a..5e84fa1 100644 --- a/src/vmlang/compiler/AST.scala +++ b/src/vmlang/compiler/AST.scala @@ -1,29 +1,29 @@ package vmlang.compiler.ast abstract class ASTNode case class Prog(defs:Map[String, Def]) extends ASTNode case class ParamSpec(name:String, argType:TypeExpr) extends ASTNode case class TypeExpr(name:String, args:List[TypeExpr]) extends ASTNode { + val isFunctionType = (name startsWith "Function") && !(name endsWith("Function")) override val toString = if(isFunctionType) args.init.mkString("(",",",")") + " => " + args.last else name + (if(args.isEmpty) "" else args.mkString("[",",","]")) val repr = if(isFunctionType) toString else name - val isFunctionType = (name startsWith "Function") && !(name endsWith("Function")) } abstract class IPromptStmt extends ASTNode case class Def(name:String, params:List[ParamSpec], returnType:TypeExpr, body:Expr) extends IPromptStmt abstract class Expr extends IPromptStmt case class IfExpr(condition:Expr, ifExpr:Expr, thenExpr:Expr) extends Expr case class Call(name:String, args:List[Expr]) extends Expr abstract class Atom extends Expr case class IntLit(value:Int) extends Atom case class FloatLit(value:Float) extends Atom case class CharLit(value:Char) extends Atom diff --git a/src/vmlang/compiler/Linearize.scala b/src/vmlang/compiler/Linearize.scala index 5dbeb14..a3cd391 100644 --- a/src/vmlang/compiler/Linearize.scala +++ b/src/vmlang/compiler/Linearize.scala @@ -1,189 +1,189 @@ package vmlang.compiler import java.io.{DataOutputStream, ByteArrayOutputStream} import collection.mutable.HashMap import vmlang.common.Opcodes import vmlang.common.Opcodes._ import vmlang.compiler.ast._ case class CheckedDef(params:List[(String,Int)], body:Expr) // shameful imperative code... object Linearize { def apply(prog:Map[String,CheckedDef]):Array[Byte] = new Linearizer(prog).run } class Linearizer(prog:Map[String,CheckedDef]) { type Scope = List[(String,Int)] private val baos = new ByteArrayOutputStream private val out = new DataOutputStream(baos) private val refs = new HashMap[Int,String] private val startingPoints = new HashMap[String,Int] def run:Array[Byte] = { wExpr(Call("main", Nil), Nil) w(STOP) for((n, d) <- prog) { startingPoints += (n -> out.size) wExpr(d.body, d.params) // goto return address (on stack) w(DEC_SP_INT) w(I_LOAD_A_SP) w(GOTO_A) } resolveGotos } private def resolveGotos:Array[Byte] = { val result = baos.toByteArray for((ind, ref) <- refs) { val refInd = startingPoints(ref) // write program index (integer) to result array result(ind+1) = (0xff & (refInd << 24)).asInstanceOf[Byte] result(ind+2) = (0xff & (refInd << 16)).asInstanceOf[Byte] result(ind+3) = (0xff & (refInd << 8)).asInstanceOf[Byte] result(ind+4) = (0xff & refInd).asInstanceOf[Byte] } result } private def w(oc:Opcodes):Unit = out.write(oc.toByte) private def w(oc:Opcodes, arg:Int):Unit = { w(oc); out.writeInt(arg) } private def w(oc:Opcodes, arg:Float):Unit = { w(oc); out.writeFloat(arg) } private def w(oc:Opcodes, arg:Byte):Unit = { w(oc); out.writeByte(arg) } private def wExpr(e:Expr, s:Scope):Unit = e match { case IntLit(i) => w(I_CONST_A, i); w(I_STORE_A_SP); w(INC_SP_INT) case CharLit(c) => w(B_CONST_A, c.toByte); w(B_STORE_A_SP); w(INC_SP) - case FloatLit(f) => w(I_CONST_A, f); w(I_STORE_A_SP); w(INC_SP_INT) + case FloatLit(f) => w(I_CONST_A, java.lang.Float.floatToIntBits(f)); w(I_STORE_A_SP); w(INC_SP_INT) case Call("+", List(a, b)) => intOp(a, b, s, ()=>{ w(I_ADD) }) case Call("-", List(a, b)) => intOp(a, b, s, ()=>{ w(I_SUB) }) case Call("*", List(a, b)) => intOp(a, b, s, ()=>{ w(I_MUL) }) case Call("/", List(a, b)) => intOp(a, b, s, ()=>{ w(I_DIV) }) case Call("%", List(a, b)) => intOp(a, b, s, ()=>{ w(I_MOD) }) case Call("==", List(a, b)) => cmpOp(a, b, s, ()=>{ w(EQ_A) }) case Call(">" , List(a, b)) => cmpOp(a, b, s, ()=>{ w(GT_A) }) case Call("<" , List(a, b)) => cmpOp(a, b, s, ()=>{ w(LT_A) }) case Call(">=", List(a, b)) => cmpOp(a, b, s, ()=>{ w(LT_A); w(NEG_A) }) case Call("<=", List(a, b)) => cmpOp(a, b, s, ()=>{ w(GT_A); w(NEG_A) }) case Call("and", List(a, b)) => byteOp(a, b, s, ()=>{ w(AND) }) case Call("or" , List(a, b)) => byteOp(a, b, s, ()=>{ w(OR) }) case Call("not", List(a)) => wExpr(a, s); wPopByteA; w(NEG_A); wPushByte() case Call("true" , Nil) => w(B_CONST_A, 1:Byte); wPushByte case Call("false", Nil) => w(B_CONST_A, 0:Byte); wPushByte case Call("null" , Nil) => // do nothing case Call("printInt", List(a)) => wExpr(a, s); wPopIntA; w(PRINT_INT_A) case Call(name, args) => argOffset(name, s) match { case Some(offset) => w(MOVE_BP_A) w(I_CONST_B, offset) w(I_SUB) w(I_LOAD_A_A) w(I_STORE_A_SP) w(INC_SP_INT) case None => (args foreach { wExpr(_, s) }) wCallPrelude wGoto(name) wCallPostlude(prog(name).params.foldLeft(0){ _ + _._2}) // retrieve returned value } } private def argOffset(name:String, scope:Scope):Option[Int] = (scope findIndexOf { _._1 == name }) match { case -1 => None case index => Some((scope drop index).foldLeft(0){ _ + _._2 }) } private def wCallPrelude = { // push base pointer w(MOVE_BP_A) w(I_STORE_A_SP) w(INC_SP_INT) // push program address w(MOVE_COUNTER_A) w(I_CONST_B, 12) w(I_ADD) w(I_STORE_A_SP) w(INC_SP_INT) } private def wGoto(ref:String) { refs += (out.size -> ref) w(GOTO, 0) // the 0 will be replaced in resolveGotos } private def wCallPostlude(paramSize:Int) = { // load answer into BP w(INC_SP_INT) w(I_LOAD_BP_SP) // save answer from BP to stack w(MOVE_SP_A) w(I_CONST_B, paramSize + 8) w(I_SUB) w(MOVE_A_SP) w(I_STORE_BP_SP) // get BP from stack w(MOVE_SP_A) w(I_CONST_B, paramSize) w(I_ADD) w(MOVE_A_SP) w(I_LOAD_BP_SP) // move SP back to operand stack w(MOVE_SP_A) w(I_CONST_B, paramSize) w(I_SUB) w(MOVE_A_SP) } private def cmpOp(a:Expr, b:Expr, s:Scope, cmp:()=>Unit) = intOp(a, b, s, { w(I_SUB); cmp(); wPushByte }) private def intOp(a:Expr, b:Expr, s:Scope, ops:()=>Unit) = { intOpNoPush(a, b, s, ops) wPushInt } private def intOpNoPush(a:Expr, b:Expr, s:Scope, ops:()=>Unit) = { wExpr(a, s) wExpr(b, s) wPopIntB wPopIntA ops() } private def byteOp(a:Expr, b:Expr, s:Scope, ops:()=>Unit) = { byteOpNoPush(a, b, s, ops) wPushByte } private def byteOpNoPush(a:Expr, b:Expr, s:Scope, ops:()=>Unit) = { wExpr(a, s) wExpr(b, s) wPopByteB wPopByteA ops() } private def wPopIntA = { w(DEC_SP_INT); w(I_LOAD_A_SP) } private def wPopIntB = { w(DEC_SP_INT); w(I_LOAD_B_SP) } private def wPushInt = { w(I_STORE_A_SP); w(INC_SP_INT) } private def wPopByteA = { w(DEC_SP); w(B_LOAD_A_SP) } private def wPopByteB = { w(DEC_SP); w(B_LOAD_B_SP) } private def wPushByte() = { w(DEC_SP); w(B_STORE_A_SP); } } diff --git a/src/vmlang/compiler/Main.scala b/src/vmlang/compiler/Main.scala new file mode 100644 index 0000000..27fdfbb --- /dev/null +++ b/src/vmlang/compiler/Main.scala @@ -0,0 +1,80 @@ +package vmlang.compiler + +import vmlang.common.{OptParser, FatalError} +import vmlang.compiler.typecheck.TypeCheck +import vmlang.compiler.ast._ +import vmlang.vm.{VM, VMError} + +import collection.mutable.HashMap + +import java.util.Scanner +import java.io.{File, FileOutputStream, FileNotFoundException, IOException} +import io.Source + +object Main extends OptParser { + + def numArgs(n:Int) = n == 0 || n == 1 + val argErrorMsg = "supply 1 file to compile, or no argument for interactive prompt" + val knownFlags = List("v") + val defaultOpts = Map[String,String]() + val help = "usage: vmlangc <optional source file> <options>\n" + + "-v print out messages about what the compiler is doing" + + def run(args:List[String], flags:List[String], opts:Map[String,String]):Unit = + args match { + case Nil => runIPrompt + case List(fn) => + try { + writeFile(Compile(loadFile(fn)), (fn split '.')(0) + ".vmlc") + } catch { + case e:CompilerError => throw FatalError(e.repr) + } + } + + def runIPrompt = { + val s = new Scanner(System.in) + var counter = 0 + var defs = Map[String,Def]() + while(true) { + print(">> ") + try { + val input = s.nextLine + if(input startsWith ":t ") { + println(TypeCheck.inferType(Parse.parseExpr(input substring 3))) + } else { + Parse.parseIPromptStmt(input) match { + case e:Expr => + defs = defs + ("main" -> Def("main", Nil, TypeExpr("Null",Nil), e match { + case Call("printInt",args) => e + case expr => Call("printInt",List(expr)) + })) + case d:Def => + defs = defs + (d.name -> d) + } + val code = Linearize(Simplify(TypeCheck(Prog(defs)))) + new VM(code, 1024, 1024).run + } + } catch { + case e:CompilerError => println(e.repr) + case e:VMError => println(e.getMessage) + } + } + } + + def writeFile(output:Array[Byte], fileName:String):Unit = + try { + new FileOutputStream(new File(fileName)).write(output) + } catch { + case e:FileNotFoundException => throw FatalError("Error creating file " + fileName) + case e:IOException => throw FatalError("Error writing file " + fileName) + } + + def loadFile(fileName:String):String = + try { + Source.fromFile(fileName).getLines.mkString + } catch { + case e:FileNotFoundException => throw FatalError("File not found: " + fileName) + case e:IOException => throw FatalError("Error reading file " + fileName) + } + +} diff --git a/src/vmlang/compiler/Parse.scala b/src/vmlang/compiler/Parse.scala index 03e501e..05f9ce8 100644 --- a/src/vmlang/compiler/Parse.scala +++ b/src/vmlang/compiler/Parse.scala @@ -1,125 +1,140 @@ package vmlang.compiler import vmlang.compiler.ast._ import util.parsing.combinator.syntactical._ import runtime.RichString import collection.immutable.HashMap case class ParserError(msg:String) extends NormalCompilerError { val repr = "Parser Error: " + msg } case object TooManyParams extends ParserError("can't make a function with more than 9 params") object Parse extends StandardTokenParsers { lexical.delimiters ++= List("+","-","*","/","(",")","[","]","=","=>",":",",",">","<", ">=","<=","==","!","!=") lexical.reserved ++= List("if","then","else","and","or") // RULES // TODO: duplicates get run over... def program = (definition *) ^^ { l => Prog(new HashMap[String,Def] ++ { l map { d => (d.name, d) } }) } def iPromptStmt = ( definition | expr ) def definition = ident ~ (paramsSpec?) ~ typeSpec ~ ("=" ~> expr) ^^ { case i ~ Some(ps) ~ rt ~ e => Def(i, checkPs(ps), rt, e) case i ~ None ~ rt ~ e => Def(i, Nil, rt, e) } def checkPs(ps:List[ParamSpec]) = if(ps.length <= 9) ps else throw TooManyParams def paramsSpec = "(" ~> repsep(paramSpec, ",") <~ ")" def paramSpec = ident ~ typeSpec ^^ { case i ~ t => ParamSpec(i,t) } def typeSpec = ":" ~> typeExpr def typeExpr:Parser[TypeExpr] = ( normalTypeExpr | funcTypeExpr ) def normalTypeExpr:Parser[TypeExpr] = ident ~ (typeParams?) ^^ { case i ~ Some(tp) => TypeExpr(i, tp) case i ~ None => TypeExpr(i, Nil) } def funcTypeExpr:Parser[TypeExpr] = ("(" ~> repsep(typeExpr,",") <~ ")") ~ ("=>" ~> typeExpr) ^^ { case pts ~ rt => mkFuncTypeExpr(pts, rt) } def mkFuncTypeExpr(paramTypes:List[TypeExpr], returnType:TypeExpr):TypeExpr = if(paramTypes.length <= 9) TypeExpr("Function" + paramTypes.length, paramTypes ::: List(returnType)) else throw TooManyParams def typeParams = "[" ~> repsep(typeExpr,",") <~ "]" def expr:Parser[Expr] = ( ifStatement | orExpr ) def ifStatement = (("if" ~> orExpr) ~ ("then" ~> orExpr) ~ ("else" ~> orExpr)) ^^ { case c ~ i ~ e => IfExpr(c,i,e) } def orExpr = andExpr * ( "or" ^^^ { (a:Expr, b:Expr) => Call("or",List(a,b)) } ) def andExpr = comparison * ( "and" ^^^ { (a:Expr, b:Expr) => Call("and",List(a,b)) } ) def comparison = sum * ( ">" ^^^ { (a:Expr, b:Expr) => Call(">",List(a,b)) } | "<" ^^^ { (a:Expr, b:Expr) => Call("<",List(a,b)) } | "==" ^^^ { (a:Expr, b:Expr) => Call("==",List(a,b)) } | "<=" ^^^ { (a:Expr, b:Expr) => Call("<=",List(a,b)) } | ">=" ^^^ { (a:Expr, b:Expr) => Call(">=",List(a,b)) } | "!=" ^^^ { (a:Expr, b:Expr) => Call("!=",List(a,b)) } ) // I'm sure there's a super-elegant way to do this, // but my Scala chops aren't up to it yet def sum = product * ( "+" ^^^ { (a:Expr, b:Expr) => Call("+",List(a,b)) } | "-" ^^^ { (a:Expr, b:Expr) => Call("-",List(a,b)) } ) def product = atom * ( "*" ^^^ { (a:Expr, b:Expr) => Call("*",List(a,b)) } | "/" ^^^ { (a:Expr, b:Expr) => Call("/",List(a,b)) } ) def atom = ( int | list | string | call | parenthesizedExpr | unaryMinus | unaryNot ) // todo: char lit (not in standardtokenparsers...) def list = "[" ~> repsep(expr,",") <~ "]" ^^ concatIze def string = stringLit ^^ { (s:String) => concatIze(new RichString(s) map { CharLit(_) }) } def concatIze(items:Seq[Expr]):Expr = items.foldRight(Call("EmptyList",Nil).asInstanceOf[Expr]){ (i,a) => Call(":",List(i,a)) } def parenthesizedExpr = "(" ~> expr <~ ")" def unaryNot:Parser[Expr] = "not" ~> atom ^^ { a => Call("not",List(a)) } def unaryMinus:Parser[Expr] = "-" ~> atom ^^ { a => Call("*",List(a,IntLit(-1))) } def int = numericLit ^^ { s => IntLit(s.toInt) } def call = ident ~ (args ?) ^^ { case i ~ Some(a) => Call(i,a) case i ~ None => Call(i,Nil) } def args = "(" ~> repsep(expr,",") <~ ")" // END OF RULES def parse(s:String) = phrase(program)(new lexical.Scanner(s)) def parseTypeExpr(t:String) = phrase(typeExpr)(new lexical.Scanner(t)) match { case Success(t, _) => t case e: NoSuccess => - throw new IllegalArgumentException(e.toString) + throw new ParserError(e.toString) } + def parseIPromptStmt(s:String) = { + phrase(iPromptStmt)(new lexical.Scanner(s)) match { + case Success(t, _) => t + case e: NoSuccess => + throw ParserError(e.toString) + } + } + + def parseExpr(s:String) = + phrase(expr)(new lexical.Scanner(s)) match { + case Success(t, _) => t + case e: NoSuccess => + throw new ParserError(e.toString) + } + def apply(s:String) = { parse(s) match { case Success(tree, _) => tree case e: NoSuccess => throw ParserError(e.toString) } } } diff --git a/src/vmlang/compiler/typecheck/TypeCheck.scala b/src/vmlang/compiler/typecheck/TypeCheck.scala index 5b4b765..a7010d6 100644 --- a/src/vmlang/compiler/typecheck/TypeCheck.scala +++ b/src/vmlang/compiler/typecheck/TypeCheck.scala @@ -1,135 +1,138 @@ package vmlang.compiler.typecheck import vmlang.compiler.ast._ import collection.immutable.{ Map, HashMap } object TypeCheck { val typeTree = TypeTree(AbsType("Value",0),List( TypeTree(AbsType("Function",0),List( TypeTree(RefType("Function0",1),Nil), TypeTree(RefType("Function1",2),Nil), TypeTree(RefType("Function2",3),Nil), TypeTree(RefType("Function3",4),Nil), TypeTree(RefType("Function4",5),Nil), TypeTree(RefType("Function5",6),Nil), TypeTree(RefType("Function6",7),Nil), TypeTree(RefType("Function7",8),Nil), TypeTree(RefType("Function8",9),Nil), TypeTree(RefType("Function9",10),Nil))), TypeTree(PrimType("Int",4),Nil), TypeTree(PrimType("Bool",1),Nil), TypeTree(PrimType("Null",0),Nil))) type FuncTable = Map[String,TypeExpr] type Scope = Map[String,TypeExpr] val rootFuncTypes = new HashMap[String, TypeExpr] ++ (List( ("+" , "(Int, Int) => Int" ), ("-" , "(Int, Int) => Int" ), ("*" , "(Int, Int) => Int" ), ("/" , "(Int, Int) => Int" ), ("==" , "(Int, Int) => Bool" ), ("!=" , "(Int, Int) => Bool" ), (">" , "(Int, Int) => Bool" ), (">=" , "(Int, Int) => Bool" ), ("<" , "(Int, Int) => Bool" ), ("<=" , "(Int, Int) => Bool" ), ("true" , "() => Bool" ), ("false" , "() => Bool" ), ("null" , "() => Null" ), ("and" , "(Bool, Bool) => Bool" ), ("or" , "(Bool, Bool) => Bool" ), ("not" , "(Bool) => Bool" ), ("printInt" , "(Int) => Null" ) - ) map { tp => (tp._1, Parser.parseTypeExpr(tp._2)) }) + ) map { tp => (tp._1, Parse.parseTypeExpr(tp._2)) }) def apply(prog:Prog):Map[String,CheckedDef] = apply(prog, rootFuncTypes, typeTree) def apply(prog:Prog, ft:FuncTable, tt:TypeTree):Map[String,CheckedDef] = (checkForMain(prog) ::: checkCompliance(prog, addTypeSigs(ft, prog), tt)) match { case Nil => Map[String,CheckedDef]() ++ (prog.defs map { case (n, d) => (n -> CheckedDef(d.params map { ps => { (ps.name, (tt find ps.argType.name).size) } }, d.body) ) }) case l => throw new TypeErrors(l) } private def checkForMain(prog:Prog):List[TypeError] = (prog.defs get "main") match { case Some(d) => (d.returnType == TypeExpr("Null",Nil) && d.params == Nil) match { case true => Nil case false => List(InvalidMainError(mkFuncTypeExpr(d))) } case None => List(NoMainError) } private def addTypeSigs(ft:FuncTable, p:Prog):FuncTable = p.defs.foldLeft(ft){ (ft, d) => ft + (d._1 -> mkFuncTypeExpr(d._2)) } private def mkFuncTypeExpr(d:Def):TypeExpr = TypeExpr("Function" + d.params.length, (d.params map { _.argType }) ::: List(d.returnType)) private def checkCompliance(p:Prog, ft:FuncTable, tt:TypeTree):List[TypeError] = p.defs.toList flatMap { m => checkDef(m._2, ft, tt) } private def checkDef(d:Def, ft:FuncTable, tt:TypeTree):List[TypeError] = { val s = Map() ++ (d.params map { ps => (ps.name, ps.argType) }) checkCalls(d.body, s, ft, tt) match { case Nil => tt.complies(d.returnType, inferType(d.body, s, ft, tt)) case l => l } } private def checkCalls(e:Expr, s:Scope, ft:FuncTable, tt:TypeTree):List[TypeError] = e match { case a:Atom => Nil case IfExpr(i, c, e) => checkCalls(List(i, c, e), s, ft, tt) - case c:Call => checkCall(c, s, ft, tt) ::: checkCalls(c.args, s, ft, tt) + case c:Call => checkCall(c, s, ft, tt) } private def checkCalls(es:List[Expr], s:Scope, ft:FuncTable, tt:TypeTree):List[TypeError] = es flatMap { e => checkCalls(e, s, ft, tt) } def checkCall(call:Call, scope:Scope, ft:FuncTable, tt:TypeTree):List[TypeError] = { val giv = call.args (scope get call.name) match { case Some(_) => Nil case None => (ft get call.name) match { case Some(funcType) => { val exp = funcType.args.init (if(exp.length == giv.length) Nil else List(WrongNumCallArgs(exp.length, giv.length))) ::: checkArgCompliance(exp, giv, scope, ft, tt) } case None => List(NonexistentFuncError(call.name)) } } } private def checkArgCompliance(expTypes:List[TypeExpr], args:List[Expr], s:Scope, ft:FuncTable, tt:TypeTree):List[TypeError] = (expTypes zip args) flatMap { case (et, e) => checkCalls(e, s, ft, tt) match { case Nil => tt.complies(et, inferType(e, s, ft, tt)) case l => l } } - def inferType(expr:Expr, ft:FuncTable, tt:TypeTree):TypeExpr = - inferType(expr, Map(), ft, tt) + def inferType(expr:Expr):TypeExpr = // for outside use + checkCalls(expr, Map[String,TypeExpr](), rootFuncTypes, typeTree) match { + case Nil => inferType(expr, Map(), rootFuncTypes, typeTree) + case es => throw TypeErrors(es) + } - def inferType(expr:Expr, scope:Scope, ft:FuncTable, tt:TypeTree):TypeExpr = { + private def inferType(expr:Expr, s:Scope, ft:FuncTable, tt:TypeTree):TypeExpr = { expr match { case IntLit(_) => TypeExpr("Int",Nil) case CharLit(_) => TypeExpr("Char",Nil) case FloatLit(_) => TypeExpr("Float",Nil) - case IfExpr(_, i, t) => tt.deepestCommonAncestor(inferType(i, ft, tt), - inferType(t, ft, tt)) - case c:Call => if(isParam(c, scope)) scope(c.name) else ft(c.name).args.last + case IfExpr(_, i, t) => tt.deepestCommonAncestor(inferType(i, s, ft, tt), + inferType(t, s, ft, tt)) + case c:Call => if(isParam(c, s)) s(c.name) else ft(c.name).args.last } } private def isParam(call:Call, scope:Scope):Boolean = call.args.isEmpty && (scope isDefinedAt call.name) } diff --git a/src/vmlang/disassembler/Main.scala b/src/vmlang/disassembler/Main.scala new file mode 100644 index 0000000..d1e5541 --- /dev/null +++ b/src/vmlang/disassembler/Main.scala @@ -0,0 +1,46 @@ +package vmlang.disassembler + +import vmlang.common.{OptParser, FatalError, Opcodes} +import vmlang.common.Opcodes._ + +import java.io.{File, FileInputStream, DataInputStream, FileNotFoundException, IOException, EOFException} + +object Main extends OptParser { + + def numArgs(n:Int) = n == 1 + val argErrorMsg = "supply 1 bytecode file to disassemble" + val knownFlags = List() + val defaultOpts = Map[String,String]() + val help = "usage: vmlangd <bytecode file>\n" + + def run(args:List[String], flags:List[String], opts:Map[String,String]):Unit = + disassemble(args.head) + + def disassemble(fileName:String) = + try { + var addr = 0 + val in = new DataInputStream(new FileInputStream(new File(fileName))) + val ocs = Opcodes.values + while(in.available > 0) { + print(addr + "\t") + val oc = ocs(in.readByte) + addr += 1 + print(oc + "\t") + oc match { + case I_CONST_A => print(in.readInt); addr += 4 + case I_CONST_B => print(in.readInt); addr += 4 + case B_CONST_A => print(in.readByte); addr += 1 + case B_CONST_B => print(in.readByte); addr += 1 + case GOTO => print(in.readInt); addr += 4 + case _ => + } + println + } + } catch { + case e:FileNotFoundException => throw FatalError("File not found: " + fileName) + case e:EOFException => throw FatalError("malformed program") + case e:ArrayIndexOutOfBoundsException => throw FatalError("malformed program") + case e:IOException => throw FatalError("Error reading file " + fileName) + } + +} diff --git a/src/vmlang/vm/Main.scala b/src/vmlang/vm/Main.scala index b29dde1..8e9d5d3 100644 --- a/src/vmlang/vm/Main.scala +++ b/src/vmlang/vm/Main.scala @@ -1,51 +1,51 @@ package vmlang.vm import java.io.{File, FileInputStream, FileNotFoundException, IOException} import vmlang.common.{OptParser, FatalError} object Main extends OptParser { def numArgs(n:Int) = n == 1 - val argErrorMsg = "supply 1 executable file to run" + val argErrorMsg = "supply 1 bytecode file to run" val knownFlags = List() val defaultOpts = Map("heap_size" -> "1024", "stack_size" -> "1024") - val help = "usage: *language name* <executable_file> <options>\n" + + val help = "usage: vmlang <bytecode file> <options>\n" + "-heap_size=<num bytes> heap size in bytes\n" + "-stack_size=<num bytes> stack size in bytes" def run(args:List[String], flags:List[String], opts:Map[String,String]):Unit = { val heapSize = try { opts("heap_size").toInt } catch { case e:NumberFormatException => throw FatalError("Invalid heap size argument") } val stackSize = try { opts("stack_size").toInt } catch { case e:NumberFormatException => throw FatalError("Invalid stack size argument") } // business time try { new VM(loadFileBytes(args(0)), heapSize, stackSize).run } catch { case e:InitError => throw FatalError("Couldn't start VM: " + e.message) case e:MalformedProgramError => throw FatalError("VM error: malformed program") case e:StackOverflowError => throw FatalError("VM error: stack overflow") } } def loadFileBytes(fileName:String):Array[Byte] = { try { val in = new FileInputStream(new File(fileName)) val result = new Array[Byte](in.available) in.read(result) result } catch { case e:FileNotFoundException => throw FatalError("File not found: " + fileName) case e:IOException => throw FatalError("Error reading file " + fileName) } } }
vilterp/VMLang
36e285e6b1312fd7272870bd13e315e7626f8ada
main:Null = printInt(2+3*4) compiles and runs w00t
diff --git a/src/vmlang/common/Opcodes.java b/src/vmlang/common/Opcodes.java index 703bae2..9d7e04e 100644 --- a/src/vmlang/common/Opcodes.java +++ b/src/vmlang/common/Opcodes.java @@ -1,48 +1,62 @@ package vmlang.common; public enum Opcodes { STOP, GOTO, GOTO_A, IF_EQ, IF_LT, I_CONST_A, I_CONST_B, B_CONST_A, B_CONST_B, I_LOAD_A_SP, + I_LOAD_A_A, + I_LOAD_BP_SP, I_LOAD_B_SP, I_LOAD_SP_SP, B_LOAD_A_SP, + B_LOAD_A_A, B_LOAD_B_SP, I_STORE_A_SP, + I_STORE_BP_SP, B_STORE_A_SP, MOVE_COUNTER_A, MOVE_SP_A, MOVE_BP_A, MOVE_A_SP, MOVE_A_BP, I_ADD, I_SUB, I_MUL, I_DIV, I_MOD, + F_ADD, + F_SUB, + F_MUL, + F_DIV, + F_MOD, INC_A, INC_B, INC_SP, + INC_SP_INT, DEC_A, DEC_B, DEC_SP, + DEC_SP_INT, NEG_A, - NEG_LT_A, + EQ_A, + LT_A, + GT_A, AND, OR, PRINT_CHAR_A, + PRINT_INT_A, READ_CHAR_A, STACK_START; public byte toByte() { return (byte)ordinal(); } } diff --git a/src/vmlang/compiler/parse/AST.scala b/src/vmlang/compiler/AST.scala similarity index 95% rename from src/vmlang/compiler/parse/AST.scala rename to src/vmlang/compiler/AST.scala index e814bf6..5491f0a 100644 --- a/src/vmlang/compiler/parse/AST.scala +++ b/src/vmlang/compiler/AST.scala @@ -1,29 +1,29 @@ package vmlang.compiler.ast abstract class ASTNode -case class Prog(defs:List[Def]) extends ASTNode +case class Prog(defs:Map[String, Def]) extends ASTNode case class ParamSpec(name:String, argType:TypeExpr) extends ASTNode case class TypeExpr(name:String, args:List[TypeExpr]) extends ASTNode { override val toString = if(isFunctionType) args.init.mkString("(",",",")") + " => " + args.last else name + (if(args.isEmpty) "" else args.mkString("[",",","]")) val repr = if(isFunctionType) toString else name val isFunctionType = (name startsWith "Function") && !(name endsWith("Function")) } abstract class IPromptStmt extends ASTNode case class Def(name:String, params:List[ParamSpec], returnType:TypeExpr, body:Expr) extends IPromptStmt abstract class Expr extends IPromptStmt case class IfExpr(condition:Expr, ifExpr:Expr, thenExpr:Expr) extends Expr case class Call(name:String, args:List[Expr]) extends Expr abstract class Atom extends Expr case class IntLit(value:Int) extends Atom case class FloatLit(value:Float) extends Atom case class CharLit(value:Char) extends Atom diff --git a/src/vmlang/compiler/Compile.scala b/src/vmlang/compiler/Compile.scala new file mode 100644 index 0000000..0ea4781 --- /dev/null +++ b/src/vmlang/compiler/Compile.scala @@ -0,0 +1,9 @@ +package vmlang.compiler + +import vmlang.compiler.typecheck.TypeCheck + +object Compile { + + def apply(prog:String):Array[Byte] = Linearize(TypeCheck(Parse(prog))) + +} diff --git a/src/vmlang/compiler/Errors.scala b/src/vmlang/compiler/Errors.scala index 0f3ec41..b357621 100644 --- a/src/vmlang/compiler/Errors.scala +++ b/src/vmlang/compiler/Errors.scala @@ -1,20 +1,16 @@ package vmlang.compiler abstract class CompilerError extends Exception { val numErrors:Int val repr:String } // TODO: should have location, but can't implement - scala's combinator library drops it abstract class NormalCompilerError extends CompilerError { val numErrors = 1 } abstract class CompoundCompilerError(errors:List[CompilerError]) extends CompilerError { val numErrors = errors.length val repr:String = (errors map { _.repr } ) mkString "\n" } - -case class NonexistentFuncError(funcName:String) extends NormalCompilerError { - val repr = "Call to nonexistent function " + funcName -} diff --git a/src/vmlang/compiler/Linearize.scala b/src/vmlang/compiler/Linearize.scala index 1063296..5dbeb14 100644 --- a/src/vmlang/compiler/Linearize.scala +++ b/src/vmlang/compiler/Linearize.scala @@ -1,54 +1,189 @@ -// package vmlang.compiler -// -// import vmlang.compiler.ast._ -// import vmlang.compiler.model._ -// import vmlang.compiler.icode._ // group these imports into one? -// import collection.immutable.Map -// -// object Compiler { -// -// def apply(funcTable:Map[String,Function]):List[(String,List[IOpcode])] = { -// (funcTable("main") match { -// case Some(f) => ("main",compFunc(f)) -// case None => throw new NonexistentFuncError("main","[compiler]") -// }) ::: ((funcTable - "main") map { p => (p._1,compFunc(p._2)) } ) -// } -// -// def compFunc(f:Function):List[IOpcode] = f match { -// case PrimFunc(code) => code -// case NormFunc(expr) => compExpr(expr) -// } -// -// def compExpr(e:Expr):List[IOpcode] = e match { -// -// // TODO: time complexity of ":::" -- are all these calls gonna kill us? -// -// case Call("+",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(AddI) -// case Call("-",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(SubI) -// case Call("*",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(MultI) -// case Call("/",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(DivI) -// -// case Call("==",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(CmpEq) -// case Call("!=",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(CmpNeq) -// case Call(">",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(CmpGt) -// case Call(">=",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(CmpGte) -// case Call("<",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(CmpLt) -// case Call("<=",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(CmpLte) -// -// case Call("true",_) => List(PushConstI(1)) -// case Call("false",_) => List(PushConstI(0)) -// -// case Call("printChar",List(e)) => compExpr(e) ::: List(PrintChar) -// case Call("readChar",_) => List(ReadChar) -// -// case Call(name,args) => (args flatMap comExpr) ::: Nil -// -// case Integer(v) => List(PushConstI(v)) -// case Char(c) => List(PushConstC(c)) -// -// case IfExpr(c,i,e) => { val el = compExpr(e) -// compExpr(c) ::: List(GotoIf(el.head)) ::: compExpr(i) ::: el } -// -// } -// -// } +package vmlang.compiler + +import java.io.{DataOutputStream, ByteArrayOutputStream} +import collection.mutable.HashMap + + +import vmlang.common.Opcodes +import vmlang.common.Opcodes._ +import vmlang.compiler.ast._ + +case class CheckedDef(params:List[(String,Int)], body:Expr) + +// shameful imperative code... + +object Linearize { + + def apply(prog:Map[String,CheckedDef]):Array[Byte] = new Linearizer(prog).run + +} + +class Linearizer(prog:Map[String,CheckedDef]) { + + type Scope = List[(String,Int)] + + private val baos = new ByteArrayOutputStream + private val out = new DataOutputStream(baos) + private val refs = new HashMap[Int,String] + private val startingPoints = new HashMap[String,Int] + + def run:Array[Byte] = { + wExpr(Call("main", Nil), Nil) + w(STOP) + for((n, d) <- prog) { + startingPoints += (n -> out.size) + wExpr(d.body, d.params) + // goto return address (on stack) + w(DEC_SP_INT) + w(I_LOAD_A_SP) + w(GOTO_A) + } + resolveGotos + } + + private def resolveGotos:Array[Byte] = { + val result = baos.toByteArray + for((ind, ref) <- refs) { + val refInd = startingPoints(ref) + // write program index (integer) to result array + result(ind+1) = (0xff & (refInd << 24)).asInstanceOf[Byte] + result(ind+2) = (0xff & (refInd << 16)).asInstanceOf[Byte] + result(ind+3) = (0xff & (refInd << 8)).asInstanceOf[Byte] + result(ind+4) = (0xff & refInd).asInstanceOf[Byte] + } + result + } + + private def w(oc:Opcodes):Unit = out.write(oc.toByte) + private def w(oc:Opcodes, arg:Int):Unit = { w(oc); out.writeInt(arg) } + private def w(oc:Opcodes, arg:Float):Unit = { w(oc); out.writeFloat(arg) } + private def w(oc:Opcodes, arg:Byte):Unit = { w(oc); out.writeByte(arg) } + + private def wExpr(e:Expr, s:Scope):Unit = e match { + + case IntLit(i) => w(I_CONST_A, i); w(I_STORE_A_SP); w(INC_SP_INT) + case CharLit(c) => w(B_CONST_A, c.toByte); w(B_STORE_A_SP); w(INC_SP) + case FloatLit(f) => w(I_CONST_A, f); w(I_STORE_A_SP); w(INC_SP_INT) + + case Call("+", List(a, b)) => intOp(a, b, s, ()=>{ w(I_ADD) }) + case Call("-", List(a, b)) => intOp(a, b, s, ()=>{ w(I_SUB) }) + case Call("*", List(a, b)) => intOp(a, b, s, ()=>{ w(I_MUL) }) + case Call("/", List(a, b)) => intOp(a, b, s, ()=>{ w(I_DIV) }) + case Call("%", List(a, b)) => intOp(a, b, s, ()=>{ w(I_MOD) }) + + case Call("==", List(a, b)) => cmpOp(a, b, s, ()=>{ w(EQ_A) }) + case Call(">" , List(a, b)) => cmpOp(a, b, s, ()=>{ w(GT_A) }) + case Call("<" , List(a, b)) => cmpOp(a, b, s, ()=>{ w(LT_A) }) + case Call(">=", List(a, b)) => cmpOp(a, b, s, ()=>{ w(LT_A); w(NEG_A) }) + case Call("<=", List(a, b)) => cmpOp(a, b, s, ()=>{ w(GT_A); w(NEG_A) }) + + case Call("and", List(a, b)) => byteOp(a, b, s, ()=>{ w(AND) }) + case Call("or" , List(a, b)) => byteOp(a, b, s, ()=>{ w(OR) }) + case Call("not", List(a)) => wExpr(a, s); wPopByteA; w(NEG_A); wPushByte() + + case Call("true" , Nil) => w(B_CONST_A, 1:Byte); wPushByte + case Call("false", Nil) => w(B_CONST_A, 0:Byte); wPushByte + case Call("null" , Nil) => // do nothing + + case Call("printInt", List(a)) => wExpr(a, s); wPopIntA; w(PRINT_INT_A) + + case Call(name, args) => argOffset(name, s) match { + case Some(offset) => + w(MOVE_BP_A) + w(I_CONST_B, offset) + w(I_SUB) + w(I_LOAD_A_A) + w(I_STORE_A_SP) + w(INC_SP_INT) + case None => + (args foreach { wExpr(_, s) }) + wCallPrelude + wGoto(name) + wCallPostlude(prog(name).params.foldLeft(0){ _ + _._2}) // retrieve returned value + } + + } + + private def argOffset(name:String, scope:Scope):Option[Int] = + (scope findIndexOf { _._1 == name }) match { + case -1 => None + case index => Some((scope drop index).foldLeft(0){ _ + _._2 }) + } + + private def wCallPrelude = { + // push base pointer + w(MOVE_BP_A) + w(I_STORE_A_SP) + w(INC_SP_INT) + // push program address + w(MOVE_COUNTER_A) + w(I_CONST_B, 12) + w(I_ADD) + w(I_STORE_A_SP) + w(INC_SP_INT) + } + + private def wGoto(ref:String) { + refs += (out.size -> ref) + w(GOTO, 0) // the 0 will be replaced in resolveGotos + } + + private def wCallPostlude(paramSize:Int) = { + // load answer into BP + w(INC_SP_INT) + w(I_LOAD_BP_SP) + // save answer from BP to stack + w(MOVE_SP_A) + w(I_CONST_B, paramSize + 8) + w(I_SUB) + w(MOVE_A_SP) + w(I_STORE_BP_SP) + // get BP from stack + w(MOVE_SP_A) + w(I_CONST_B, paramSize) + w(I_ADD) + w(MOVE_A_SP) + w(I_LOAD_BP_SP) + // move SP back to operand stack + w(MOVE_SP_A) + w(I_CONST_B, paramSize) + w(I_SUB) + w(MOVE_A_SP) + } + + private def cmpOp(a:Expr, b:Expr, s:Scope, cmp:()=>Unit) = + intOp(a, b, s, { w(I_SUB); cmp(); wPushByte }) + + private def intOp(a:Expr, b:Expr, s:Scope, ops:()=>Unit) = { + intOpNoPush(a, b, s, ops) + wPushInt + } + private def intOpNoPush(a:Expr, b:Expr, s:Scope, ops:()=>Unit) = { + wExpr(a, s) + wExpr(b, s) + wPopIntB + wPopIntA + ops() + } + + private def byteOp(a:Expr, b:Expr, s:Scope, ops:()=>Unit) = { + byteOpNoPush(a, b, s, ops) + wPushByte + } + private def byteOpNoPush(a:Expr, b:Expr, s:Scope, ops:()=>Unit) = { + wExpr(a, s) + wExpr(b, s) + wPopByteB + wPopByteA + ops() + } + + private def wPopIntA = { w(DEC_SP_INT); w(I_LOAD_A_SP) } + private def wPopIntB = { w(DEC_SP_INT); w(I_LOAD_B_SP) } + private def wPushInt = { w(I_STORE_A_SP); w(INC_SP_INT) } + + private def wPopByteA = { w(DEC_SP); w(B_LOAD_A_SP) } + private def wPopByteB = { w(DEC_SP); w(B_LOAD_B_SP) } + private def wPushByte() = { w(DEC_SP); w(B_STORE_A_SP); } + +} diff --git a/src/vmlang/compiler/parse/Parse.scala b/src/vmlang/compiler/Parse.scala similarity index 93% rename from src/vmlang/compiler/parse/Parse.scala rename to src/vmlang/compiler/Parse.scala index 7dddbb5..03e501e 100644 --- a/src/vmlang/compiler/parse/Parse.scala +++ b/src/vmlang/compiler/Parse.scala @@ -1,120 +1,125 @@ -package vmlang.compiler.ast +package vmlang.compiler -import scala.runtime.RichString -import scala.util.parsing.combinator.syntactical._ +import vmlang.compiler.ast._ + +import util.parsing.combinator.syntactical._ +import runtime.RichString + +import collection.immutable.HashMap case class ParserError(msg:String) extends NormalCompilerError { val repr = "Parser Error: " + msg } case object TooManyParams extends ParserError("can't make a function with more than 9 params") object Parse extends StandardTokenParsers { lexical.delimiters ++= List("+","-","*","/","(",")","[","]","=","=>",":",",",">","<", ">=","<=","==","!","!=") lexical.reserved ++= List("if","then","else","and","or") // RULES - def program = (definition *) ^^ { l => Prog(l) } + // TODO: duplicates get run over... + def program = (definition *) ^^ { l => Prog(new HashMap[String,Def] ++ { l map { d => (d.name, d) } }) } def iPromptStmt = ( definition | expr ) def definition = ident ~ (paramsSpec?) ~ typeSpec ~ ("=" ~> expr) ^^ { case i ~ Some(ps) ~ rt ~ e => Def(i, checkPs(ps), rt, e) case i ~ None ~ rt ~ e => Def(i, Nil, rt, e) } def checkPs(ps:List[ParamSpec]) = if(ps.length <= 9) ps else throw TooManyParams def paramsSpec = "(" ~> repsep(paramSpec, ",") <~ ")" def paramSpec = ident ~ typeSpec ^^ { case i ~ t => ParamSpec(i,t) } def typeSpec = ":" ~> typeExpr def typeExpr:Parser[TypeExpr] = ( normalTypeExpr | funcTypeExpr ) def normalTypeExpr:Parser[TypeExpr] = ident ~ (typeParams?) ^^ { case i ~ Some(tp) => TypeExpr(i, tp) case i ~ None => TypeExpr(i, Nil) } def funcTypeExpr:Parser[TypeExpr] = ("(" ~> repsep(typeExpr,",") <~ ")") ~ ("=>" ~> typeExpr) ^^ { case pts ~ rt => mkFuncTypeExpr(pts, rt) } def mkFuncTypeExpr(paramTypes:List[TypeExpr], returnType:TypeExpr):TypeExpr = if(paramTypes.length <= 9) TypeExpr("Function" + paramTypes.length, paramTypes ::: List(returnType)) else throw TooManyParams def typeParams = "[" ~> repsep(typeExpr,",") <~ "]" def expr:Parser[Expr] = ( ifStatement | orExpr ) def ifStatement = (("if" ~> orExpr) ~ ("then" ~> orExpr) ~ ("else" ~> orExpr)) ^^ { case c ~ i ~ e => IfExpr(c,i,e) } def orExpr = andExpr * ( "or" ^^^ { (a:Expr, b:Expr) => Call("or",List(a,b)) } ) def andExpr = comparison * ( "and" ^^^ { (a:Expr, b:Expr) => Call("and",List(a,b)) } ) def comparison = sum * ( ">" ^^^ { (a:Expr, b:Expr) => Call(">",List(a,b)) } | "<" ^^^ { (a:Expr, b:Expr) => Call("<",List(a,b)) } | "==" ^^^ { (a:Expr, b:Expr) => Call("==",List(a,b)) } | "<=" ^^^ { (a:Expr, b:Expr) => Call("<=",List(a,b)) } | ">=" ^^^ { (a:Expr, b:Expr) => Call(">=",List(a,b)) } | "!=" ^^^ { (a:Expr, b:Expr) => Call("!=",List(a,b)) } ) // I'm sure there's a super-elegant way to do this, // but my Scala chops aren't up to it yet def sum = product * ( "+" ^^^ { (a:Expr, b:Expr) => Call("+",List(a,b)) } | "-" ^^^ { (a:Expr, b:Expr) => Call("-",List(a,b)) } ) def product = atom * ( "*" ^^^ { (a:Expr, b:Expr) => Call("*",List(a,b)) } | "/" ^^^ { (a:Expr, b:Expr) => Call("/",List(a,b)) } ) def atom = ( int | list | string | call | parenthesizedExpr | unaryMinus | unaryNot ) // todo: char lit (not in standardtokenparsers...) def list = "[" ~> repsep(expr,",") <~ "]" ^^ concatIze def string = stringLit ^^ { (s:String) => concatIze(new RichString(s) map { CharLit(_) }) } def concatIze(items:Seq[Expr]):Expr = items.foldRight(Call("EmptyList",Nil).asInstanceOf[Expr]){ (i,a) => Call(":",List(i,a)) } def parenthesizedExpr = "(" ~> expr <~ ")" def unaryNot:Parser[Expr] = "not" ~> atom ^^ { a => Call("not",List(a)) } def unaryMinus:Parser[Expr] = "-" ~> atom ^^ { a => Call("*",List(a,IntLit(-1))) } def int = numericLit ^^ { s => IntLit(s.toInt) } def call = ident ~ (args ?) ^^ { case i ~ Some(a) => Call(i,a) case i ~ None => Call(i,Nil) } def args = "(" ~> repsep(expr,",") <~ ")" // END OF RULES def parse(s:String) = phrase(program)(new lexical.Scanner(s)) def parseTypeExpr(t:String) = phrase(typeExpr)(new lexical.Scanner(t)) match { case Success(t, _) => t case e: NoSuccess => throw new IllegalArgumentException(e.toString) } def apply(s:String) = { parse(s) match { case Success(tree, _) => tree case e: NoSuccess => throw ParserError(e.toString) } } } diff --git a/src/vmlang/compiler/Simplify.scala b/src/vmlang/compiler/Simplify.scala index 28f0c4b..4d5939f 100644 --- a/src/vmlang/compiler/Simplify.scala +++ b/src/vmlang/compiler/Simplify.scala @@ -1,41 +1,45 @@ package vmlang.compiler import vmlang.compiler.ast._ import collection.immutable.HashSet object Simplify { - def apply(prog:Prog) = Prog(prog.defs map { case Def(n,a,r,body) => Def(n,a,r,simplify(body)) }) + def apply(prog:Map[String,CheckedDef]) = + Map[String,CheckedDef]() ++ + (prog map { m => (m._1 -> CheckedDef(m._2.params, simplify(m._2.body))) }) def simplify(e:Expr):Expr = e match { case a:Atom => a case IfExpr(c,i,e) => (simplify(c), simplify(i), simplify(e)) match { case (Call("true",Nil), i, e) => i case (Call("false",Nil), i, e) => e case (c, i, e) => IfExpr(c, i, e) } case Call(n,args) => (n, args map simplify) match { case ("+" , List(IntLit(a),IntLit(b))) => IntLit(a + b) case ("-" , List(IntLit(a),IntLit(b))) => IntLit(a - b) case ("*" , List(IntLit(a),IntLit(b))) => IntLit(a * b) case ("/" , List(IntLit(a),IntLit(b))) => IntLit(a / b) case (">" , List(IntLit(a),IntLit(b))) => Call(if(a > b) "true" else "false", Nil) case (">=", List(IntLit(a),IntLit(b))) => Call(if(a >= b) "true" else "false", Nil) case ("<" , List(IntLit(a),IntLit(b))) => Call(if(a < b) "true" else "false", Nil) case ("<=", List(IntLit(a),IntLit(b))) => Call(if(a <= b) "true" else "false", Nil) case ("==", List(IntLit(a),IntLit(b))) => Call(if(a == b) "true" else "false", Nil) case ("not", List(Call("true",Nil))) => Call("false", Nil) case ("not", List(Call("false",Nil))) => Call("true", Nil) case ("and", List(Call(a,Nil),Call(b,Nil))) => Call(if(a == "true" && b == "true") "true" else "false", Nil) case ("or", List(Call(a,Nil),Call(b,Nil))) => Call(if(a == "true" || b == "true") "true" else "false", Nil) - + + case (n, args) => Call(n, args) + } } } diff --git a/src/vmlang/compiler/parse/NewParser.scala b/src/vmlang/compiler/parse/NewParser.scala deleted file mode 100644 index 1154cd0..0000000 --- a/src/vmlang/compiler/parse/NewParser.scala +++ /dev/null @@ -1,97 +0,0 @@ -// import scala.util.parsing.combinator._ -// import scala.util.parsing.input._ -// -// // Bug: CharSequenceReader eliminates spaces in strings ("hello there" => StringLit(hellothere)) -// -// object Test extends RegexParsers { -// -// def apply(input:String) = -// doRule(expr,input) match { -// case Success(t, _) => t -// case e: NoSuccess => throw new IllegalArgumentException(e.toString) -// } -// -// def doRule(rule:Parser[Any], input:String) = phrase(rule)(new CharSequenceReader(input)) -// -// def expr = ( float | int | variable | string | char ) -// -// def float = regex("""-?(\d+\.\d+|\.\d+)""".r) ~ (sciNot?) ^^ { -// case f ~ Some(s) => FloatLit(checkFloatSize(f,s)) -// case f ~ None => FloatLit(checkFloatSize(f,0)) } -// -// def int = regex("""-?\d+""".r) ~ (sciNot?) ^^ { -// case i ~ Some(s) => IntLit(checkIntSize(i,s)) -// case i ~ None => IntLit(checkIntSize(i,0)) } -// -// def checkIntSize(v:String, e:Int):Int = { -// val bi = BigInt(v) * (BigInt(10) pow e) -// if(bi > Math.MAX_INT) -// throw new IllegalArgumentException("int literal too big") -// else if(bi < Math.MIN_INT) -// throw new IllegalArgumentException("int literal too small") -// else -// bi.intValue -// } -// -// def checkFloatSize(v:String, e:Int):Float = { -// val bd = BigDecimal(v) * new BigDecimal(new java.math.BigDecimal(10) pow e) -// if(bd > BigDecimal(Math.MAX_FLOAT)) -// throw new IllegalArgumentException("float literal too big") -// else if(bd < BigDecimal(Math.MIN_FLOAT)) -// throw new IllegalArgumentException("float literal too small") -// else -// bd.floatValue -// } -// -// def sciNot = regex("""[eE]-?\d+""".r) ^^ { -// try { -// i => i.substring(1).toInt -// } catch { -// case c:NumberFormatException => throw new IllegalArgumentException("exponent too big") -// } } -// -// def string = "\"" ~> (stringChar*) <~ "\"" ^^ { l => StringLit(l.mkString) } // should actually map to list of char... -// -// def stringChar = ( unicodeChar | escapedCharInStr | normalCharInStr ) -// -// def char = "'" ~> ( unicodeChar | escapedCharInChar | normalCharInChar ) <~ "'" ^^ { c => CharLit(c) } -// -// def normalCharInChar = regex("""[ -&\(-~]""".r) ^^ { s => s charAt 0 } -// -// def escapedCharInChar = regex("""\\[nt']""".r) ^^ { case "\\n" => '\n' -// case "\\t" => '\t' -// case "\\'" => '\'' } -// -// def normalCharInStr = regex("""[ -!#-~]""".r) ^^ { s => s charAt 0 } -// -// def escapedCharInStr = regex("""\\[nt\"]""".r) ^^ { case "\\n" => '\n' -// case "\\t" => '\t' -// case "\\\"" => '"' } -// -// def unicodeChar = regex("""\\u[0-9a-f]{1,4}""".r) ^^ { s => Integer.parseInt(s substring 2,16).toChar } -// -// def variable = regex("""[a-zA-Z_]\w*""".r) ^^ { i => Var(i) } -// -// def main(args:Array[String]) = { -// List("123","-123","123.1234","123e4","hello","hello_o","HelloYo","_yo", -// "64654654654654645564654456564654654654654","5e65465465465465465","-.123","000.3","8e4","Infinity", -// "'a'","'!'","'\\n'","'\\u61'","'\\''", -// "\"Sup?\"","\"hey\\nthere\"","\"'that is cool'\"","\"\\\"\"") foreach test -// } -// -// def test(input:String) = println(input + " => " + { -// try { -// apply(input) -// } catch { -// case e: IllegalArgumentException => "error: " + e.getMessage -// } -// }) -// -// } -// -// abstract class Atom -// case class CharLit(value:Char) extends Atom -// case class FloatLit(value:Float) extends Atom -// case class IntLit(value:Int) extends Atom -// case class StringLit(value:String) extends Atom -// case class Var(name:String) extends Atom diff --git a/src/vmlang/compiler/typecheck/Type.scala b/src/vmlang/compiler/typecheck/Type.scala index f8ceb8d..52a5556 100644 --- a/src/vmlang/compiler/typecheck/Type.scala +++ b/src/vmlang/compiler/typecheck/Type.scala @@ -1,26 +1,28 @@ package vmlang.compiler.typecheck -import vmlang.compiler.ast._ - abstract class Type { val name:String val numParams:Int + val size:Int override def toString = name - def toTypeExpr = Parser.parseTypeExpr(toString) } -case class AbsType(name:String, numParams:Int) extends Type +case class AbsType(name:String, numParams:Int) extends Type { + val size = 4 // TODO: this is not right +} abstract class ConcreteType extends Type -case class RefType(name:String, numParams:Int) extends ConcreteType -case class PrimType(name:String) extends ConcreteType { +case class RefType(name:String, numParams:Int) extends ConcreteType { + val size = 4 +} +case class PrimType(name:String, size:Int) extends ConcreteType { val numParams = 0 } /* Type [AbsType] ConcreteType [RefType] [PrimType] */ diff --git a/src/vmlang/compiler/typecheck/TypeCheck.scala b/src/vmlang/compiler/typecheck/TypeCheck.scala index 9e6a143..5b4b765 100644 --- a/src/vmlang/compiler/typecheck/TypeCheck.scala +++ b/src/vmlang/compiler/typecheck/TypeCheck.scala @@ -1,125 +1,135 @@ package vmlang.compiler.typecheck import vmlang.compiler.ast._ import collection.immutable.{ Map, HashMap } object TypeCheck { val typeTree = TypeTree(AbsType("Value",0),List( TypeTree(AbsType("Function",0),List( TypeTree(RefType("Function0",1),Nil), TypeTree(RefType("Function1",2),Nil), TypeTree(RefType("Function2",3),Nil), TypeTree(RefType("Function3",4),Nil), TypeTree(RefType("Function4",5),Nil), TypeTree(RefType("Function5",6),Nil), TypeTree(RefType("Function6",7),Nil), TypeTree(RefType("Function7",8),Nil), TypeTree(RefType("Function8",9),Nil), TypeTree(RefType("Function9",10),Nil))), - TypeTree(AbsType("Eq",0),List( - TypeTree(PrimType("Bool"),Nil), - TypeTree(PrimType("Null"),Nil), - TypeTree(AbsType("Ord",0),List( - TypeTree(PrimType("Char"),Nil), - TypeTree(PrimType("Int"),Nil))))))) + TypeTree(PrimType("Int",4),Nil), + TypeTree(PrimType("Bool",1),Nil), + TypeTree(PrimType("Null",0),Nil))) type FuncTable = Map[String,TypeExpr] type Scope = Map[String,TypeExpr] val rootFuncTypes = new HashMap[String, TypeExpr] ++ (List( ("+" , "(Int, Int) => Int" ), ("-" , "(Int, Int) => Int" ), ("*" , "(Int, Int) => Int" ), ("/" , "(Int, Int) => Int" ), - ("==" , "(Eq, Eq) => Bool" ), - ("!=" , "(Eq, Eq) => Bool" ), - (">" , "(Ord, Ord) => Bool" ), - (">=" , "(Ord, Ord) => Bool" ), - ("<" , "(Ord, Ord) => Bool" ), - ("<=" , "(Ord, Ord) => Bool" ), + ("==" , "(Int, Int) => Bool" ), + ("!=" , "(Int, Int) => Bool" ), + (">" , "(Int, Int) => Bool" ), + (">=" , "(Int, Int) => Bool" ), + ("<" , "(Int, Int) => Bool" ), + ("<=" , "(Int, Int) => Bool" ), ("true" , "() => Bool" ), ("false" , "() => Bool" ), ("null" , "() => Null" ), ("and" , "(Bool, Bool) => Bool" ), ("or" , "(Bool, Bool) => Bool" ), ("not" , "(Bool) => Bool" ), - ("printChar" , "(Char) => Null" ), - ("getChar" , "() => Char" ), - ("stackStart" , "() => Int" ) + ("printInt" , "(Int) => Null" ) ) map { tp => (tp._1, Parser.parseTypeExpr(tp._2)) }) - def apply(prog:Prog):Prog = + def apply(prog:Prog):Map[String,CheckedDef] = apply(prog, rootFuncTypes, typeTree) - def apply(prog:Prog, ft:FuncTable, tt:TypeTree):Prog = - checkCompliance(prog, addTypeSigs(ft, prog), tt) + def apply(prog:Prog, ft:FuncTable, tt:TypeTree):Map[String,CheckedDef] = + (checkForMain(prog) ::: checkCompliance(prog, addTypeSigs(ft, prog), tt)) match { + case Nil => Map[String,CheckedDef]() ++ (prog.defs map { + case (n, d) => (n -> CheckedDef(d.params map { ps => { + (ps.name, (tt find ps.argType.name).size) + } }, d.body) ) + }) + case l => throw new TypeErrors(l) + } + + private def checkForMain(prog:Prog):List[TypeError] = + (prog.defs get "main") match { + case Some(d) => (d.returnType == TypeExpr("Null",Nil) && d.params == Nil) match { + case true => Nil + case false => List(InvalidMainError(mkFuncTypeExpr(d))) + } + case None => List(NoMainError) + } private def addTypeSigs(ft:FuncTable, p:Prog):FuncTable = - p.defs.foldLeft(ft){ (ft, d) => ft + (d.name -> TypeExpr("Function" + d.params.length, - (d.params map { _.argType }) ::: List(d.returnType))) } + p.defs.foldLeft(ft){ (ft, d) => ft + (d._1 -> mkFuncTypeExpr(d._2)) } - private def checkCompliance(p:Prog, ft:FuncTable, tt:TypeTree):Prog = - (p.defs flatMap { checkDef(_, ft, tt) }) match { - case Nil => p - case l => throw new TypeErrors(l.removeDuplicates) - } + private def mkFuncTypeExpr(d:Def):TypeExpr = + TypeExpr("Function" + d.params.length, (d.params map { _.argType }) ::: List(d.returnType)) + + private def checkCompliance(p:Prog, ft:FuncTable, tt:TypeTree):List[TypeError] = + p.defs.toList flatMap { m => checkDef(m._2, ft, tt) } - private def checkDef(d:Def, ft:FuncTable, tt:TypeTree):List[CompilerError] = { + private def checkDef(d:Def, ft:FuncTable, tt:TypeTree):List[TypeError] = { val s = Map() ++ (d.params map { ps => (ps.name, ps.argType) }) checkCalls(d.body, s, ft, tt) match { case Nil => tt.complies(d.returnType, inferType(d.body, s, ft, tt)) case l => l } } - private def checkCalls(e:Expr, s:Scope, ft:FuncTable, tt:TypeTree):List[CompilerError] = + private def checkCalls(e:Expr, s:Scope, ft:FuncTable, tt:TypeTree):List[TypeError] = e match { case a:Atom => Nil case IfExpr(i, c, e) => checkCalls(List(i, c, e), s, ft, tt) case c:Call => checkCall(c, s, ft, tt) ::: checkCalls(c.args, s, ft, tt) } - private def checkCalls(es:List[Expr], s:Scope, ft:FuncTable, tt:TypeTree):List[CompilerError] = + private def checkCalls(es:List[Expr], s:Scope, ft:FuncTable, tt:TypeTree):List[TypeError] = es flatMap { e => checkCalls(e, s, ft, tt) } - def checkCall(call:Call, scope:Scope, ft:FuncTable, tt:TypeTree):List[CompilerError] = { + def checkCall(call:Call, scope:Scope, ft:FuncTable, tt:TypeTree):List[TypeError] = { val giv = call.args (scope get call.name) match { case Some(_) => Nil case None => (ft get call.name) match { case Some(funcType) => { val exp = funcType.args.init (if(exp.length == giv.length) Nil else List(WrongNumCallArgs(exp.length, giv.length))) ::: - checkArgCompliance(exp, giv, scope, ft, tt) + checkArgCompliance(exp, giv, scope, ft, tt) } case None => List(NonexistentFuncError(call.name)) } } } private def checkArgCompliance(expTypes:List[TypeExpr], args:List[Expr], - s:Scope, ft:FuncTable, tt:TypeTree):List[CompilerError] = + s:Scope, ft:FuncTable, tt:TypeTree):List[TypeError] = (expTypes zip args) flatMap { case (et, e) => checkCalls(e, s, ft, tt) match { case Nil => tt.complies(et, inferType(e, s, ft, tt)) case l => l } } def inferType(expr:Expr, ft:FuncTable, tt:TypeTree):TypeExpr = inferType(expr, Map(), ft, tt) def inferType(expr:Expr, scope:Scope, ft:FuncTable, tt:TypeTree):TypeExpr = { expr match { case IntLit(_) => TypeExpr("Int",Nil) case CharLit(_) => TypeExpr("Char",Nil) case FloatLit(_) => TypeExpr("Float",Nil) case IfExpr(_, i, t) => tt.deepestCommonAncestor(inferType(i, ft, tt), inferType(t, ft, tt)) case c:Call => if(isParam(c, scope)) scope(c.name) else ft(c.name).args.last } } private def isParam(call:Call, scope:Scope):Boolean = call.args.isEmpty && (scope isDefinedAt call.name) } diff --git a/src/vmlang/compiler/typecheck/TypeErrors.scala b/src/vmlang/compiler/typecheck/TypeErrors.scala index 443d113..170c07f 100644 --- a/src/vmlang/compiler/typecheck/TypeErrors.scala +++ b/src/vmlang/compiler/typecheck/TypeErrors.scala @@ -1,23 +1,39 @@ package vmlang.compiler.typecheck -import vmlang.compiler.ast._ +import vmlang.compiler.ast.TypeExpr case class TypeErrors(errors:List[CompilerError]) extends CompoundCompilerError(errors) abstract class TypeError extends NormalCompilerError case class NonexistentType(name:String) extends TypeError { val repr = "Nonexistent type: \"" + name + "\"" } case class Mismatch(expected:TypeExpr, given:TypeExpr) extends TypeError { val repr = "Type mismatch. Expected: " + expected.repr + "; given: " + given.repr } case class WrongNumTypeArgs(expected:Int, given:Int) extends TypeError { val repr = "Wrong number of type arguments. Expected: " + expected + "; given: " + given } case class WrongNumCallArgs(expected:Int, given:Int) extends TypeError { val repr = "Wrong number of arguments. Expected: " + expected + "; given: " + given } + +case class NonexistentFuncError(funcName:String) extends TypeError { + val repr = "Call to nonexistent function " + funcName +} + +case class DuplicateDefError(name:String) extends TypeError { + val repr = "Two definitions with same name: " + name +} + +case object NoMainError extends TypeError { + val repr = "No main function. (Must be () => Null)" +} + +case class InvalidMainError(te:TypeExpr) extends TypeError { + val repr = "Function main is " + te + "; must be () => Null" +} diff --git a/src/vmlang/compiler/typecheck/TypeTree.scala b/src/vmlang/compiler/typecheck/TypeTree.scala index 251b6ee..8185bee 100644 --- a/src/vmlang/compiler/typecheck/TypeTree.scala +++ b/src/vmlang/compiler/typecheck/TypeTree.scala @@ -1,94 +1,101 @@ package vmlang.compiler.typecheck import vmlang.compiler.ast.TypeExpr // todo: make it work w/ type vars case class TypeTree(t:Type, subTypes:List[TypeTree]) { def complies(exp:TypeExpr, giv:TypeExpr):List[TypeError] = (checkValidTypeExpr(exp) ::: checkValidTypeExpr(giv)) match { case Nil => descends(exp.name, giv.name) match { case true => (exp.args zip giv.args) flatMap { p => complies(p._1, p._2) } case false => List(Mismatch(exp, giv)) } case es => es } private def descends(e:String, g:String):Boolean = this findSubType e match { case Some(eTree) => eTree findSubType g match { case Some(gTree) => true case None => false } case None => throw new IllegalArgumentException("nonexistent type: " + e) } def deepestCommonAncestor(l:List[TypeExpr]):TypeExpr = l match { case Nil => throw new IllegalArgumentException("can't give DCA of empty list") case t :: Nil => t case t :: ts => deepestCommonAncestor(t,deepestCommonAncestor(ts)) } def deepestCommonAncestor(a:TypeExpr, b:TypeExpr):TypeExpr = { // TODO: this isn't really right for situations with different numbers of type args val (name, numArgs) = DCA(a.name, b.name) TypeExpr(name, ((a.args zip b.args) map { p => deepestCommonAncestor(p._1, p._2) }) take numArgs) } private def DCA(a:String, b:String):(String,Int) = ((path(a) zip path(b)) takeWhile { p => p._1 == p._2 }).last._1 private def path(tn:String):List[(String,Int)] = path(Nil,tn) match { case Some(l) => l case None => throw new NonexistentType(tn) } private def path(path:List[(String,Int)], tn:String):Option[List[(String,Int)]] = if(tn == t.name) Some(path ::: List((t.name,t.numParams))) else if(isLeaf) None else subTypes.map(_.path(path,tn)).find(_.isInstanceOf[Some[List[String]]]) match { case Some(Some(p)) => Some(path ::: List((t.name,t.numParams)) ::: p) case Some(None) => None // would never happen... case None => None } private def checkValidTypeExpr(te:TypeExpr):List[TypeError] = checkExistentAndNumArgs(te.name, te.args.length) ::: (te.args flatMap { a => checkValidTypeExpr(a) }) private def checkExistentAndNumArgs(tn:String, numArgs:Int):List[TypeError] = findSubType(tn) match { case None => List(NonexistentType(tn)) case Some(tree) => { val expNum = tree.t.numParams if(numArgs == expNum) Nil else List(WrongNumTypeArgs(expNum, numArgs)) } } private def findSubType(tn:String):Option[TypeTree] = { if(tn == t.name) Some(this) else if(isLeaf) None else subTypes.map(_ findSubType tn).find(_.isInstanceOf[Some[TypeTree]]) match { case Some(tree) => tree case None => None } } + def find(tn:String):Type = { + findSubType(tn) match { + case Some(tt) => tt.t + case None => throw NonexistentType(tn) + } + } + def isLeaf = subTypes.isEmpty def prettyPrint:String = prettyPrint(0).mkString def prettyPrint(indent:Int):List[Char] = (" " * indent).toList ::: t.name.toList ::: List('\n') ::: ( subTypes flatMap { _ prettyPrint (indent + 2) }) } diff --git a/src/vmlang/vm/VM.java b/src/vmlang/vm/VM.java index 7404f03..cada7ab 100644 --- a/src/vmlang/vm/VM.java +++ b/src/vmlang/vm/VM.java @@ -1,272 +1,322 @@ package vmlang.vm; import java.io.IOException; import java.io.PrintStream; import java.io.InputStream; import vmlang.common.Opcodes; public class VM { // registers private int A, B, SP, BP; private int counter; // memory private byte[] program; private byte[] memory; // io private InputStream in; private PrintStream out; private int stackStart; private static final Opcodes[] opcodes = Opcodes.values(); // inefficient? public VM(byte[] prog, int heapSize, int stackSize) throws InitError { this(prog, heapSize, stackSize, System.in, System.out); } public VM(byte[] prog, int heapSize, int stackSize, InputStream is, PrintStream os) throws InitError { if(heapSize % 8 != 0) throw new InitError("Heap size must be divisible by 8 (for malloc)"); program = prog; memory = new byte[heapSize + stackSize]; stackStart = heapSize; in = is; out = os; } public void run() throws VMError { int nextAddr; while(true) { Opcodes opcode; try { opcode = opcodes[progReadByte()]; } catch(ArrayIndexOutOfBoundsException e) { throw getMalfProgEx(); } switch(opcode) { // FLOW CONTROL // basic case STOP: return; case GOTO: counter = progReadInt(); break; case GOTO_A: counter = A; break; // conditional jumps: based on post-SUB state of register A case IF_EQ: nextAddr = progReadInt(); if(A != 0) counter = nextAddr; break; case IF_LT: nextAddr = progReadInt(); if(A >= 0) counter = nextAddr; break; // LOAD & STORE (Von-Neumann bottleneck) // int constants case I_CONST_A: A = progReadInt(); break; case I_CONST_B: B = progReadInt(); break; // byte constants case B_CONST_A: A = progReadByte(); break; case B_CONST_B: B = progReadByte(); break; // load int case I_LOAD_A_SP: A = memReadInt(SP); break; + case I_LOAD_A_A: + A = memReadInt(A); + break; + case I_LOAD_BP_SP: + BP = memReadInt(SP); + break; case I_LOAD_B_SP: B = memReadInt(SP); break; case I_LOAD_SP_SP: SP = memReadInt(SP); break; // load byte case B_LOAD_A_SP: A = memReadByte(SP); break; + case B_LOAD_A_A: + A = memReadByte(A); + break; case B_LOAD_B_SP: B = memReadByte(SP); break; // store int case I_STORE_A_SP: memWriteInt(SP,A); break; + case I_STORE_BP_SP: + memWriteInt(SP,BP); + break; // store byte case B_STORE_A_SP: memWriteByte(SP,(byte)A); break; // moves case MOVE_COUNTER_A: A = counter; break; case MOVE_SP_A: A = SP; break; case MOVE_BP_A: A = BP; break; case MOVE_A_SP: SP = A; break; case MOVE_A_BP: BP = A; break; // REGISTER OPERATIONS - // arithmetic + // int arithmetic case I_ADD: A = A + B; break; case I_SUB: A = A - B; break; case I_MUL: A = A * B; break; case I_DIV: A = A / B; break; case I_MOD: - A = A * B; + A = A % B; break; case INC_A: A++; break; + // float arithmetic + case F_ADD: + A = Float.floatToIntBits(Float.intBitsToFloat(A) + Float.intBitsToFloat(B)); + break; + case F_SUB: + A = Float.floatToIntBits(Float.intBitsToFloat(A) - Float.intBitsToFloat(B)); + break; + case F_MUL: + A = A = Float.floatToIntBits(Float.intBitsToFloat(A) * Float.intBitsToFloat(B)); + break; + case F_DIV: + A = Float.floatToIntBits(Float.intBitsToFloat(A) / Float.intBitsToFloat(B)); + break; + case F_MOD: + A = Float.floatToIntBits(Float.intBitsToFloat(A) % Float.intBitsToFloat(B)); + break; // inc/dec case INC_B: B++; break; case INC_SP: SP++; break; + case INC_SP_INT: + SP += 4; + break; case DEC_A: A--; break; case DEC_B: B--; break; case DEC_SP: SP--; break; + case DEC_SP_INT: + SP -= 4; + break; // logic (0: false; non-0: true) case NEG_A: if(A == 0) A = 1; else A = 0; break; - case NEG_LT_A: - if(A < 0) - A = 1; - else - A = 0; + case EQ_A: + if(A == 0) + A = 1; + else + A = 0; + break; + case LT_A: + if(A < 0) + A = 1; + else + A = 0; + break; + case GT_A: + if(A > 0) + A = 1; + else + A = 0; + break; case AND: if(A != 0 && B != 0) A = 1; else A = 0; break; case OR: if(A != 0 || B != 0) A = 1; else A = 0; break; case STACK_START: A = stackStart; break; // io case PRINT_CHAR_A: out.print((char)A); break; + case PRINT_INT_A: + out.println(A); + break; case READ_CHAR_A: try { A = in.read(); } catch(IOException e) { out.println(e.getMessage()); } break; } } } // PROGRAM READERS private byte progReadByte() throws MalformedProgramError { byte result; try { result = program[counter]; } catch(ArrayIndexOutOfBoundsException e) { throw getMalfProgEx(); } counter++; return result; } private int progReadInt() throws MalformedProgramError { return ((progReadByte() & 0xff) << 24) | ((progReadByte() & 0xff) << 16) | ((progReadByte() & 0xff) << 8) | (progReadByte() & 0xff); } // MEMORY READERS & WRITERS private byte memReadByte(int addr) throws StackOverflowError { try { return memory[addr]; } catch(ArrayIndexOutOfBoundsException e) { throw new StackOverflowError(); } } private int memReadInt(int addr) throws StackOverflowError { return ((memReadByte(addr) & 0xff) << 24) | ((memReadByte(addr+1) & 0xff) << 16) | ((memReadByte(addr+2) & 0xff) << 8) | (memReadByte(addr+3) & 0xff); } private void memWriteByte(int addr, byte val) throws StackOverflowError { try { memory[addr] = val; } catch(ArrayIndexOutOfBoundsException e) { throw new StackOverflowError(); } } private void memWriteInt(int addr, int val) throws StackOverflowError { memWriteByte(addr ,(byte)(0xff & (val >> 24))); memWriteByte(addr+1,(byte)(0xff & (val >> 16))); memWriteByte(addr+2,(byte)(0xff & (val >> 8))); memWriteByte(addr+3,(byte)(0xff & val)); } private MalformedProgramError getMalfProgEx() { return new MalformedProgramError(); } } \ No newline at end of file
vilterp/VMLang
0ee6c5e421f2727162d3557747387d0c145143d4
typechecker
diff --git a/src/vmlang/compiler/Util.scala b/src/vmlang/compiler/Errors.scala similarity index 100% rename from src/vmlang/compiler/Util.scala rename to src/vmlang/compiler/Errors.scala diff --git a/src/vmlang/compiler/Simplifier.scala b/src/vmlang/compiler/Simplifier.scala index d8aa757..7132ff1 100644 --- a/src/vmlang/compiler/Simplifier.scala +++ b/src/vmlang/compiler/Simplifier.scala @@ -1,30 +1,41 @@ -// package vmlang.compiler -// -// import vmlang.compiler.ast._ -// import collection.immutable.HashSet -// -// object Simplifier { -// -// def apply(prog:Prog) = Prog(prog.defs map { case Def(n,a,r,body) => Def(n,a,r,simplify(body)) }) -// -// def simplify(e:Expr):Expr = e match { -// case a:Atom => a -// case IfExpr(c,i,e) => (simplify(c), simplify(i), simplify(e)) match { -// case (Call("true",Nil), i, e) => i -// case (Call("false",Nil), i, e) => i -// case (c, i, e) => IfExpr(c, i, e) -// } -// case Call(n,args) => (n, args map simplify) match { -// case ("+" , List(Integer(a),Integer(b))) => Integer(a + b) -// case ("-" , List(Integer(a),Integer(b))) => Integer(a - b) -// case ("*" , List(Integer(a),Integer(b))) => Integer(a * b) -// case ("/" , List(Integer(a),Integer(b))) => Integer(a / b) -// case (">" , List(Integer(a),Integer(b))) => Integer(a b) -// case (">=", List(Integer(a),Integer(b))) => Integer(a + b) -// case ("<" , List(Integer(a),Integer(b))) => Integer(a + b) -// case ("<=", List(Integer(a),Integer(b))) => Integer(a + b) -// case ("==", List(Integer(a),Integer(b))) => Integer(a + b) -// } -// } -// -// } +package vmlang.compiler + +import vmlang.compiler.ast._ +import collection.immutable.HashSet + +object Simplifier { + + def apply(prog:Prog) = Prog(prog.defs map { case Def(n,a,r,body) => Def(n,a,r,simplify(body)) }) + + def simplify(e:Expr):Expr = e match { + case a:Atom => a + case IfExpr(c,i,e) => (simplify(c), simplify(i), simplify(e)) match { + case (Call("true",Nil), i, e) => i + case (Call("false",Nil), i, e) => e + case (c, i, e) => IfExpr(c, i, e) + } + case Call(n,args) => (n, args map simplify) match { + + case ("+" , List(IntLit(a),IntLit(b))) => IntLit(a + b) + case ("-" , List(IntLit(a),IntLit(b))) => IntLit(a - b) + case ("*" , List(IntLit(a),IntLit(b))) => IntLit(a * b) + case ("/" , List(IntLit(a),IntLit(b))) => IntLit(a / b) + + case (">" , List(IntLit(a),IntLit(b))) => Call(if(a > b) "true" else "false", Nil) + case (">=", List(IntLit(a),IntLit(b))) => Call(if(a >= b) "true" else "false", Nil) + case ("<" , List(IntLit(a),IntLit(b))) => Call(if(a < b) "true" else "false", Nil) + case ("<=", List(IntLit(a),IntLit(b))) => Call(if(a <= b) "true" else "false", Nil) + case ("==", List(IntLit(a),IntLit(b))) => Call(if(a == b) "true" else "false", Nil) + + case ("not", List(Call("true",Nil))) => Call("false", Nil) + case ("not", List(Call("false",Nil))) => Call("true", Nil) + + case ("and", List(Call(a,Nil),Call(b,Nil))) => + Call(if(a == "true" && b == "true") "true" else "false", Nil) + case ("or", List(Call(a,Nil),Call(b,Nil))) => + Call(if(a == "true" || b == "true") "true" else "false", Nil) + + } + } + +} diff --git a/src/vmlang/compiler/ast/AST.scala b/src/vmlang/compiler/ast/AST.scala index 57e9b7a..e814bf6 100644 --- a/src/vmlang/compiler/ast/AST.scala +++ b/src/vmlang/compiler/ast/AST.scala @@ -1,29 +1,29 @@ package vmlang.compiler.ast abstract class ASTNode case class Prog(defs:List[Def]) extends ASTNode -case class Def(name:String, params:List[ParamSpec], returnType:TypeExpr, body:Expr) extends ASTNode case class ParamSpec(name:String, argType:TypeExpr) extends ASTNode - case class TypeExpr(name:String, args:List[TypeExpr]) extends ASTNode { override val toString = if(isFunctionType) - args.take(args.length-1).mkString("(",",",")") + " => " + args.last + args.init.mkString("(",",",")") + " => " + args.last else name + (if(args.isEmpty) "" else args.mkString("[",",","]")) val repr = if(isFunctionType) toString else name val isFunctionType = (name startsWith "Function") && !(name endsWith("Function")) } -abstract class Expr extends ASTNode +abstract class IPromptStmt extends ASTNode + +case class Def(name:String, params:List[ParamSpec], returnType:TypeExpr, body:Expr) extends IPromptStmt + +abstract class Expr extends IPromptStmt case class IfExpr(condition:Expr, ifExpr:Expr, thenExpr:Expr) extends Expr case class Call(name:String, args:List[Expr]) extends Expr abstract class Atom extends Expr case class IntLit(value:Int) extends Atom case class FloatLit(value:Float) extends Atom case class CharLit(value:Char) extends Atom -case object EmptyList extends Atom - diff --git a/src/vmlang/compiler/ast/Parser.scala b/src/vmlang/compiler/ast/Parser.scala index 33cf54c..01dd3c4 100644 --- a/src/vmlang/compiler/ast/Parser.scala +++ b/src/vmlang/compiler/ast/Parser.scala @@ -1,111 +1,120 @@ package vmlang.compiler.ast import scala.runtime.RichString import scala.util.parsing.combinator.syntactical._ case class ParserError(msg:String) extends NormalCompilerError { val repr = "Parser Error: " + msg } +case object TooManyParams extends ParserError("can't make a function with more than 9 params") + object Parser extends StandardTokenParsers { lexical.delimiters ++= List("+","-","*","/","(",")","[","]","=","=>",":",",",">","<", ">=","<=","==","!","!=") lexical.reserved ++= List("if","then","else","and","or") // RULES def program = (definition *) ^^ { l => Prog(l) } + def iPromptStmt = ( definition | expr ) + def definition = ident ~ (paramsSpec?) ~ typeSpec ~ ("=" ~> expr) ^^ { - case i ~ Some(ps) ~ rt ~ e => Def(i,ps,rt,e) - case i ~ None ~ rt ~ e => Def(i,Nil,rt,e) } + case i ~ Some(ps) ~ rt ~ e => Def(i, checkPs(ps), rt, e) + case i ~ None ~ rt ~ e => Def(i, Nil, rt, e) } + + def checkPs(ps:List[ParamSpec]) = if(ps.length <= 9) ps else throw TooManyParams def paramsSpec = "(" ~> repsep(paramSpec, ",") <~ ")" def paramSpec = ident ~ typeSpec ^^ { case i ~ t => ParamSpec(i,t) } def typeSpec = ":" ~> typeExpr def typeExpr:Parser[TypeExpr] = ( normalTypeExpr | funcTypeExpr ) - def normalTypeExpr:Parser[TypeExpr] = ident ~ (typeParams?) ^^ { case i ~ Some(tp) => TypeExpr(i,tp) - case i ~ None => TypeExpr(i,Nil) } + def normalTypeExpr:Parser[TypeExpr] = ident ~ (typeParams?) ^^ { case i ~ Some(tp) => TypeExpr(i, tp) + case i ~ None => TypeExpr(i, Nil) } + + def funcTypeExpr:Parser[TypeExpr] = ("(" ~> repsep(typeExpr,",") <~ ")") ~ ("=>" ~> typeExpr) ^^ + { case pts ~ rt => mkFuncTypeExpr(pts, rt) } - def funcTypeExpr:Parser[TypeExpr] = ("(" ~> repsep(typeExpr,",") <~ ")") ~ ("=>" ~> typeExpr) ^^ { - case pts ~ rt => if(pts.length <= 8) - TypeExpr("Function" + pts.length, pts ::: List(rt)) - else - throw ParserError("can't make a function with more than 8 parameters") } + def mkFuncTypeExpr(paramTypes:List[TypeExpr], returnType:TypeExpr):TypeExpr = + if(paramTypes.length <= 9) + TypeExpr("Function" + paramTypes.length, paramTypes ::: List(returnType)) + else + throw TooManyParams def typeParams = "[" ~> repsep(typeExpr,",") <~ "]" def expr:Parser[Expr] = ( ifStatement | orExpr ) def ifStatement = (("if" ~> orExpr) ~ ("then" ~> orExpr) ~ ("else" ~> orExpr)) ^^ { case c ~ i ~ e => IfExpr(c,i,e) } def orExpr = andExpr * ( "or" ^^^ { (a:Expr, b:Expr) => Call("or",List(a,b)) } ) def andExpr = comparison * ( "and" ^^^ { (a:Expr, b:Expr) => Call("and",List(a,b)) } ) def comparison = sum * ( ">" ^^^ { (a:Expr, b:Expr) => Call(">",List(a,b)) } | "<" ^^^ { (a:Expr, b:Expr) => Call("<",List(a,b)) } | "==" ^^^ { (a:Expr, b:Expr) => Call("==",List(a,b)) } | "<=" ^^^ { (a:Expr, b:Expr) => Call("<=",List(a,b)) } | ">=" ^^^ { (a:Expr, b:Expr) => Call(">=",List(a,b)) } | "!=" ^^^ { (a:Expr, b:Expr) => Call("!=",List(a,b)) } ) // I'm sure there's a super-elegant way to do this, // but my Scala chops aren't up to it yet def sum = product * ( "+" ^^^ { (a:Expr, b:Expr) => Call("+",List(a,b)) } | "-" ^^^ { (a:Expr, b:Expr) => Call("-",List(a,b)) } ) def product = atom * ( "*" ^^^ { (a:Expr, b:Expr) => Call("*",List(a,b)) } | "/" ^^^ { (a:Expr, b:Expr) => Call("/",List(a,b)) } ) def atom = ( int | list | string | call | parenthesizedExpr | unaryMinus | unaryNot ) // todo: char lit (not in standardtokenparsers...) def list = "[" ~> repsep(expr,",") <~ "]" ^^ concatIze def string = stringLit ^^ { (s:String) => concatIze(new RichString(s) map { CharLit(_) }) } - def concatIze(items:Seq[Expr]):Expr = items.foldRight(EmptyList.asInstanceOf[Expr]){ - (i,a) => Call(":",List(i,a)) } + def concatIze(items:Seq[Expr]):Expr = items.foldRight(Call("EmptyList",Nil).asInstanceOf[Expr]){ + (i,a) => Call(":",List(i,a)) } def parenthesizedExpr = "(" ~> expr <~ ")" - def unaryNot:Parser[Expr] = "!" ~> atom ^^ { a => Call("!",List(a)) } + def unaryNot:Parser[Expr] = "not" ~> atom ^^ { a => Call("not",List(a)) } def unaryMinus:Parser[Expr] = "-" ~> atom ^^ { a => Call("*",List(a,IntLit(-1))) } def int = numericLit ^^ { s => IntLit(s.toInt) } def call = ident ~ (args ?) ^^ { case i ~ Some(a) => Call(i,a) case i ~ None => Call(i,Nil) } def args = "(" ~> repsep(expr,",") <~ ")" // END OF RULES def parse(s:String) = phrase(program)(new lexical.Scanner(s)) def parseTypeExpr(t:String) = phrase(typeExpr)(new lexical.Scanner(t)) match { case Success(t, _) => t case e: NoSuccess => throw new IllegalArgumentException(e.toString) } def apply(s:String) = { parse(s) match { case Success(tree, _) => tree case e: NoSuccess => throw ParserError(e.toString) } } } diff --git a/src/vmlang/compiler/typecheck/TypeCheck.scala b/src/vmlang/compiler/typecheck/TypeCheck.scala index e5f30a9..9e6a143 100644 --- a/src/vmlang/compiler/typecheck/TypeCheck.scala +++ b/src/vmlang/compiler/typecheck/TypeCheck.scala @@ -1,92 +1,125 @@ -// package vmlang.compiler.typecheck -// -// import vmlang.compiler.ast._ -// import collection.immutable.HashMap -// -// // TODO: check expr tree for calls to nonexistent functions first -// // otherwise, maps and stuff are hard -// -// object TypeCheck { -// -// val typeTree = TypeTree(AbsType("Value"),List( -// TypeTree(AbsType("Eq"),List( -// TypeTree(PrimType("Bool"),Nil), -// TypeTree(PrimType("Null"),Nil), -// TypeTree(AbsType("Ord"),List( -// TypeTree(AbsType("Num"),List( -// TypeTree(PrimType("Int"),Nil), -// TypeTree(PrimType("Float"),Nil))), -// TypeTree(PrimType("Char"),Nil))))))) -// -// type FuncTable = HashMap[String,FuncType] -// -// implicit def string2typeExpr(s:String) = Parser.parseTypeExpr(s).name -// -// val rootFuncTypes = HashMap( -// "+" -> FuncType(List("Num","Num"),"Num"), -// "-" -> FuncType(List("Num","Num"),"Num"), -// "*" -> FuncType(List("Num","Num"),"Num"), -// "/" -> FuncType(List("Num","Num"),"Num"), -// "==" -> FuncType(List("Eq","Eq"),"Bool"), -// "!=" -> FuncType(List("Eq","Eq"),"Bool"), -// ">" -> FuncType(List("Ord","Ord"),"Bool"), -// ">=" -> FuncType(List("Ord","Ord"),"Bool"), -// "<" -> FuncType(List("Ord","Ord"),"Bool"), -// "<=" -> FuncType(List("Ord","Ord"),"Bool"), -// "true" -> FuncType(Nil,"Bool"), -// "false" -> FuncType(Nil,"Bool"), -// "null" -> FuncType(Nil,"Null"), -// "and" -> FuncType(List("Bool","Bool"),"Bool"), -// "or" -> FuncType(List("Bool","Bool"),"Bool"), -// "printChar" -> FuncType(List("Char"),"Null"), -// "getChar" -> FuncType(Nil,"Char"), -// "stackStart" -> FuncType(Nil,"Int") -// ) -// -// def apply(prog:Prog):Prog = -// apply(prog, rootFuncTypes, typeTree) -// -// def apply(prog:Prog, ft:FuncTable, tt:TypeTree):Prog = -// checkCompliance(prog, addTypeSigs(prog, ft), tt) -// -// private def addTypeSigs(p:Prog, ft:FuncTable):FuncTable = -// p.defs.foldLeft(ft){ (ft,d) => ft + (d.name -> FuncType(d.args, d.returnType)) } -// -// private def checkCompliance(p:Prog, ft:FuncTable, tt:TypeTree):Prog = -// (p.defs flatMap { checkDef(_, ft, tt) }) match { -// case Nil => p -// case l:List[CompilerError] => throw new TypeErrors(l) -// } -// -// private def checkDef(d:Def, ft:FuncTable, tt:TypeTree):List[CompilerError] = -// tt.complies(d.returnType, inferType(d.body)) // Type vs. TypeExpr ... -// -// def checkCall(call:Call, ft:FuncTable, tt:TypeTree):List[CompilerError] = { -// val giv = call.args -// ft.get(call.name) match { -// case Some(ft) => { -// val exp = ft.paramTypes -// if(exp.length == giv.length) Nil else List(WrongNumCallArgs(exp.length, giv.length)) ::: -// ((exp zip (giv map { inferType(_) })) map { p => tt.complies(p._1,p._2) }) -// } -// case None => List(NonexistentFuncError(call.name)) -// } -// } -// -// def inferType(expr:Expr, funcTypes:FuncTable, typeTree:TypeTree):TypeExpr = -// inferType(expr, Map(), funcTypes, typeTree) -// -// // TODO: check function scope when inferring call -// def inferType(expr:Expr, scope:Map[String,Type], ft:FuncTable, tt:TypeTree):TypeExpr = -// expr match { -// case IntLit(_) => tt find "Int" -// case CharLit(_) => tt find "Char" -// case IfExpr(_, i, t) => typeTree.deepestCommonAncestor(inferType(i, funcTypes, typeTree), -// inferType(t, funcTypes, typeTree)) -// case c:Call => if(isParam(c, scope)) scope(c.name) else ft(c.name).returnType -// } -// -// private def isParam(call:Call, scope:Map[String,Type]):Boolean = -// call.params.isEmpty && scope isDefinedAt call.name -// -// } +package vmlang.compiler.typecheck + +import vmlang.compiler.ast._ +import collection.immutable.{ Map, HashMap } + +object TypeCheck { + + val typeTree = TypeTree(AbsType("Value",0),List( + TypeTree(AbsType("Function",0),List( + TypeTree(RefType("Function0",1),Nil), + TypeTree(RefType("Function1",2),Nil), + TypeTree(RefType("Function2",3),Nil), + TypeTree(RefType("Function3",4),Nil), + TypeTree(RefType("Function4",5),Nil), + TypeTree(RefType("Function5",6),Nil), + TypeTree(RefType("Function6",7),Nil), + TypeTree(RefType("Function7",8),Nil), + TypeTree(RefType("Function8",9),Nil), + TypeTree(RefType("Function9",10),Nil))), + TypeTree(AbsType("Eq",0),List( + TypeTree(PrimType("Bool"),Nil), + TypeTree(PrimType("Null"),Nil), + TypeTree(AbsType("Ord",0),List( + TypeTree(PrimType("Char"),Nil), + TypeTree(PrimType("Int"),Nil))))))) + + type FuncTable = Map[String,TypeExpr] + type Scope = Map[String,TypeExpr] + + val rootFuncTypes = new HashMap[String, TypeExpr] ++ (List( + ("+" , "(Int, Int) => Int" ), + ("-" , "(Int, Int) => Int" ), + ("*" , "(Int, Int) => Int" ), + ("/" , "(Int, Int) => Int" ), + ("==" , "(Eq, Eq) => Bool" ), + ("!=" , "(Eq, Eq) => Bool" ), + (">" , "(Ord, Ord) => Bool" ), + (">=" , "(Ord, Ord) => Bool" ), + ("<" , "(Ord, Ord) => Bool" ), + ("<=" , "(Ord, Ord) => Bool" ), + ("true" , "() => Bool" ), + ("false" , "() => Bool" ), + ("null" , "() => Null" ), + ("and" , "(Bool, Bool) => Bool" ), + ("or" , "(Bool, Bool) => Bool" ), + ("not" , "(Bool) => Bool" ), + ("printChar" , "(Char) => Null" ), + ("getChar" , "() => Char" ), + ("stackStart" , "() => Int" ) + ) map { tp => (tp._1, Parser.parseTypeExpr(tp._2)) }) + + def apply(prog:Prog):Prog = + apply(prog, rootFuncTypes, typeTree) + + def apply(prog:Prog, ft:FuncTable, tt:TypeTree):Prog = + checkCompliance(prog, addTypeSigs(ft, prog), tt) + + private def addTypeSigs(ft:FuncTable, p:Prog):FuncTable = + p.defs.foldLeft(ft){ (ft, d) => ft + (d.name -> TypeExpr("Function" + d.params.length, + (d.params map { _.argType }) ::: List(d.returnType))) } + + private def checkCompliance(p:Prog, ft:FuncTable, tt:TypeTree):Prog = + (p.defs flatMap { checkDef(_, ft, tt) }) match { + case Nil => p + case l => throw new TypeErrors(l.removeDuplicates) + } + + private def checkDef(d:Def, ft:FuncTable, tt:TypeTree):List[CompilerError] = { + val s = Map() ++ (d.params map { ps => (ps.name, ps.argType) }) + checkCalls(d.body, s, ft, tt) match { + case Nil => tt.complies(d.returnType, inferType(d.body, s, ft, tt)) + case l => l + } + } + + private def checkCalls(e:Expr, s:Scope, ft:FuncTable, tt:TypeTree):List[CompilerError] = + e match { + case a:Atom => Nil + case IfExpr(i, c, e) => checkCalls(List(i, c, e), s, ft, tt) + case c:Call => checkCall(c, s, ft, tt) ::: checkCalls(c.args, s, ft, tt) + } + + private def checkCalls(es:List[Expr], s:Scope, ft:FuncTable, tt:TypeTree):List[CompilerError] = + es flatMap { e => checkCalls(e, s, ft, tt) } + + def checkCall(call:Call, scope:Scope, ft:FuncTable, tt:TypeTree):List[CompilerError] = { + val giv = call.args + (scope get call.name) match { + case Some(_) => Nil + case None => (ft get call.name) match { + case Some(funcType) => { + val exp = funcType.args.init + (if(exp.length == giv.length) Nil else List(WrongNumCallArgs(exp.length, giv.length))) ::: + checkArgCompliance(exp, giv, scope, ft, tt) + } + case None => List(NonexistentFuncError(call.name)) + } + } + } + + private def checkArgCompliance(expTypes:List[TypeExpr], args:List[Expr], + s:Scope, ft:FuncTable, tt:TypeTree):List[CompilerError] = + (expTypes zip args) flatMap { case (et, e) => checkCalls(e, s, ft, tt) match { + case Nil => tt.complies(et, inferType(e, s, ft, tt)) + case l => l + } } + + def inferType(expr:Expr, ft:FuncTable, tt:TypeTree):TypeExpr = + inferType(expr, Map(), ft, tt) + + def inferType(expr:Expr, scope:Scope, ft:FuncTable, tt:TypeTree):TypeExpr = { + expr match { + case IntLit(_) => TypeExpr("Int",Nil) + case CharLit(_) => TypeExpr("Char",Nil) + case FloatLit(_) => TypeExpr("Float",Nil) + case IfExpr(_, i, t) => tt.deepestCommonAncestor(inferType(i, ft, tt), + inferType(t, ft, tt)) + case c:Call => if(isParam(c, scope)) scope(c.name) else ft(c.name).args.last + } + } + + private def isParam(call:Call, scope:Scope):Boolean = + call.args.isEmpty && (scope isDefinedAt call.name) + +} diff --git a/src/vmlang/compiler/typecheck/Compliance.scala b/src/vmlang/compiler/typecheck/TypeErrors.scala similarity index 100% rename from src/vmlang/compiler/typecheck/Compliance.scala rename to src/vmlang/compiler/typecheck/TypeErrors.scala diff --git a/src/vmlang/compiler/typecheck/TypeTree.scala b/src/vmlang/compiler/typecheck/TypeTree.scala index 90a2b1e..251b6ee 100644 --- a/src/vmlang/compiler/typecheck/TypeTree.scala +++ b/src/vmlang/compiler/typecheck/TypeTree.scala @@ -1,94 +1,94 @@ package vmlang.compiler.typecheck import vmlang.compiler.ast.TypeExpr -// could be more efficient: complies("Map[Num,Value]","TreeMap[Int,Float]") results in 44 calls to findSubType +// todo: make it work w/ type vars case class TypeTree(t:Type, subTypes:List[TypeTree]) { def complies(exp:TypeExpr, giv:TypeExpr):List[TypeError] = (checkValidTypeExpr(exp) ::: checkValidTypeExpr(giv)) match { case Nil => descends(exp.name, giv.name) match { case true => (exp.args zip giv.args) flatMap { p => complies(p._1, p._2) } case false => List(Mismatch(exp, giv)) } - case es:List[TypeError] => es + case es => es } private def descends(e:String, g:String):Boolean = this findSubType e match { case Some(eTree) => eTree findSubType g match { case Some(gTree) => true case None => false } case None => throw new IllegalArgumentException("nonexistent type: " + e) } def deepestCommonAncestor(l:List[TypeExpr]):TypeExpr = l match { case Nil => throw new IllegalArgumentException("can't give DCA of empty list") case t :: Nil => t case t :: ts => deepestCommonAncestor(t,deepestCommonAncestor(ts)) } def deepestCommonAncestor(a:TypeExpr, b:TypeExpr):TypeExpr = { // TODO: this isn't really right for situations with different numbers of type args val (name, numArgs) = DCA(a.name, b.name) TypeExpr(name, ((a.args zip b.args) map { p => deepestCommonAncestor(p._1, p._2) }) take numArgs) } private def DCA(a:String, b:String):(String,Int) = ((path(a) zip path(b)) takeWhile { p => p._1 == p._2 }).last._1 private def path(tn:String):List[(String,Int)] = path(Nil,tn) match { case Some(l) => l case None => throw new NonexistentType(tn) } private def path(path:List[(String,Int)], tn:String):Option[List[(String,Int)]] = if(tn == t.name) Some(path ::: List((t.name,t.numParams))) else if(isLeaf) None else subTypes.map(_.path(path,tn)).find(_.isInstanceOf[Some[List[String]]]) match { case Some(Some(p)) => Some(path ::: List((t.name,t.numParams)) ::: p) case Some(None) => None // would never happen... case None => None } private def checkValidTypeExpr(te:TypeExpr):List[TypeError] = checkExistentAndNumArgs(te.name, te.args.length) ::: (te.args flatMap { a => checkValidTypeExpr(a) }) private def checkExistentAndNumArgs(tn:String, numArgs:Int):List[TypeError] = findSubType(tn) match { case None => List(NonexistentType(tn)) case Some(tree) => { val expNum = tree.t.numParams if(numArgs == expNum) Nil else List(WrongNumTypeArgs(expNum, numArgs)) } } private def findSubType(tn:String):Option[TypeTree] = { if(tn == t.name) Some(this) else if(isLeaf) None else subTypes.map(_ findSubType tn).find(_.isInstanceOf[Some[TypeTree]]) match { case Some(tree) => tree case None => None } } def isLeaf = subTypes.isEmpty def prettyPrint:String = prettyPrint(0).mkString def prettyPrint(indent:Int):List[Char] = (" " * indent).toList ::: t.name.toList ::: List('\n') ::: ( subTypes flatMap { _ prettyPrint (indent + 2) }) }
vilterp/VMLang
327f2a9154e2a679a9b24b7fe7d0f5490cfadb87
functions are subtypes of Function, Scala-style (Function0, Function1, etc)
diff --git a/src/vmlang/compiler/Compiler.scala b/src/vmlang/compiler/Compiler.scala index b15f21e..1063296 100644 --- a/src/vmlang/compiler/Compiler.scala +++ b/src/vmlang/compiler/Compiler.scala @@ -1,54 +1,54 @@ // package vmlang.compiler // // import vmlang.compiler.ast._ // import vmlang.compiler.model._ // import vmlang.compiler.icode._ // group these imports into one? // import collection.immutable.Map // // object Compiler { // // def apply(funcTable:Map[String,Function]):List[(String,List[IOpcode])] = { // (funcTable("main") match { // case Some(f) => ("main",compFunc(f)) // case None => throw new NonexistentFuncError("main","[compiler]") // }) ::: ((funcTable - "main") map { p => (p._1,compFunc(p._2)) } ) // } // // def compFunc(f:Function):List[IOpcode] = f match { // case PrimFunc(code) => code // case NormFunc(expr) => compExpr(expr) // } // // def compExpr(e:Expr):List[IOpcode] = e match { // // // TODO: time complexity of ":::" -- are all these calls gonna kill us? // // case Call("+",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(AddI) // case Call("-",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(SubI) // case Call("*",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(MultI) // case Call("/",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(DivI) // // case Call("==",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(CmpEq) // case Call("!=",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(CmpNeq) // case Call(">",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(CmpGt) // case Call(">=",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(CmpGte) // case Call("<",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(CmpLt) // case Call("<=",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(CmpLte) // // case Call("true",_) => List(PushConstI(1)) // case Call("false",_) => List(PushConstI(0)) // // case Call("printChar",List(e)) => compExpr(e) ::: List(PrintChar) // case Call("readChar",_) => List(ReadChar) // -// case Call(name,args) => (args flatMap comExpr) ::: List() +// case Call(name,args) => (args flatMap comExpr) ::: Nil // // case Integer(v) => List(PushConstI(v)) // case Char(c) => List(PushConstC(c)) // // case IfExpr(c,i,e) => { val el = compExpr(e) // compExpr(c) ::: List(GotoIf(el.head)) ::: compExpr(i) ::: el } // // } // // } diff --git a/src/vmlang/compiler/ast/AST.scala b/src/vmlang/compiler/ast/AST.scala index 60e248d..57e9b7a 100644 --- a/src/vmlang/compiler/ast/AST.scala +++ b/src/vmlang/compiler/ast/AST.scala @@ -1,32 +1,29 @@ package vmlang.compiler.ast abstract class ASTNode case class Prog(defs:List[Def]) extends ASTNode case class Def(name:String, params:List[ParamSpec], returnType:TypeExpr, body:Expr) extends ASTNode case class ParamSpec(name:String, argType:TypeExpr) extends ASTNode -abstract class TypeExpr extends ASTNode { - val shortRepr:String -} -case class NormalTypeExpr(name:String, args:List[TypeExpr]) extends TypeExpr { - override val toString = name + (if(args.isEmpty) "" else args.mkString("[",",","]")) - val shortRepr = name -} -case class FuncTypeExpr(paramTypes:List[TypeExpr], returnType:TypeExpr) extends TypeExpr { - override val toString = paramTypes.mkString("(",",",")") + " => " + returnType - val shortRepr = toString +case class TypeExpr(name:String, args:List[TypeExpr]) extends ASTNode { + override val toString = if(isFunctionType) + args.take(args.length-1).mkString("(",",",")") + " => " + args.last + else + name + (if(args.isEmpty) "" else args.mkString("[",",","]")) + val repr = if(isFunctionType) toString else name + val isFunctionType = (name startsWith "Function") && !(name endsWith("Function")) } abstract class Expr extends ASTNode case class IfExpr(condition:Expr, ifExpr:Expr, thenExpr:Expr) extends Expr case class Call(name:String, args:List[Expr]) extends Expr abstract class Atom extends Expr case class IntLit(value:Int) extends Atom case class FloatLit(value:Float) extends Atom case class CharLit(value:Char) extends Atom case object EmptyList extends Atom diff --git a/src/vmlang/compiler/ast/Parser.scala b/src/vmlang/compiler/ast/Parser.scala index e685a7b..33cf54c 100644 --- a/src/vmlang/compiler/ast/Parser.scala +++ b/src/vmlang/compiler/ast/Parser.scala @@ -1,108 +1,111 @@ package vmlang.compiler.ast import scala.runtime.RichString import scala.util.parsing.combinator.syntactical._ -class ParserError(msg:String) extends NormalCompilerError { +case class ParserError(msg:String) extends NormalCompilerError { val repr = "Parser Error: " + msg } object Parser extends StandardTokenParsers { lexical.delimiters ++= List("+","-","*","/","(",")","[","]","=","=>",":",",",">","<", ">=","<=","==","!","!=") lexical.reserved ++= List("if","then","else","and","or") // RULES def program = (definition *) ^^ { l => Prog(l) } def definition = ident ~ (paramsSpec?) ~ typeSpec ~ ("=" ~> expr) ^^ { case i ~ Some(ps) ~ rt ~ e => Def(i,ps,rt,e) case i ~ None ~ rt ~ e => Def(i,Nil,rt,e) } def paramsSpec = "(" ~> repsep(paramSpec, ",") <~ ")" def paramSpec = ident ~ typeSpec ^^ { case i ~ t => ParamSpec(i,t) } def typeSpec = ":" ~> typeExpr def typeExpr:Parser[TypeExpr] = ( normalTypeExpr | funcTypeExpr ) - def normalTypeExpr:Parser[NormalTypeExpr] = ident ~ (typeParams?) ^^ { case i ~ Some(tp) => NormalTypeExpr(i,tp) - case i ~ None => NormalTypeExpr(i,Nil) } + def normalTypeExpr:Parser[TypeExpr] = ident ~ (typeParams?) ^^ { case i ~ Some(tp) => TypeExpr(i,tp) + case i ~ None => TypeExpr(i,Nil) } - def funcTypeExpr:Parser[FuncTypeExpr] = ("(" ~> repsep(typeExpr,",") <~ ")") ~ ("=>" ~> typeExpr) ^^ { - case pts ~ rt => FuncTypeExpr(pts,rt) } + def funcTypeExpr:Parser[TypeExpr] = ("(" ~> repsep(typeExpr,",") <~ ")") ~ ("=>" ~> typeExpr) ^^ { + case pts ~ rt => if(pts.length <= 8) + TypeExpr("Function" + pts.length, pts ::: List(rt)) + else + throw ParserError("can't make a function with more than 8 parameters") } def typeParams = "[" ~> repsep(typeExpr,",") <~ "]" def expr:Parser[Expr] = ( ifStatement | orExpr ) def ifStatement = (("if" ~> orExpr) ~ ("then" ~> orExpr) ~ ("else" ~> orExpr)) ^^ { case c ~ i ~ e => IfExpr(c,i,e) } def orExpr = andExpr * ( "or" ^^^ { (a:Expr, b:Expr) => Call("or",List(a,b)) } ) def andExpr = comparison * ( "and" ^^^ { (a:Expr, b:Expr) => Call("and",List(a,b)) } ) def comparison = sum * ( ">" ^^^ { (a:Expr, b:Expr) => Call(">",List(a,b)) } | "<" ^^^ { (a:Expr, b:Expr) => Call("<",List(a,b)) } | "==" ^^^ { (a:Expr, b:Expr) => Call("==",List(a,b)) } | "<=" ^^^ { (a:Expr, b:Expr) => Call("<=",List(a,b)) } | ">=" ^^^ { (a:Expr, b:Expr) => Call(">=",List(a,b)) } | "!=" ^^^ { (a:Expr, b:Expr) => Call("!=",List(a,b)) } ) // I'm sure there's a super-elegant way to do this, // but my Scala chops aren't up to it yet def sum = product * ( "+" ^^^ { (a:Expr, b:Expr) => Call("+",List(a,b)) } | "-" ^^^ { (a:Expr, b:Expr) => Call("-",List(a,b)) } ) def product = atom * ( "*" ^^^ { (a:Expr, b:Expr) => Call("*",List(a,b)) } | "/" ^^^ { (a:Expr, b:Expr) => Call("/",List(a,b)) } ) def atom = ( int | list | string | call | parenthesizedExpr | unaryMinus | unaryNot ) // todo: char lit (not in standardtokenparsers...) def list = "[" ~> repsep(expr,",") <~ "]" ^^ concatIze def string = stringLit ^^ { (s:String) => concatIze(new RichString(s) map { CharLit(_) }) } def concatIze(items:Seq[Expr]):Expr = items.foldRight(EmptyList.asInstanceOf[Expr]){ (i,a) => Call(":",List(i,a)) } def parenthesizedExpr = "(" ~> expr <~ ")" def unaryNot:Parser[Expr] = "!" ~> atom ^^ { a => Call("!",List(a)) } def unaryMinus:Parser[Expr] = "-" ~> atom ^^ { a => Call("*",List(a,IntLit(-1))) } def int = numericLit ^^ { s => IntLit(s.toInt) } def call = ident ~ (args ?) ^^ { case i ~ Some(a) => Call(i,a) - case i ~ None => Call(i,List()) } + case i ~ None => Call(i,Nil) } def args = "(" ~> repsep(expr,",") <~ ")" // END OF RULES def parse(s:String) = phrase(program)(new lexical.Scanner(s)) def parseTypeExpr(t:String) = phrase(typeExpr)(new lexical.Scanner(t)) match { case Success(t, _) => t case e: NoSuccess => throw new IllegalArgumentException(e.toString) } def apply(s:String) = { parse(s) match { case Success(tree, _) => tree case e: NoSuccess => - throw new ParserError(e.toString) + throw ParserError(e.toString) } } } diff --git a/src/vmlang/compiler/typecheck/Compliance.scala b/src/vmlang/compiler/typecheck/Compliance.scala index 0897f0c..443d113 100644 --- a/src/vmlang/compiler/typecheck/Compliance.scala +++ b/src/vmlang/compiler/typecheck/Compliance.scala @@ -1,23 +1,23 @@ package vmlang.compiler.typecheck import vmlang.compiler.ast._ case class TypeErrors(errors:List[CompilerError]) extends CompoundCompilerError(errors) abstract class TypeError extends NormalCompilerError case class NonexistentType(name:String) extends TypeError { val repr = "Nonexistent type: \"" + name + "\"" } case class Mismatch(expected:TypeExpr, given:TypeExpr) extends TypeError { - val repr = "Type mismatch. Expected: " + expected.shortRepr + "; given: " + given.shortRepr + val repr = "Type mismatch. Expected: " + expected.repr + "; given: " + given.repr } case class WrongNumTypeArgs(expected:Int, given:Int) extends TypeError { val repr = "Wrong number of type arguments. Expected: " + expected + "; given: " + given } case class WrongNumCallArgs(expected:Int, given:Int) extends TypeError { val repr = "Wrong number of arguments. Expected: " + expected + "; given: " + given } diff --git a/src/vmlang/compiler/typecheck/TypeTree.scala b/src/vmlang/compiler/typecheck/TypeTree.scala index cb925a4..90a2b1e 100644 --- a/src/vmlang/compiler/typecheck/TypeTree.scala +++ b/src/vmlang/compiler/typecheck/TypeTree.scala @@ -1,135 +1,94 @@ package vmlang.compiler.typecheck -import vmlang.compiler.ast.{TypeExpr, NormalTypeExpr, FuncTypeExpr} +import vmlang.compiler.ast.TypeExpr // could be more efficient: complies("Map[Num,Value]","TreeMap[Int,Float]") results in 44 calls to findSubType case class TypeTree(t:Type, subTypes:List[TypeTree]) { def complies(exp:TypeExpr, giv:TypeExpr):List[TypeError] = (checkValidTypeExpr(exp) ::: checkValidTypeExpr(giv)) match { - case Nil => (exp, giv) match { - case (e:NormalTypeExpr, g:NormalTypeExpr) => compliesNormal(e, g) - case (e:FuncTypeExpr , g:FuncTypeExpr ) => compliesFunc(e, g) - case (e , g ) => List(Mismatch(e, g)) + case Nil => descends(exp.name, giv.name) match { + case true => (exp.args zip giv.args) flatMap { p => complies(p._1, p._2) } + case false => List(Mismatch(exp, giv)) } - case es:List[TypeError] => es ::: ((exp, giv) match { - case (e:NormalTypeExpr, g:NormalTypeExpr) => Nil - case (e:FuncTypeExpr , g:FuncTypeExpr ) => Nil - case (e , g ) => List(Mismatch(e, g)) - }) + case es:List[TypeError] => es } - private def compliesNormal(exp:NormalTypeExpr, giv:NormalTypeExpr) = - descends(exp.name, giv.name) match { - case true => (exp.args zip giv.args) flatMap { p => complies(p._1, p._2) } - case false => List(Mismatch(exp, giv)) - } - - private def compliesFunc(exp:FuncTypeExpr, giv:FuncTypeExpr) = { - val expPs = exp.paramTypes - val givPs = giv.paramTypes - complies(exp.returnType, giv.returnType) ::: (expPs.length == givPs.length match { - case true => (expPs zip givPs) flatMap { p => complies(p._1, p._2) } - case false => List(WrongNumTypeArgs(expPs.length, givPs.length)) - }) - } - private def descends(e:String, g:String):Boolean = this findSubType e match { case Some(eTree) => eTree findSubType g match { case Some(gTree) => true case None => false } case None => throw new IllegalArgumentException("nonexistent type: " + e) } def deepestCommonAncestor(l:List[TypeExpr]):TypeExpr = l match { case Nil => throw new IllegalArgumentException("can't give DCA of empty list") case t :: Nil => t case t :: ts => deepestCommonAncestor(t,deepestCommonAncestor(ts)) } - def deepestCommonAncestor(a:TypeExpr, b:TypeExpr):TypeExpr = - (a, b) match { - case (a:NormalTypeExpr, b:NormalTypeExpr) => normalDCA(a, b) - case (a:FuncTypeExpr , b:FuncTypeExpr ) => funcDCA(a, b) - case (a , b ) => throw TypeErrors(List(Mismatch(a, b))) - } - - private def normalDCA(a:NormalTypeExpr, b:NormalTypeExpr):NormalTypeExpr = { + def deepestCommonAncestor(a:TypeExpr, b:TypeExpr):TypeExpr = { // TODO: this isn't really right for situations with different numbers of type args val (name, numArgs) = DCA(a.name, b.name) - NormalTypeExpr(name, + TypeExpr(name, ((a.args zip b.args) map { p => deepestCommonAncestor(p._1, p._2) }) take numArgs) } - private def funcDCA(a:FuncTypeExpr, b:FuncTypeExpr):FuncTypeExpr = { - val aps = a.paramTypes - val bps = b.paramTypes - (aps.length == bps.length) match { - case true => FuncTypeExpr((aps zip bps) map { p => deepestCommonAncestor(p._1, p._2) }, - deepestCommonAncestor(a.returnType, b.returnType)) - case false => throw TypeErrors(List(Mismatch(a, b))) - } - } - private def DCA(a:String, b:String):(String,Int) = ((path(a) zip path(b)) takeWhile { p => p._1 == p._2 }).last._1 private def path(tn:String):List[(String,Int)] = - path(List(),tn) match { + path(Nil,tn) match { case Some(l) => l case None => throw new NonexistentType(tn) } private def path(path:List[(String,Int)], tn:String):Option[List[(String,Int)]] = if(tn == t.name) Some(path ::: List((t.name,t.numParams))) else if(isLeaf) None else subTypes.map(_.path(path,tn)).find(_.isInstanceOf[Some[List[String]]]) match { case Some(Some(p)) => Some(path ::: List((t.name,t.numParams)) ::: p) case Some(None) => None // would never happen... case None => None } private def checkValidTypeExpr(te:TypeExpr):List[TypeError] = - te match { - case NormalTypeExpr(n, as) => checkExistentAndNumArgs(n, as.length) ::: - (as flatMap { a => checkValidTypeExpr(a) }) - case FuncTypeExpr(as, rt) => (rt :: as) flatMap { a => checkValidTypeExpr(a) } - } + checkExistentAndNumArgs(te.name, te.args.length) ::: (te.args flatMap { a => checkValidTypeExpr(a) }) private def checkExistentAndNumArgs(tn:String, numArgs:Int):List[TypeError] = findSubType(tn) match { case None => List(NonexistentType(tn)) case Some(tree) => { val expNum = tree.t.numParams if(numArgs == expNum) Nil else List(WrongNumTypeArgs(expNum, numArgs)) } } private def findSubType(tn:String):Option[TypeTree] = { if(tn == t.name) Some(this) else if(isLeaf) None else subTypes.map(_ findSubType tn).find(_.isInstanceOf[Some[TypeTree]]) match { case Some(tree) => tree case None => None } } def isLeaf = subTypes.isEmpty def prettyPrint:String = prettyPrint(0).mkString def prettyPrint(indent:Int):List[Char] = (" " * indent).toList ::: t.name.toList ::: List('\n') ::: ( subTypes flatMap { _ prettyPrint (indent + 2) }) }
vilterp/VMLang
7a103bea6a96f6dbaea1e9a12943d54fcd363149
worked on TypeTree (AGAIN). Wrote a bunch of function-specific code, but Function should really be in TypeTree just like everything else
diff --git a/.gitignore b/.gitignore index 19eaa85..e57a911 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,7 @@ .DS_Store bin/* vmlang_log.txt .settings/* .manager/* .classpath - +src/vmlang/compiler/testhelper diff --git a/build.xml b/build.xml index af8236e..d5d4b7e 100644 --- a/build.xml +++ b/build.xml @@ -1,47 +1,43 @@ <?xml version="1.0" encoding="UTF-8"?> -<project name="VMLang" default="test" basedir="."> +<project name="VMLang" default="compile_everything" basedir="."> <property name="base.dir" value="${basedir}" /> <property name="sources.dir" value="${base.dir}/src" /> <property name="build.dir" value="${base.dir}/bin" /> <!-- set up scala stuff --> <property name="scala.home" value="/Applications/scala-2.7.7"/> <property name="scala-library.jar" value="${scala.home}/lib/scala-library.jar"/> <path id="build.classpath"> <pathelement location="${scala-library.jar}"/> <pathelement location="${build.dir}"/> </path> <taskdef resource="scala/tools/ant/antlib.xml"> <classpath> <pathelement location="${scala.home}/lib/scala-compiler.jar"/> <pathelement location="${scala-library.jar}"/> </classpath> </taskdef> <!-- end scala setup --> <target name="compile_everything"> <antcall target="compile_vm"/> <antcall target="compile_compiler"/> </target> <target name="compile_vm"> <javac srcdir="${sources.dir}" destdir="${build.dir}" debug="true"/> </target> <target name="compile_compiler"> <scalac srcdir="${sources.dir}" destdir="${build.dir}" classpathref="build.classpath" scalacdebugging="true"> <include name="**/*.scala"/> <exclude name="**/*.java"/> </scalac> </target> - <target name="test" depends="compile_everything"> - <java classname="vmlang.compiler.Test" classpathref="build.classpath"/> - </target> - </project> diff --git a/src/vmlang/compiler/Util.scala b/src/vmlang/compiler/Util.scala index 0b73360..0f3ec41 100644 --- a/src/vmlang/compiler/Util.scala +++ b/src/vmlang/compiler/Util.scala @@ -1,20 +1,20 @@ package vmlang.compiler abstract class CompilerError extends Exception { val numErrors:Int val repr:String } // TODO: should have location, but can't implement - scala's combinator library drops it abstract class NormalCompilerError extends CompilerError { val numErrors = 1 } -abstract class CompoundCompilerError(errors:List[CompilerError]) { +abstract class CompoundCompilerError(errors:List[CompilerError]) extends CompilerError { val numErrors = errors.length val repr:String = (errors map { _.repr } ) mkString "\n" } case class NonexistentFuncError(funcName:String) extends NormalCompilerError { val repr = "Call to nonexistent function " + funcName } diff --git a/src/vmlang/compiler/ast/AST.scala b/src/vmlang/compiler/ast/AST.scala index 88f7ff0..60e248d 100644 --- a/src/vmlang/compiler/ast/AST.scala +++ b/src/vmlang/compiler/ast/AST.scala @@ -1,23 +1,32 @@ package vmlang.compiler.ast abstract class ASTNode case class Prog(defs:List[Def]) extends ASTNode case class Def(name:String, params:List[ParamSpec], returnType:TypeExpr, body:Expr) extends ASTNode case class ParamSpec(name:String, argType:TypeExpr) extends ASTNode -case class TypeExpr(name:String, args:List[TypeExpr]) extends ASTNode { - override val toString = name + args.mkString("[",",","]") + +abstract class TypeExpr extends ASTNode { + val shortRepr:String +} +case class NormalTypeExpr(name:String, args:List[TypeExpr]) extends TypeExpr { + override val toString = name + (if(args.isEmpty) "" else args.mkString("[",",","]")) + val shortRepr = name +} +case class FuncTypeExpr(paramTypes:List[TypeExpr], returnType:TypeExpr) extends TypeExpr { + override val toString = paramTypes.mkString("(",",",")") + " => " + returnType + val shortRepr = toString } abstract class Expr extends ASTNode case class IfExpr(condition:Expr, ifExpr:Expr, thenExpr:Expr) extends Expr case class Call(name:String, args:List[Expr]) extends Expr abstract class Atom extends Expr case class IntLit(value:Int) extends Atom case class FloatLit(value:Float) extends Atom case class CharLit(value:Char) extends Atom case object EmptyList extends Atom diff --git a/src/vmlang/compiler/ast/NewParser.scala b/src/vmlang/compiler/ast/NewParser.scala index 877c9b4..1154cd0 100644 --- a/src/vmlang/compiler/ast/NewParser.scala +++ b/src/vmlang/compiler/ast/NewParser.scala @@ -1,97 +1,97 @@ -import scala.util.parsing.combinator._ -import scala.util.parsing.input._ - -// Bug: CharSequenceReader eliminates spaces in strings ("hello there" => StringLit(hellothere)) - -object Test extends RegexParsers { - - def apply(input:String) = - doRule(expr,input) match { - case Success(t, _) => t - case e: NoSuccess => throw new IllegalArgumentException(e.toString) - } - - def doRule(rule:Parser[Any], input:String) = phrase(rule)(new CharSequenceReader(input)) - - def expr = ( float | int | variable | string | char ) - - def float = regex("""-?(\d+\.\d+|\.\d+)""".r) ~ (sciNot?) ^^ { - case f ~ Some(s) => FloatLit(checkFloatSize(f,s)) - case f ~ None => FloatLit(checkFloatSize(f,0)) } - - def int = regex("""-?\d+""".r) ~ (sciNot?) ^^ { - case i ~ Some(s) => IntLit(checkIntSize(i,s)) - case i ~ None => IntLit(checkIntSize(i,0)) } - - def checkIntSize(v:String, e:Int):Int = { - val bi = BigInt(v) * (BigInt(10) pow e) - if(bi > Math.MAX_INT) - throw new IllegalArgumentException("int literal too big") - else if(bi < Math.MIN_INT) - throw new IllegalArgumentException("int literal too small") - else - bi.intValue - } - - def checkFloatSize(v:String, e:Int):Float = { - val bd = BigDecimal(v) * new BigDecimal(new java.math.BigDecimal(10) pow e) - if(bd > BigDecimal(Math.MAX_FLOAT)) - throw new IllegalArgumentException("float literal too big") - else if(bd < BigDecimal(Math.MIN_FLOAT)) - throw new IllegalArgumentException("float literal too small") - else - bd.floatValue - } - - def sciNot = regex("""[eE]-?\d+""".r) ^^ { - try { - i => i.substring(1).toInt - } catch { - case c:NumberFormatException => throw new IllegalArgumentException("exponent too big") - } } - - def string = "\"" ~> (stringChar*) <~ "\"" ^^ { l => StringLit(l.mkString) } // should actually map to list of char... - - def stringChar = ( unicodeChar | escapedCharInStr | normalCharInStr ) - - def char = "'" ~> ( unicodeChar | escapedCharInChar | normalCharInChar ) <~ "'" ^^ { c => CharLit(c) } - - def normalCharInChar = regex("""[ -&\(-~]""".r) ^^ { s => s charAt 0 } - - def escapedCharInChar = regex("""\\[nt']""".r) ^^ { case "\\n" => '\n' - case "\\t" => '\t' - case "\\'" => '\'' } - - def normalCharInStr = regex("""[ -!#-~]""".r) ^^ { s => s charAt 0 } - - def escapedCharInStr = regex("""\\[nt\"]""".r) ^^ { case "\\n" => '\n' - case "\\t" => '\t' - case "\\\"" => '"' } - - def unicodeChar = regex("""\\u[0-9a-f]{1,4}""".r) ^^ { s => Integer.parseInt(s substring 2,16).toChar } - - def variable = regex("""[a-zA-Z_]\w*""".r) ^^ { i => Var(i) } - - def main(args:Array[String]) = { - List("123","-123","123.1234","123e4","hello","hello_o","HelloYo","_yo", - "64654654654654645564654456564654654654654","5e65465465465465465","-.123","000.3","8e4","Infinity", - "'a'","'!'","'\\n'","'\\u61'","'\\''", - "\"Sup?\"","\"hey\\nthere\"","\"'that is cool'\"","\"\\\"\"") foreach test - } - - def test(input:String) = println(input + " => " + { - try { - apply(input) - } catch { - case e: IllegalArgumentException => "error: " + e.getMessage - } - }) - -} - -abstract class Atom -case class CharLit(value:Char) extends Atom -case class FloatLit(value:Float) extends Atom -case class IntLit(value:Int) extends Atom -case class StringLit(value:String) extends Atom -case class Var(name:String) extends Atom +// import scala.util.parsing.combinator._ +// import scala.util.parsing.input._ +// +// // Bug: CharSequenceReader eliminates spaces in strings ("hello there" => StringLit(hellothere)) +// +// object Test extends RegexParsers { +// +// def apply(input:String) = +// doRule(expr,input) match { +// case Success(t, _) => t +// case e: NoSuccess => throw new IllegalArgumentException(e.toString) +// } +// +// def doRule(rule:Parser[Any], input:String) = phrase(rule)(new CharSequenceReader(input)) +// +// def expr = ( float | int | variable | string | char ) +// +// def float = regex("""-?(\d+\.\d+|\.\d+)""".r) ~ (sciNot?) ^^ { +// case f ~ Some(s) => FloatLit(checkFloatSize(f,s)) +// case f ~ None => FloatLit(checkFloatSize(f,0)) } +// +// def int = regex("""-?\d+""".r) ~ (sciNot?) ^^ { +// case i ~ Some(s) => IntLit(checkIntSize(i,s)) +// case i ~ None => IntLit(checkIntSize(i,0)) } +// +// def checkIntSize(v:String, e:Int):Int = { +// val bi = BigInt(v) * (BigInt(10) pow e) +// if(bi > Math.MAX_INT) +// throw new IllegalArgumentException("int literal too big") +// else if(bi < Math.MIN_INT) +// throw new IllegalArgumentException("int literal too small") +// else +// bi.intValue +// } +// +// def checkFloatSize(v:String, e:Int):Float = { +// val bd = BigDecimal(v) * new BigDecimal(new java.math.BigDecimal(10) pow e) +// if(bd > BigDecimal(Math.MAX_FLOAT)) +// throw new IllegalArgumentException("float literal too big") +// else if(bd < BigDecimal(Math.MIN_FLOAT)) +// throw new IllegalArgumentException("float literal too small") +// else +// bd.floatValue +// } +// +// def sciNot = regex("""[eE]-?\d+""".r) ^^ { +// try { +// i => i.substring(1).toInt +// } catch { +// case c:NumberFormatException => throw new IllegalArgumentException("exponent too big") +// } } +// +// def string = "\"" ~> (stringChar*) <~ "\"" ^^ { l => StringLit(l.mkString) } // should actually map to list of char... +// +// def stringChar = ( unicodeChar | escapedCharInStr | normalCharInStr ) +// +// def char = "'" ~> ( unicodeChar | escapedCharInChar | normalCharInChar ) <~ "'" ^^ { c => CharLit(c) } +// +// def normalCharInChar = regex("""[ -&\(-~]""".r) ^^ { s => s charAt 0 } +// +// def escapedCharInChar = regex("""\\[nt']""".r) ^^ { case "\\n" => '\n' +// case "\\t" => '\t' +// case "\\'" => '\'' } +// +// def normalCharInStr = regex("""[ -!#-~]""".r) ^^ { s => s charAt 0 } +// +// def escapedCharInStr = regex("""\\[nt\"]""".r) ^^ { case "\\n" => '\n' +// case "\\t" => '\t' +// case "\\\"" => '"' } +// +// def unicodeChar = regex("""\\u[0-9a-f]{1,4}""".r) ^^ { s => Integer.parseInt(s substring 2,16).toChar } +// +// def variable = regex("""[a-zA-Z_]\w*""".r) ^^ { i => Var(i) } +// +// def main(args:Array[String]) = { +// List("123","-123","123.1234","123e4","hello","hello_o","HelloYo","_yo", +// "64654654654654645564654456564654654654654","5e65465465465465465","-.123","000.3","8e4","Infinity", +// "'a'","'!'","'\\n'","'\\u61'","'\\''", +// "\"Sup?\"","\"hey\\nthere\"","\"'that is cool'\"","\"\\\"\"") foreach test +// } +// +// def test(input:String) = println(input + " => " + { +// try { +// apply(input) +// } catch { +// case e: IllegalArgumentException => "error: " + e.getMessage +// } +// }) +// +// } +// +// abstract class Atom +// case class CharLit(value:Char) extends Atom +// case class FloatLit(value:Float) extends Atom +// case class IntLit(value:Int) extends Atom +// case class StringLit(value:String) extends Atom +// case class Var(name:String) extends Atom diff --git a/src/vmlang/compiler/ast/Parser.scala b/src/vmlang/compiler/ast/Parser.scala index 710fe9c..e685a7b 100644 --- a/src/vmlang/compiler/ast/Parser.scala +++ b/src/vmlang/compiler/ast/Parser.scala @@ -1,103 +1,108 @@ package vmlang.compiler.ast import scala.runtime.RichString import scala.util.parsing.combinator.syntactical._ class ParserError(msg:String) extends NormalCompilerError { val repr = "Parser Error: " + msg } object Parser extends StandardTokenParsers { - lexical.delimiters ++= List("+","-","*","/","(",")","[","]","=",":",",",">","<", + lexical.delimiters ++= List("+","-","*","/","(",")","[","]","=","=>",":",",",">","<", ">=","<=","==","!","!=") lexical.reserved ++= List("if","then","else","and","or") // RULES def program = (definition *) ^^ { l => Prog(l) } def definition = ident ~ (paramsSpec?) ~ typeSpec ~ ("=" ~> expr) ^^ { case i ~ Some(ps) ~ rt ~ e => Def(i,ps,rt,e) case i ~ None ~ rt ~ e => Def(i,Nil,rt,e) } def paramsSpec = "(" ~> repsep(paramSpec, ",") <~ ")" def paramSpec = ident ~ typeSpec ^^ { case i ~ t => ParamSpec(i,t) } def typeSpec = ":" ~> typeExpr - def typeExpr:Parser[TypeExpr] = ident ~ (typeParams?) ^^ { case i ~ Some(tp) => TypeExpr(i,tp) - case i ~ None => TypeExpr(i,Nil) } + def typeExpr:Parser[TypeExpr] = ( normalTypeExpr | funcTypeExpr ) + + def normalTypeExpr:Parser[NormalTypeExpr] = ident ~ (typeParams?) ^^ { case i ~ Some(tp) => NormalTypeExpr(i,tp) + case i ~ None => NormalTypeExpr(i,Nil) } + + def funcTypeExpr:Parser[FuncTypeExpr] = ("(" ~> repsep(typeExpr,",") <~ ")") ~ ("=>" ~> typeExpr) ^^ { + case pts ~ rt => FuncTypeExpr(pts,rt) } def typeParams = "[" ~> repsep(typeExpr,",") <~ "]" def expr:Parser[Expr] = ( ifStatement | orExpr ) def ifStatement = (("if" ~> orExpr) ~ ("then" ~> orExpr) ~ ("else" ~> orExpr)) ^^ { case c ~ i ~ e => IfExpr(c,i,e) } def orExpr = andExpr * ( "or" ^^^ { (a:Expr, b:Expr) => Call("or",List(a,b)) } ) def andExpr = comparison * ( "and" ^^^ { (a:Expr, b:Expr) => Call("and",List(a,b)) } ) def comparison = sum * ( ">" ^^^ { (a:Expr, b:Expr) => Call(">",List(a,b)) } | "<" ^^^ { (a:Expr, b:Expr) => Call("<",List(a,b)) } | "==" ^^^ { (a:Expr, b:Expr) => Call("==",List(a,b)) } | "<=" ^^^ { (a:Expr, b:Expr) => Call("<=",List(a,b)) } | ">=" ^^^ { (a:Expr, b:Expr) => Call(">=",List(a,b)) } | "!=" ^^^ { (a:Expr, b:Expr) => Call("!=",List(a,b)) } ) // I'm sure there's a super-elegant way to do this, // but my Scala chops aren't up to it yet def sum = product * ( "+" ^^^ { (a:Expr, b:Expr) => Call("+",List(a,b)) } | "-" ^^^ { (a:Expr, b:Expr) => Call("-",List(a,b)) } ) def product = atom * ( "*" ^^^ { (a:Expr, b:Expr) => Call("*",List(a,b)) } | "/" ^^^ { (a:Expr, b:Expr) => Call("/",List(a,b)) } ) def atom = ( int | list | string | call | parenthesizedExpr | unaryMinus | unaryNot ) // todo: char lit (not in standardtokenparsers...) def list = "[" ~> repsep(expr,",") <~ "]" ^^ concatIze def string = stringLit ^^ { (s:String) => concatIze(new RichString(s) map { CharLit(_) }) } def concatIze(items:Seq[Expr]):Expr = items.foldRight(EmptyList.asInstanceOf[Expr]){ (i,a) => Call(":",List(i,a)) } def parenthesizedExpr = "(" ~> expr <~ ")" def unaryNot:Parser[Expr] = "!" ~> atom ^^ { a => Call("!",List(a)) } def unaryMinus:Parser[Expr] = "-" ~> atom ^^ { a => Call("*",List(a,IntLit(-1))) } def int = numericLit ^^ { s => IntLit(s.toInt) } def call = ident ~ (args ?) ^^ { case i ~ Some(a) => Call(i,a) case i ~ None => Call(i,List()) } def args = "(" ~> repsep(expr,",") <~ ")" // END OF RULES def parse(s:String) = phrase(program)(new lexical.Scanner(s)) def parseTypeExpr(t:String) = phrase(typeExpr)(new lexical.Scanner(t)) match { case Success(t, _) => t case e: NoSuccess => throw new IllegalArgumentException(e.toString) } def apply(s:String) = { parse(s) match { case Success(tree, _) => tree case e: NoSuccess => throw new ParserError(e.toString) } } } diff --git a/src/vmlang/compiler/icode/ICode.scala b/src/vmlang/compiler/icode/ICode.scala deleted file mode 100644 index bf09195..0000000 --- a/src/vmlang/compiler/icode/ICode.scala +++ /dev/null @@ -1,34 +0,0 @@ -package vmlang.compiler - -// intermediate code: source > intermediate code > { MiniVM, JVM, x86 ... } - -abstract class IOpcode - -case object Stop extends IOpcode -case class Goto(a:Int) extends IOpcode -case class GotoFunc(f:String) extends IOpcode -case class GotoIf(ref:IOpcode) extends IOpcode -case object RetI extends IOpcode - -case class PushConstI(c:Int) extends IOpcode -case class PushConstC(c:Char) extends IOpcode - -case object AddI extends IOpcode -case object SubI extends IOpcode -case object MultI extends IOpcode -case object DivI extends IOpcode - -case class CmpEq(ref:IOpcode) extends IOpcode -case class CmpNeq(ref:IOpcode) extends IOpcode -case class CmpGt(ref:IOpcode) extends IOpcode -case class CmpGte(ref:IOpcode) extends IOpcode -case class CmpLt(ref:IOpcode) extends IOpcode -case class CmpLte(ref:IOpcode) extends IOpcode - -case object Neg extends IOpcode -case object NegLt extends IOpcode -case object And extends IOpcode -case object Or extends IOpcode - -case object PrintChar extends IOpcode -case object ReadChar extends IOpcode diff --git a/src/vmlang/compiler/test.scala b/src/vmlang/compiler/test.scala deleted file mode 100644 index 34c77f9..0000000 --- a/src/vmlang/compiler/test.scala +++ /dev/null @@ -1,18 +0,0 @@ -package vmlang.compiler - -import vmlang.compiler.ast._ - -object Test extends UnitTest { - - def main(args:Array[String]) = { - shouldBe(2,2) - } - -} - -class UnitTest { - - def shouldBe(a:Any, b:Any) = - if (a == b) println("pass") else println("fail. should be: " + b + "; found: " + a) - -} \ No newline at end of file diff --git a/src/vmlang/compiler/typecheck/Compliance.scala b/src/vmlang/compiler/typecheck/Compliance.scala index a05f263..0897f0c 100644 --- a/src/vmlang/compiler/typecheck/Compliance.scala +++ b/src/vmlang/compiler/typecheck/Compliance.scala @@ -1,23 +1,23 @@ package vmlang.compiler.typecheck import vmlang.compiler.ast._ -class TypeErrors(errors:List[CompilerError]) extends CompoundCompilerError(errors) +case class TypeErrors(errors:List[CompilerError]) extends CompoundCompilerError(errors) abstract class TypeError extends NormalCompilerError case class NonexistentType(name:String) extends TypeError { val repr = "Nonexistent type: \"" + name + "\"" } case class Mismatch(expected:TypeExpr, given:TypeExpr) extends TypeError { - val repr = "Type mismatch. Expected: " + expected.name + "; given: " + given.name + val repr = "Type mismatch. Expected: " + expected.shortRepr + "; given: " + given.shortRepr } case class WrongNumTypeArgs(expected:Int, given:Int) extends TypeError { val repr = "Wrong number of type arguments. Expected: " + expected + "; given: " + given } case class WrongNumCallArgs(expected:Int, given:Int) extends TypeError { val repr = "Wrong number of arguments. Expected: " + expected + "; given: " + given } diff --git a/src/vmlang/compiler/typecheck/Type.scala b/src/vmlang/compiler/typecheck/Type.scala index 278384c..f8ceb8d 100644 --- a/src/vmlang/compiler/typecheck/Type.scala +++ b/src/vmlang/compiler/typecheck/Type.scala @@ -1,32 +1,26 @@ package vmlang.compiler.typecheck import vmlang.compiler.ast._ -abstract class Type -case class FuncType(paramTypes:List[TypeExpr], returnType:TypeExpr) extends Type { - override def toString = paramTypes.mkString("(",",",")") + " => " + returnType -} -abstract class ExprType extends Type { +abstract class Type { val name:String val numParams:Int override def toString = name def toTypeExpr = Parser.parseTypeExpr(toString) } -case class AbsType(name:String, numParams:Int) extends ExprType -abstract class ConcreteType extends ExprType +case class AbsType(name:String, numParams:Int) extends Type +abstract class ConcreteType extends Type case class RefType(name:String, numParams:Int) extends ConcreteType case class PrimType(name:String) extends ConcreteType { val numParams = 0 } /* Type - [FuncType] - ExprType - [AbsType] - ConcreteType - [RefType] - [PrimType] + [AbsType] + ConcreteType + [RefType] + [PrimType] -*/ \ No newline at end of file +*/ diff --git a/src/vmlang/compiler/typecheck/TypeTree.scala b/src/vmlang/compiler/typecheck/TypeTree.scala index b2e3f9a..cb925a4 100644 --- a/src/vmlang/compiler/typecheck/TypeTree.scala +++ b/src/vmlang/compiler/typecheck/TypeTree.scala @@ -1,107 +1,135 @@ package vmlang.compiler.typecheck -import vmlang.compiler.ast.TypeExpr +import vmlang.compiler.ast.{TypeExpr, NormalTypeExpr, FuncTypeExpr} -// could be more efficient: complies("Map[Num,Value]","TreeMap[Int,Float]") results in 44 calls to findTree +// could be more efficient: complies("Map[Num,Value]","TreeMap[Int,Float]") results in 44 calls to findSubType -case class TypeTree(t:ExprType, subTypes:List[TypeTree]) { +case class TypeTree(t:Type, subTypes:List[TypeTree]) { - def find(tn:String) = - findTree(tn) match { - case Some(tree) => tree.t - case None => - throw new NonexistentType(tn) + def complies(exp:TypeExpr, giv:TypeExpr):List[TypeError] = + (checkValidTypeExpr(exp) ::: checkValidTypeExpr(giv)) match { + case Nil => (exp, giv) match { + case (e:NormalTypeExpr, g:NormalTypeExpr) => compliesNormal(e, g) + case (e:FuncTypeExpr , g:FuncTypeExpr ) => compliesFunc(e, g) + case (e , g ) => List(Mismatch(e, g)) + } + case es:List[TypeError] => es ::: ((exp, giv) match { + case (e:NormalTypeExpr, g:NormalTypeExpr) => Nil + case (e:FuncTypeExpr , g:FuncTypeExpr ) => Nil + case (e , g ) => List(Mismatch(e, g)) + }) + } + + private def compliesNormal(exp:NormalTypeExpr, giv:NormalTypeExpr) = + descends(exp.name, giv.name) match { + case true => (exp.args zip giv.args) flatMap { p => complies(p._1, p._2) } + case false => List(Mismatch(exp, giv)) + } + + private def compliesFunc(exp:FuncTypeExpr, giv:FuncTypeExpr) = { + val expPs = exp.paramTypes + val givPs = giv.paramTypes + complies(exp.returnType, giv.returnType) ::: (expPs.length == givPs.length match { + case true => (expPs zip givPs) flatMap { p => complies(p._1, p._2) } + case false => List(WrongNumTypeArgs(expPs.length, givPs.length)) + }) + } + + private def descends(e:String, g:String):Boolean = + this findSubType e match { + case Some(eTree) => eTree findSubType g match { + case Some(gTree) => true + case None => false + } + case None => throw new IllegalArgumentException("nonexistent type: " + e) + } + + def deepestCommonAncestor(l:List[TypeExpr]):TypeExpr = + l match { + case Nil => throw new IllegalArgumentException("can't give DCA of empty list") + case t :: Nil => t + case t :: ts => deepestCommonAncestor(t,deepestCommonAncestor(ts)) + } + + def deepestCommonAncestor(a:TypeExpr, b:TypeExpr):TypeExpr = + (a, b) match { + case (a:NormalTypeExpr, b:NormalTypeExpr) => normalDCA(a, b) + case (a:FuncTypeExpr , b:FuncTypeExpr ) => funcDCA(a, b) + case (a , b ) => throw TypeErrors(List(Mismatch(a, b))) + } + + private def normalDCA(a:NormalTypeExpr, b:NormalTypeExpr):NormalTypeExpr = { + // TODO: this isn't really right for situations with different numbers of type args + val (name, numArgs) = DCA(a.name, b.name) + NormalTypeExpr(name, + ((a.args zip b.args) map { p => deepestCommonAncestor(p._1, p._2) }) take numArgs) + } + + private def funcDCA(a:FuncTypeExpr, b:FuncTypeExpr):FuncTypeExpr = { + val aps = a.paramTypes + val bps = b.paramTypes + (aps.length == bps.length) match { + case true => FuncTypeExpr((aps zip bps) map { p => deepestCommonAncestor(p._1, p._2) }, + deepestCommonAncestor(a.returnType, b.returnType)) + case false => throw TypeErrors(List(Mismatch(a, b))) } + } + + private def DCA(a:String, b:String):(String,Int) = + ((path(a) zip path(b)) takeWhile { p => p._1 == p._2 }).last._1 - private def findTree(tn:String):Option[TypeTree] = { - println(t.name + " findTree " + tn) - if (tn == t.name) + private def path(tn:String):List[(String,Int)] = + path(List(),tn) match { + case Some(l) => l + case None => throw new NonexistentType(tn) + } + + private def path(path:List[(String,Int)], tn:String):Option[List[(String,Int)]] = + if(tn == t.name) + Some(path ::: List((t.name,t.numParams))) + else if(isLeaf) + None + else + subTypes.map(_.path(path,tn)).find(_.isInstanceOf[Some[List[String]]]) match { + case Some(Some(p)) => Some(path ::: List((t.name,t.numParams)) ::: p) + case Some(None) => None // would never happen... + case None => None + } + + private def checkValidTypeExpr(te:TypeExpr):List[TypeError] = + te match { + case NormalTypeExpr(n, as) => checkExistentAndNumArgs(n, as.length) ::: + (as flatMap { a => checkValidTypeExpr(a) }) + case FuncTypeExpr(as, rt) => (rt :: as) flatMap { a => checkValidTypeExpr(a) } + } + + private def checkExistentAndNumArgs(tn:String, numArgs:Int):List[TypeError] = + findSubType(tn) match { + case None => List(NonexistentType(tn)) + case Some(tree) => { + val expNum = tree.t.numParams + if(numArgs == expNum) Nil else List(WrongNumTypeArgs(expNum, numArgs)) + } + } + + private def findSubType(tn:String):Option[TypeTree] = { + if(tn == t.name) Some(this) - else if (isLeaf) + else if(isLeaf) None else - subTypes.map(_ findTree tn).find(_.isInstanceOf[Some[TypeTree]]) match { + subTypes.map(_ findSubType tn).find(_.isInstanceOf[Some[TypeTree]]) match { case Some(tree) => tree case None => None } } - def complies(expected:TypeExpr, given:TypeExpr):List[TypeError] = - complies(this,expected,given) - - private def complies(topLevel:TypeTree, expected:TypeExpr, given:TypeExpr):List[TypeError] = - findTree(expected.name) match { - // expected type exists - case Some(expTree) => - expTree findTree given.name match { - // given type descends from expected type - case Some(givTree) => cmpTypeArgs(expected.args,expTree.t,given.args,givTree.t,topLevel) - // given type doesn't descend from expected type - case None => topLevel findTree given.name match { - // given type doesn't descend, but exists - case Some(givTree) => List(Mismatch(expected,given)) ::: - cmpTypeArgs(expected.args,expTree.t,given.args,givTree.t,topLevel) - // given type doesn't exist - case None => List(NonexistentType(given.name)) - } - } - // expected type doesn't exist - case None => List(NonexistentType(expected.name)) ::: (topLevel findTree given.name match { - // given type exists - case Some(givTree) => cmpNumTypeArgs(givTree.t, given.args) - // neither type exists - case None => List(NonexistentType(given.name)) - }) - } - - private def cmpTypeArgs(exp:List[TypeExpr], expType:ExprType, - giv:List[TypeExpr], givType:ExprType, - topLevel:TypeTree):List[TypeError] = - ((exp zip giv) flatMap { p => topLevel.complies(p._1, p._2) }) ::: - cmpNumTypeArgs(expType, exp) ::: cmpNumTypeArgs(givType, giv) ::: - checkExistent(exp, topLevel) ::: checkExistent(giv, topLevel) - - private def checkExistent(ts:List[TypeExpr], topLevel:TypeTree):List[TypeError] = - ts flatMap { t => topLevel findTree t.name match { - case Some(_) => Nil - case None => List(NonexistentType(t.name)) - } } - - private def cmpNumTypeArgs(t:ExprType, tas:List[TypeExpr]):List[TypeError] = - if(t.numParams == tas.length) - Nil - else - List(WrongNumTypeArgs(t.numParams, tas.length)) - - // def deepestCommonAncestor(a:TypeExpr, b:TypeExpr):TypeExpr = - // find(commonPath(a.name,b.name).last) - // - // private def commonPath(a:String, b:String):List[String] = - // (path(a) zip path(b)) takeWhile { p => p._1 == p._2 } map { p => p._1 } - // - // private def path(tn:String):List[String] = - // path(List(),tn) match { - // case Some(l) => l - // case None => throw new NonexistentType(tn) - // } - // - // private def path(path:List[String], tn:String):Option[List[String]] = - // if(tn == t.name) - // Some(path ::: List(tn)) - // else if(isLeaf) - // None - // else - // subTypes.map(_.path(path,tn)).find(_.isInstanceOf[Some[List[String]]]) match { - // case Some(Some(p)) => Some(path ::: List(t.name) ::: p) - // case None => None - // } + def isLeaf = subTypes.isEmpty def prettyPrint:String = prettyPrint(0).mkString def prettyPrint(indent:Int):List[Char] = (" " * indent).toList ::: t.name.toList ::: List('\n') ::: ( subTypes flatMap { _ prettyPrint (indent + 2) }) - def isLeaf = subTypes.isEmpty - }
vilterp/VMLang
23220385ce1d0e1392ab8e3cc9f773e65a10bcf2
worked on TypeTree#complies
diff --git a/src/vmlang/compiler/Util.scala b/src/vmlang/compiler/Util.scala index b489d72..0b73360 100644 --- a/src/vmlang/compiler/Util.scala +++ b/src/vmlang/compiler/Util.scala @@ -1,20 +1,20 @@ package vmlang.compiler abstract class CompilerError extends Exception { val numErrors:Int val repr:String } // TODO: should have location, but can't implement - scala's combinator library drops it abstract class NormalCompilerError extends CompilerError { val numErrors = 1 } abstract class CompoundCompilerError(errors:List[CompilerError]) { - def numErrors = errors.length - def repr:String = (errors flatMap { _.repr } ) mkString "\n" + val numErrors = errors.length + val repr:String = (errors map { _.repr } ) mkString "\n" } -class NonexistentFuncError(funcName:String,inDef:String) extends NormalCompilerError { - val repr = "reference to nonexistent function " + funcName + " in " + inDef -} \ No newline at end of file +case class NonexistentFuncError(funcName:String) extends NormalCompilerError { + val repr = "Call to nonexistent function " + funcName +} diff --git a/src/vmlang/compiler/ast/AST.scala b/src/vmlang/compiler/ast/AST.scala index ed07c2a..88f7ff0 100644 --- a/src/vmlang/compiler/ast/AST.scala +++ b/src/vmlang/compiler/ast/AST.scala @@ -1,21 +1,23 @@ package vmlang.compiler.ast abstract class ASTNode case class Prog(defs:List[Def]) extends ASTNode -case class Def(name:String, args:List[ArgSpec], returnType:TypeExpr, body:Expr) extends ASTNode -case class ArgSpec(name:String, argType:TypeExpr) extends ASTNode -case class TypeExpr(name:String) extends ASTNode +case class Def(name:String, params:List[ParamSpec], returnType:TypeExpr, body:Expr) extends ASTNode +case class ParamSpec(name:String, argType:TypeExpr) extends ASTNode +case class TypeExpr(name:String, args:List[TypeExpr]) extends ASTNode { + override val toString = name + args.mkString("[",",","]") +} abstract class Expr extends ASTNode case class IfExpr(condition:Expr, ifExpr:Expr, thenExpr:Expr) extends Expr case class Call(name:String, args:List[Expr]) extends Expr abstract class Atom extends Expr case class IntLit(value:Int) extends Atom case class FloatLit(value:Float) extends Atom case class CharLit(value:Char) extends Atom case object EmptyList extends Atom diff --git a/src/vmlang/compiler/ast/Parser.scala b/src/vmlang/compiler/ast/Parser.scala index f50494b..710fe9c 100644 --- a/src/vmlang/compiler/ast/Parser.scala +++ b/src/vmlang/compiler/ast/Parser.scala @@ -1,102 +1,103 @@ package vmlang.compiler.ast import scala.runtime.RichString import scala.util.parsing.combinator.syntactical._ class ParserError(msg:String) extends NormalCompilerError { val repr = "Parser Error: " + msg } object Parser extends StandardTokenParsers { lexical.delimiters ++= List("+","-","*","/","(",")","[","]","=",":",",",">","<", ">=","<=","==","!","!=") lexical.reserved ++= List("if","then","else","and","or") // RULES def program = (definition *) ^^ { l => Prog(l) } - def definition = ident ~ (argsSpec?) ~ typeSpec ~ ("=" ~> expr) ^^ { - case i ~ Some(as) ~ rt ~ e => Def(i,as,rt,e) + def definition = ident ~ (paramsSpec?) ~ typeSpec ~ ("=" ~> expr) ^^ { + case i ~ Some(ps) ~ rt ~ e => Def(i,ps,rt,e) case i ~ None ~ rt ~ e => Def(i,Nil,rt,e) } - def argsSpec = "(" ~> repsep(argSpec, ",") <~ ")" + def paramsSpec = "(" ~> repsep(paramSpec, ",") <~ ")" - def argSpec = ident ~ typeSpec ^^ { case i ~ t => ArgSpec(i,t) } + def paramSpec = ident ~ typeSpec ^^ { case i ~ t => ParamSpec(i,t) } def typeSpec = ":" ~> typeExpr - def typeExpr:Parser[TypeExpr] = ident ^^ { i => TypeExpr(i) } + def typeExpr:Parser[TypeExpr] = ident ~ (typeParams?) ^^ { case i ~ Some(tp) => TypeExpr(i,tp) + case i ~ None => TypeExpr(i,Nil) } def typeParams = "[" ~> repsep(typeExpr,",") <~ "]" def expr:Parser[Expr] = ( ifStatement | orExpr ) def ifStatement = (("if" ~> orExpr) ~ ("then" ~> orExpr) ~ ("else" ~> orExpr)) ^^ { case c ~ i ~ e => IfExpr(c,i,e) } def orExpr = andExpr * ( "or" ^^^ { (a:Expr, b:Expr) => Call("or",List(a,b)) } ) def andExpr = comparison * ( "and" ^^^ { (a:Expr, b:Expr) => Call("and",List(a,b)) } ) def comparison = sum * ( ">" ^^^ { (a:Expr, b:Expr) => Call(">",List(a,b)) } | "<" ^^^ { (a:Expr, b:Expr) => Call("<",List(a,b)) } | "==" ^^^ { (a:Expr, b:Expr) => Call("==",List(a,b)) } | "<=" ^^^ { (a:Expr, b:Expr) => Call("<=",List(a,b)) } | ">=" ^^^ { (a:Expr, b:Expr) => Call(">=",List(a,b)) } | "!=" ^^^ { (a:Expr, b:Expr) => Call("!=",List(a,b)) } ) // I'm sure there's a super-elegant way to do this, // but my Scala chops aren't up to it yet def sum = product * ( "+" ^^^ { (a:Expr, b:Expr) => Call("+",List(a,b)) } | "-" ^^^ { (a:Expr, b:Expr) => Call("-",List(a,b)) } ) def product = atom * ( "*" ^^^ { (a:Expr, b:Expr) => Call("*",List(a,b)) } | "/" ^^^ { (a:Expr, b:Expr) => Call("/",List(a,b)) } ) def atom = ( int | list | string | call | parenthesizedExpr | unaryMinus | unaryNot ) // todo: char lit (not in standardtokenparsers...) def list = "[" ~> repsep(expr,",") <~ "]" ^^ concatIze def string = stringLit ^^ { (s:String) => concatIze(new RichString(s) map { CharLit(_) }) } def concatIze(items:Seq[Expr]):Expr = items.foldRight(EmptyList.asInstanceOf[Expr]){ (i,a) => Call(":",List(i,a)) } def parenthesizedExpr = "(" ~> expr <~ ")" def unaryNot:Parser[Expr] = "!" ~> atom ^^ { a => Call("!",List(a)) } def unaryMinus:Parser[Expr] = "-" ~> atom ^^ { a => Call("*",List(a,IntLit(-1))) } def int = numericLit ^^ { s => IntLit(s.toInt) } def call = ident ~ (args ?) ^^ { case i ~ Some(a) => Call(i,a) case i ~ None => Call(i,List()) } def args = "(" ~> repsep(expr,",") <~ ")" // END OF RULES def parse(s:String) = phrase(program)(new lexical.Scanner(s)) def parseTypeExpr(t:String) = phrase(typeExpr)(new lexical.Scanner(t)) match { case Success(t, _) => t case e: NoSuccess => throw new IllegalArgumentException(e.toString) } def apply(s:String) = { parse(s) match { case Success(tree, _) => tree case e: NoSuccess => throw new ParserError(e.toString) } } } diff --git a/src/vmlang/compiler/typecheck/Compliance.scala b/src/vmlang/compiler/typecheck/Compliance.scala index 0cf6007..a05f263 100644 --- a/src/vmlang/compiler/typecheck/Compliance.scala +++ b/src/vmlang/compiler/typecheck/Compliance.scala @@ -1,16 +1,23 @@ package vmlang.compiler.typecheck -abstract class TypeCompliance -case object Complies extends TypeCompliance -abstract class DoesntComply extends TypeCompliance -case class NonexistentType(name:String) extends DoesntComply -case class DoesntDescend(expected:String, given:String) extends DoesntComply +import vmlang.compiler.ast._ + +class TypeErrors(errors:List[CompilerError]) extends CompoundCompilerError(errors) -class TypeErrors(errors:List[TypeError]) extends CompoundCompilerError(errors) abstract class TypeError extends NormalCompilerError -class NonexistentTypeError(name:String) extends TypeError { - val repr = "type " + name + " doesn't exist" + +case class NonexistentType(name:String) extends TypeError { + val repr = "Nonexistent type: \"" + name + "\"" +} + +case class Mismatch(expected:TypeExpr, given:TypeExpr) extends TypeError { + val repr = "Type mismatch. Expected: " + expected.name + "; given: " + given.name } -class DoesntDescendError(expected:String, given:String) extends TypeError { - val repr = "given type " + given + " doesn't descend from expected type " + expected + +case class WrongNumTypeArgs(expected:Int, given:Int) extends TypeError { + val repr = "Wrong number of type arguments. Expected: " + expected + "; given: " + given +} + +case class WrongNumCallArgs(expected:Int, given:Int) extends TypeError { + val repr = "Wrong number of arguments. Expected: " + expected + "; given: " + given } diff --git a/src/vmlang/compiler/typecheck/Type.scala b/src/vmlang/compiler/typecheck/Type.scala index d73bd6c..278384c 100644 --- a/src/vmlang/compiler/typecheck/Type.scala +++ b/src/vmlang/compiler/typecheck/Type.scala @@ -1,18 +1,32 @@ package vmlang.compiler.typecheck import vmlang.compiler.ast._ abstract class Type -case object UnknownType extends Type -abstract class KnownType extends Type { +case class FuncType(paramTypes:List[TypeExpr], returnType:TypeExpr) extends Type { + override def toString = paramTypes.mkString("(",",",")") + " => " + returnType +} +abstract class ExprType extends Type { val name:String + val numParams:Int override def toString = name + def toTypeExpr = Parser.parseTypeExpr(toString) +} +case class AbsType(name:String, numParams:Int) extends ExprType +abstract class ConcreteType extends ExprType +case class RefType(name:String, numParams:Int) extends ConcreteType +case class PrimType(name:String) extends ConcreteType { + val numParams = 0 } -case class AbsType(name:String) extends KnownType -abstract class ConcreteType extends KnownType -case class RefType(name:String) extends ConcreteType -case class PrimType(name:String) extends ConcreteType -case class FuncType(paramTypes:List[TypeExpr], returnType:TypeExpr) { - override def toString = paramTypes.mkString("(",",",")") + " => " + returnType -} // TODO: make this part of the normal type hierarchy... +/* + +Type + [FuncType] + ExprType + [AbsType] + ConcreteType + [RefType] + [PrimType] + +*/ \ No newline at end of file diff --git a/src/vmlang/compiler/typecheck/TypeCheck.scala b/src/vmlang/compiler/typecheck/TypeCheck.scala index 257f717..e5f30a9 100644 --- a/src/vmlang/compiler/typecheck/TypeCheck.scala +++ b/src/vmlang/compiler/typecheck/TypeCheck.scala @@ -1,70 +1,92 @@ // package vmlang.compiler.typecheck // // import vmlang.compiler.ast._ // import collection.immutable.HashMap // +// // TODO: check expr tree for calls to nonexistent functions first +// // otherwise, maps and stuff are hard +// // object TypeCheck { // // val typeTree = TypeTree(AbsType("Value"),List( // TypeTree(AbsType("Eq"),List( // TypeTree(PrimType("Bool"),Nil), // TypeTree(PrimType("Null"),Nil), // TypeTree(AbsType("Ord"),List( // TypeTree(AbsType("Num"),List( // TypeTree(PrimType("Int"),Nil), // TypeTree(PrimType("Float"),Nil))), // TypeTree(PrimType("Char"),Nil))))))) // // type FuncTable = HashMap[String,FuncType] // // implicit def string2typeExpr(s:String) = Parser.parseTypeExpr(s).name // -// val funcTable = HashMap( -// "+" -> FuncType(List("Num","Num"),"Num"), -// "-" -> FuncType(List("Num","Num"),"Num"), -// "*" -> FuncType(List("Num","Num"),"Num"), -// "/" -> FuncType(List("Num","Num"),"Num"), -// "==" -> FuncType(List("Eq","Eq"),"Bool"), -// "!=" -> FuncType(List("Eq","Eq"),"Bool"), -// ">" -> FuncType(List("Ord","Ord"),"Bool"), -// ">=" -> FuncType(List("Ord","Ord"),"Bool"), -// "<" -> FuncType(List("Ord","Ord"),"Bool"), -// "<=" -> FuncType(List("Ord","Ord"),"Bool"), -// "true" -> FuncType(Nil,"Bool"), -// "false" -> FuncType(Nil,"Bool"), -// "null" -> FuncType(Nil,"Null"), -// "printChar" -> FuncType(List("Char"),"Null"), -// "getChar" -> FuncType(Nil,"Char") +// val rootFuncTypes = HashMap( +// "+" -> FuncType(List("Num","Num"),"Num"), +// "-" -> FuncType(List("Num","Num"),"Num"), +// "*" -> FuncType(List("Num","Num"),"Num"), +// "/" -> FuncType(List("Num","Num"),"Num"), +// "==" -> FuncType(List("Eq","Eq"),"Bool"), +// "!=" -> FuncType(List("Eq","Eq"),"Bool"), +// ">" -> FuncType(List("Ord","Ord"),"Bool"), +// ">=" -> FuncType(List("Ord","Ord"),"Bool"), +// "<" -> FuncType(List("Ord","Ord"),"Bool"), +// "<=" -> FuncType(List("Ord","Ord"),"Bool"), +// "true" -> FuncType(Nil,"Bool"), +// "false" -> FuncType(Nil,"Bool"), +// "null" -> FuncType(Nil,"Null"), +// "and" -> FuncType(List("Bool","Bool"),"Bool"), +// "or" -> FuncType(List("Bool","Bool"),"Bool"), +// "printChar" -> FuncType(List("Char"),"Null"), +// "getChar" -> FuncType(Nil,"Char"), +// "stackStart" -> FuncType(Nil,"Int") // ) // // def apply(prog:Prog):Prog = -// apply(prog, funcTable, typeTree) +// apply(prog, rootFuncTypes, typeTree) // -// def apply(prog:Prog, funcTypes:FuncTable, typeTree:TypeTree):Prog = -// checkCompliance(prog,addTypeSigs(prog,funcTypes),typeTree) +// def apply(prog:Prog, ft:FuncTable, tt:TypeTree):Prog = +// checkCompliance(prog, addTypeSigs(prog, ft), tt) // // private def addTypeSigs(p:Prog, ft:FuncTable):FuncTable = -// p.defs.foldLeft(ft){ (ft,d) => ft + (d.name -> FuncType(d.args,d.returnType)) } +// p.defs.foldLeft(ft){ (ft,d) => ft + (d.name -> FuncType(d.args, d.returnType)) } // // private def checkCompliance(p:Prog, ft:FuncTable, tt:TypeTree):Prog = -// (p.defs flatMap { checkDef(_,ft,tt) }) match { -// case Complies :: Nil => p -// case errors:List[DoesntComply] => throw new TypeErrors // ... +// (p.defs flatMap { checkDef(_, ft, tt) }) match { +// case Nil => p +// case l:List[CompilerError] => throw new TypeErrors(l) // } // -// private def checkDef(d:Def, ft:FuncTable, tt:TypeTree):List[TypeCompliance] = -// tt.complies(d.returnType,inferType(d.body)) // Type vs. TypeExpr ... +// private def checkDef(d:Def, ft:FuncTable, tt:TypeTree):List[CompilerError] = +// tt.complies(d.returnType, inferType(d.body)) // Type vs. TypeExpr ... // -// private def inferType(expr:Expr, funcTypes:FuncTable, typeTree:TypeTree):Type = -// expr match { -// case IntLit(_) => typeTree find "Int" -// case CharLit(_) => typeTree find "Char" -// case IfExpr(_,i,t) => typeTree.deepestCommonAncestor(inferType(i,funcTypes,typeTree), -// inferType(t,funcTypes,typeTree)) -// case Call(name,args) => funcTypes get name match { -// case Some(ft) => ft.returnType // TODO: check compliance of arguments - how to report all at once? -// case None => UnknownType +// def checkCall(call:Call, ft:FuncTable, tt:TypeTree):List[CompilerError] = { +// val giv = call.args +// ft.get(call.name) match { +// case Some(ft) => { +// val exp = ft.paramTypes +// if(exp.length == giv.length) Nil else List(WrongNumCallArgs(exp.length, giv.length)) ::: +// ((exp zip (giv map { inferType(_) })) map { p => tt.complies(p._1,p._2) }) // } +// case None => List(NonexistentFuncError(call.name)) // } +// } +// +// def inferType(expr:Expr, funcTypes:FuncTable, typeTree:TypeTree):TypeExpr = +// inferType(expr, Map(), funcTypes, typeTree) +// +// // TODO: check function scope when inferring call +// def inferType(expr:Expr, scope:Map[String,Type], ft:FuncTable, tt:TypeTree):TypeExpr = +// expr match { +// case IntLit(_) => tt find "Int" +// case CharLit(_) => tt find "Char" +// case IfExpr(_, i, t) => typeTree.deepestCommonAncestor(inferType(i, funcTypes, typeTree), +// inferType(t, funcTypes, typeTree)) +// case c:Call => if(isParam(c, scope)) scope(c.name) else ft(c.name).returnType +// } +// +// private def isParam(call:Call, scope:Map[String,Type]):Boolean = +// call.params.isEmpty && scope isDefinedAt call.name // // } diff --git a/src/vmlang/compiler/typecheck/TypeTree.scala b/src/vmlang/compiler/typecheck/TypeTree.scala index 2f7d31a..b2e3f9a 100644 --- a/src/vmlang/compiler/typecheck/TypeTree.scala +++ b/src/vmlang/compiler/typecheck/TypeTree.scala @@ -1,84 +1,107 @@ -// package vmlang.compiler.typecheck -// -// import vmlang.compiler.ast.TypeExpr -// -// case class TypeTree(t:KnownType, subTypes:List[TypeTree]) { -// -// def add(superTypeName:String, newType:KnownType):TypeTree = -// findTree(superTypeName) match { -// case Some(tree) => tree add newType -// case None => -// throw new NonexistentTypeError(superTypeName) -// } -// -// def add(newType:KnownType):TypeTree = TypeTree(t, TypeTree(newType,Nil) :: subTypes) -// -// def find(tn:String) = -// findTree(tn) match { -// case Some(tree) => tree.t -// case None => -// throw new NonexistentTypeError(tn) -// } -// -// private def findTree(tn:String):Option[TypeTree] = -// if (tn == t.name) -// Some(this) -// else if (isLeaf) -// None -// else -// subTypes.map(_ findTree tn).find(_.isInstanceOf[Some[TypeTree]]) match { -// case Some(tree) => tree -// case None => None -// } -// -// def complies(expected:TypeExpr, given:TypeExpr):List[TypeCompliance] = -// complies(this,expected,given) -// -// private def complies(topLevel:TypeTree, expected:TypeExpr, given:TypeExpr):List[TypeCompliance] = -// findTree(expected.name) match { -// case Some(expTree) => -// expTree.findTree(given.name) match { -// case Some(givTree) => List(Complies) -// case None => topLevel findTree given.name match { -// case Some(_) => List(DoesntDescend(expected.name,given.name)) -// case None => List(NonexistentType(given.name)) -// } -// } -// case None => List(NonexistentType(expected.name)) -// } -// -// def deepestCommonAncestor(a:Type, b:Type):Type = -// (a, b) match { -// case (a:KnownType, b:KnownType) => find(commonPath(a.name,b.name).last) -// case (_, _) => UnknownType -// } -// -// private def commonPath(a:String, b:String):List[String] = -// (path(a) zip path(b)) takeWhile { p => p._1 == p._2 } map { p => p._1 } -// -// private def path(tn:String):List[String] = -// path(List(),tn) match { -// case Some(l) => l -// case None => throw new NonexistentTypeError(tn) -// } -// -// private def path(path:List[String], tn:String):Option[List[String]] = -// if(tn == t.name) -// Some(path ::: List(tn)) -// else if(isLeaf) -// None -// else -// subTypes.map(_.path(path,tn)).find(_.isInstanceOf[Some[List[String]]]) match { -// case Some(Some(p)) => Some(path ::: List(t.name) ::: p) -// case None => None -// } -// -// def prettyPrint:String = prettyPrint(0).mkString -// -// def prettyPrint(indent:Int):List[Char] = -// (" " * indent).toList ::: t.name.toList ::: List('\n') ::: ( -// subTypes flatMap { _ prettyPrint (indent + 2) }) -// -// def isLeaf = subTypes.isEmpty -// -// } +package vmlang.compiler.typecheck + +import vmlang.compiler.ast.TypeExpr + +// could be more efficient: complies("Map[Num,Value]","TreeMap[Int,Float]") results in 44 calls to findTree + +case class TypeTree(t:ExprType, subTypes:List[TypeTree]) { + + def find(tn:String) = + findTree(tn) match { + case Some(tree) => tree.t + case None => + throw new NonexistentType(tn) + } + + private def findTree(tn:String):Option[TypeTree] = { + println(t.name + " findTree " + tn) + if (tn == t.name) + Some(this) + else if (isLeaf) + None + else + subTypes.map(_ findTree tn).find(_.isInstanceOf[Some[TypeTree]]) match { + case Some(tree) => tree + case None => None + } + } + + def complies(expected:TypeExpr, given:TypeExpr):List[TypeError] = + complies(this,expected,given) + + private def complies(topLevel:TypeTree, expected:TypeExpr, given:TypeExpr):List[TypeError] = + findTree(expected.name) match { + // expected type exists + case Some(expTree) => + expTree findTree given.name match { + // given type descends from expected type + case Some(givTree) => cmpTypeArgs(expected.args,expTree.t,given.args,givTree.t,topLevel) + // given type doesn't descend from expected type + case None => topLevel findTree given.name match { + // given type doesn't descend, but exists + case Some(givTree) => List(Mismatch(expected,given)) ::: + cmpTypeArgs(expected.args,expTree.t,given.args,givTree.t,topLevel) + // given type doesn't exist + case None => List(NonexistentType(given.name)) + } + } + // expected type doesn't exist + case None => List(NonexistentType(expected.name)) ::: (topLevel findTree given.name match { + // given type exists + case Some(givTree) => cmpNumTypeArgs(givTree.t, given.args) + // neither type exists + case None => List(NonexistentType(given.name)) + }) + } + + private def cmpTypeArgs(exp:List[TypeExpr], expType:ExprType, + giv:List[TypeExpr], givType:ExprType, + topLevel:TypeTree):List[TypeError] = + ((exp zip giv) flatMap { p => topLevel.complies(p._1, p._2) }) ::: + cmpNumTypeArgs(expType, exp) ::: cmpNumTypeArgs(givType, giv) ::: + checkExistent(exp, topLevel) ::: checkExistent(giv, topLevel) + + private def checkExistent(ts:List[TypeExpr], topLevel:TypeTree):List[TypeError] = + ts flatMap { t => topLevel findTree t.name match { + case Some(_) => Nil + case None => List(NonexistentType(t.name)) + } } + + private def cmpNumTypeArgs(t:ExprType, tas:List[TypeExpr]):List[TypeError] = + if(t.numParams == tas.length) + Nil + else + List(WrongNumTypeArgs(t.numParams, tas.length)) + + // def deepestCommonAncestor(a:TypeExpr, b:TypeExpr):TypeExpr = + // find(commonPath(a.name,b.name).last) + // + // private def commonPath(a:String, b:String):List[String] = + // (path(a) zip path(b)) takeWhile { p => p._1 == p._2 } map { p => p._1 } + // + // private def path(tn:String):List[String] = + // path(List(),tn) match { + // case Some(l) => l + // case None => throw new NonexistentType(tn) + // } + // + // private def path(path:List[String], tn:String):Option[List[String]] = + // if(tn == t.name) + // Some(path ::: List(tn)) + // else if(isLeaf) + // None + // else + // subTypes.map(_.path(path,tn)).find(_.isInstanceOf[Some[List[String]]]) match { + // case Some(Some(p)) => Some(path ::: List(t.name) ::: p) + // case None => None + // } + + def prettyPrint:String = prettyPrint(0).mkString + + def prettyPrint(indent:Int):List[Char] = + (" " * indent).toList ::: t.name.toList ::: List('\n') ::: ( + subTypes flatMap { _ prettyPrint (indent + 2) }) + + def isLeaf = subTypes.isEmpty + +}
vilterp/VMLang
20b846dcd0691ff1ba33257628c2cb0f3f73613d
extensible cmdline option parser. Okay, back to the actual compiler now
diff --git a/src/vmlang/common/Opcodes.java b/src/vmlang/common/Opcodes.java index aab0c7e..703bae2 100644 --- a/src/vmlang/common/Opcodes.java +++ b/src/vmlang/common/Opcodes.java @@ -1,47 +1,48 @@ package vmlang.common; public enum Opcodes { STOP, GOTO, GOTO_A, IF_EQ, IF_LT, I_CONST_A, I_CONST_B, B_CONST_A, B_CONST_B, I_LOAD_A_SP, I_LOAD_B_SP, I_LOAD_SP_SP, B_LOAD_A_SP, B_LOAD_B_SP, I_STORE_A_SP, B_STORE_A_SP, MOVE_COUNTER_A, MOVE_SP_A, MOVE_BP_A, MOVE_A_SP, MOVE_A_BP, I_ADD, I_SUB, I_MUL, I_DIV, I_MOD, INC_A, INC_B, INC_SP, DEC_A, DEC_B, DEC_SP, NEG_A, NEG_LT_A, AND, OR, PRINT_CHAR_A, - READ_CHAR_A; + READ_CHAR_A, + STACK_START; public byte toByte() { return (byte)ordinal(); } } diff --git a/src/vmlang/common/OptParse.scala b/src/vmlang/common/OptParse.scala deleted file mode 100644 index 94f975f..0000000 --- a/src/vmlang/common/OptParse.scala +++ /dev/null @@ -1,17 +0,0 @@ -package vmlang.common - -import collection.immutable.{Map, HashMap} - -case class Args(args:Seq[String], flags:Seq[String], opts:Map[String,String]) - -object OptParse { - - def apply(input:Array[String]):Args = { - val (dashStarts, args) = input partition { _ startsWith "-" } - val (optArgs, flags) = dashStarts partition { _ exists { _ == '=' } } - val opts = new HashMap[String,String] ++ - ((optArgs map { s => ((s substring 1) split '=') }) map { a => (a(0), a(1)) }) - Args(args,flags,opts) - } - -} \ No newline at end of file diff --git a/src/vmlang/common/OptParser.scala b/src/vmlang/common/OptParser.scala new file mode 100644 index 0000000..75bcdd7 --- /dev/null +++ b/src/vmlang/common/OptParser.scala @@ -0,0 +1,64 @@ +package vmlang.common + +import collection.immutable.HashMap + +abstract class OptParser { + + def numArgs(n:Int):Boolean + val argErrorMsg:String + val knownFlags:List[String] + val defaultOpts:Map[String,String] + val help:String + + def run(args:List[String], flags:List[String], opts:Map[String,String]):Unit + + def main(as:Array[String]) = { + val (args, flags, opts) = parse(as) + // check num args + if(!numArgs(args.length)) { + println(argErrorMsg) + println(help) + } else { + // check for unknown flags + flags -- knownFlags match { + case Nil => { + // check for unknown opts + opts.keySet.toList -- defaultOpts.keySet.toList match { + case Nil => { + // get opts + val allOpts = defaultOpts ++ opts + // run + try { + run(args, flags, allOpts) + } catch { + case FatalError(msg) => println(msg) + } + } + case l:List[String] => { + println("Unknown options: " + (l mkString ", ")) + println(help) + } + } + } + case l:List[String] => { + println("Unkown flags: " + (l mkString ", ")) + println(help) + } + } + } + } + + private def parse(as:Array[String]) = { + val (dashStarts, args) = as.toList partition { _ startsWith "-" } + val (optArgs, flags) = dashStarts partition { _ exists { _ == '=' } } + val opts = new HashMap[String,String] ++ + (optArgs map { a => { + val s = (a substring 1) split '='; + (s(0), s(1)) + } } ) + (args, flags, opts) + } + +} + +case class FatalError(msg:String) extends Exception diff --git a/src/vmlang/compiler/test.scala b/src/vmlang/compiler/test.scala index dd7e21f..34c77f9 100644 --- a/src/vmlang/compiler/test.scala +++ b/src/vmlang/compiler/test.scala @@ -1,41 +1,18 @@ package vmlang.compiler import vmlang.compiler.ast._ object Test extends UnitTest { - val tt = TypeTree(AbsType("Value"),List( - TypeTree(AbsType("Ord"),List( - TypeTree(AbsType("Num"),List( - TypeTree(PrimType("Int"),Nil), - TypeTree(PrimType("Float"),Nil))), - TypeTree(PrimType("Char"),Nil)) - ), - TypeTree(RefType("List"),Nil), - TypeTree(AbsType("Map"),List( - TypeTree(RefType("HashMap"),Nil))) - )) - - implicit def string2typeExpr(s:String) = Parser.parseTypeExpr(s) - - implicit def string2type(s:String) = tt find s - def main(args:Array[String]) = { - shouldBe(tt.complies("Value","Char"),List(Complies)) - shouldBe(tt.complies("Int","Int"),List(Complies)) - shouldBe(tt.complies("Int","Char"),List(DoesntDescend("Int","Char"))) - shouldBe(tt.complies("Int","Slartibartfast"),List(NonexistentType("Slartibartfast"))) - - shouldBe(tt.deepestCommonAncestor("Int","Int"),tt find "Int") - shouldBe(tt.deepestCommonAncestor("Int","Float"),tt find "Num") - shouldBe(tt.deepestCommonAncestor("Char","Int"),tt find "Ord") - shouldBe(tt.deepestCommonAncestor("Num","List"),tt find "Value") + shouldBe(2,2) } + } class UnitTest { def shouldBe(a:Any, b:Any) = if (a == b) println("pass") else println("fail. should be: " + b + "; found: " + a) } \ No newline at end of file diff --git a/src/vmlang/vm/InitError.java b/src/vmlang/vm/InitError.java new file mode 100644 index 0000000..02432c1 --- /dev/null +++ b/src/vmlang/vm/InitError.java @@ -0,0 +1,11 @@ +package vmlang.vm; + +public class InitError extends VMError { + + public String message; + + public InitError(String msg) { + message = msg; + } + +} \ No newline at end of file diff --git a/src/vmlang/vm/Main.scala b/src/vmlang/vm/Main.scala index 1c66a2b..b29dde1 100644 --- a/src/vmlang/vm/Main.scala +++ b/src/vmlang/vm/Main.scala @@ -1,102 +1,51 @@ package vmlang.vm import java.io.{File, FileInputStream, FileNotFoundException, IOException} -import vmlang.common.{OptParse, Args} -import collection.immutable.{Set, EmptySet} +import vmlang.common.{OptParser, FatalError} -object Main { +object Main extends OptParser { - // TODO: think up language name! + def numArgs(n:Int) = n == 1 + val argErrorMsg = "supply 1 executable file to run" + val knownFlags = List() + val defaultOpts = Map("heap_size" -> "1024", "stack_size" -> "1024") val help = "usage: *language name* <executable_file> <options>\n" + "-heap_size=<num bytes> heap size in bytes\n" + "-stack_size=<num bytes> stack size in bytes" - def main(as:Array[String]) = { + def run(args:List[String], flags:List[String], opts:Map[String,String]):Unit = { + val heapSize = try { + opts("heap_size").toInt + } catch { + case e:NumberFormatException => throw FatalError("Invalid heap size argument") + } + val stackSize = try { + opts("stack_size").toInt + } catch { + case e:NumberFormatException => throw FatalError("Invalid stack size argument") + } + // business time try { - val args = OptParse(as) - // check for extra arg pairs - args.opts.keySet.toList -- List("heap_size","stack_size") match { - case Nil => - case l:List[String] => { - println("Unrecognized options: " + (l mkString ", ")) - exit - } - } - // check for extra flags - args.flags match { - case s if s.isEmpty => - case s:Seq[String] => { - println("Unrecognized flags: " + (s mkString ", ")) - exit - } - } - // get file name - val fileName = args.args match { - case s if s.length == 1 => s.first - case _ => { - println("supply 1 file name") - exit - } - } - // get stack size - val stackSize = args.opts get "stack_size" match { - case Some(s) => try { s.toInt } catch { - case e:NumberFormatException => "not a valid stack size number" - exit - } - case None => 1024 - } - // get heap size - val heapSize = args.opts get "heap_size" match { - case Some(s) => try { s.toInt } catch { - case e:NumberFormatException => "not a valid heap size number" - println(help) - throw new FatalError - } - case None => 1024 - } - - // and, finally - try { - new VM(loadFileBytes(fileName),heapSize,stackSize).run() - } catch { - case e:StackOverflowError => { - println("VM Error: Stack Overflow") - throw new FatalError - } - case e:IllegalArgumentException => { - println("VM Error: " + e.getMessage) - throw new FatalError - } - } + new VM(loadFileBytes(args(0)), heapSize, stackSize).run } catch { - case e:FatalError => + case e:InitError => throw FatalError("Couldn't start VM: " + e.message) + case e:MalformedProgramError => throw FatalError("VM error: malformed program") + case e:StackOverflowError => throw FatalError("VM error: stack overflow") } } def loadFileBytes(fileName:String):Array[Byte] = { try { val in = new FileInputStream(new File(fileName)) val result = new Array[Byte](in.available) in.read(result) result } catch { - case e:FileNotFoundException => { - println("File not found: " + fileName) - throw new FatalError - } - case e:IOException => { - println("Error reading file " + fileName) - throw new FatalError - } + case e:FileNotFoundException => + throw FatalError("File not found: " + fileName) + case e:IOException => + throw FatalError("Error reading file " + fileName) } } - def exit = { - println(help) - throw new FatalError - } - } - -class FatalError extends Exception diff --git a/src/vmlang/vm/MalformedProgramError.java b/src/vmlang/vm/MalformedProgramError.java new file mode 100644 index 0000000..08b9cee --- /dev/null +++ b/src/vmlang/vm/MalformedProgramError.java @@ -0,0 +1,3 @@ +package vmlang.vm; + +public class MalformedProgramError extends VMError {} \ No newline at end of file diff --git a/src/vmlang/vm/StackOverflowError.java b/src/vmlang/vm/StackOverflowError.java index 26b31a2..65632df 100644 --- a/src/vmlang/vm/StackOverflowError.java +++ b/src/vmlang/vm/StackOverflowError.java @@ -1,3 +1,3 @@ package vmlang.vm; -public class StackOverflowError extends Exception {} \ No newline at end of file +public class StackOverflowError extends VMError {} \ No newline at end of file diff --git a/src/vmlang/vm/VM.java b/src/vmlang/vm/VM.java index dc7ea2e..7404f03 100644 --- a/src/vmlang/vm/VM.java +++ b/src/vmlang/vm/VM.java @@ -1,267 +1,272 @@ package vmlang.vm; import java.io.IOException; import java.io.PrintStream; import java.io.InputStream; import vmlang.common.Opcodes; public class VM { // registers private int A, B, SP, BP; private int counter; // memory private byte[] program; private byte[] memory; // io private InputStream in; private PrintStream out; private int stackStart; private static final Opcodes[] opcodes = Opcodes.values(); // inefficient? - public VM(byte[] prog, int heapSize, int stackSize) { - this(prog,heapSize,stackSize,System.in,System.out); + public VM(byte[] prog, int heapSize, int stackSize) throws InitError { + this(prog, heapSize, stackSize, System.in, System.out); } - public VM(byte[] prog, int stackSize, int heapSize, InputStream is, PrintStream os) { + public VM(byte[] prog, int heapSize, int stackSize, InputStream is, PrintStream os) + throws InitError { if(heapSize % 8 != 0) - throw new IllegalArgumentException("Heap size must be divisible by 8 (for malloc)"); + throw new InitError("Heap size must be divisible by 8 (for malloc)"); program = prog; memory = new byte[heapSize + stackSize]; stackStart = heapSize; in = is; out = os; } - public void run() throws StackOverflowError { + public void run() throws VMError { int nextAddr; while(true) { Opcodes opcode; try { opcode = opcodes[progReadByte()]; } catch(ArrayIndexOutOfBoundsException e) { throw getMalfProgEx(); } switch(opcode) { // FLOW CONTROL // basic case STOP: return; case GOTO: counter = progReadInt(); break; case GOTO_A: counter = A; break; // conditional jumps: based on post-SUB state of register A case IF_EQ: nextAddr = progReadInt(); if(A != 0) counter = nextAddr; break; case IF_LT: nextAddr = progReadInt(); if(A >= 0) counter = nextAddr; break; // LOAD & STORE (Von-Neumann bottleneck) // int constants case I_CONST_A: A = progReadInt(); break; case I_CONST_B: B = progReadInt(); break; // byte constants case B_CONST_A: A = progReadByte(); break; case B_CONST_B: B = progReadByte(); break; // load int case I_LOAD_A_SP: A = memReadInt(SP); break; case I_LOAD_B_SP: B = memReadInt(SP); break; case I_LOAD_SP_SP: SP = memReadInt(SP); break; // load byte case B_LOAD_A_SP: A = memReadByte(SP); break; case B_LOAD_B_SP: B = memReadByte(SP); break; // store int case I_STORE_A_SP: memWriteInt(SP,A); break; // store byte case B_STORE_A_SP: memWriteByte(SP,(byte)A); break; // moves case MOVE_COUNTER_A: A = counter; break; case MOVE_SP_A: A = SP; break; case MOVE_BP_A: A = BP; break; case MOVE_A_SP: SP = A; break; case MOVE_A_BP: BP = A; break; // REGISTER OPERATIONS // arithmetic case I_ADD: A = A + B; break; case I_SUB: A = A - B; break; case I_MUL: A = A * B; break; case I_DIV: A = A / B; break; case I_MOD: A = A * B; break; case INC_A: A++; break; // inc/dec case INC_B: B++; break; case INC_SP: SP++; break; case DEC_A: A--; break; case DEC_B: B--; break; case DEC_SP: SP--; break; // logic (0: false; non-0: true) case NEG_A: if(A == 0) A = 1; else A = 0; break; case NEG_LT_A: if(A < 0) A = 1; else A = 0; case AND: if(A != 0 && B != 0) A = 1; else A = 0; break; case OR: if(A != 0 || B != 0) A = 1; else A = 0; break; - + + case STACK_START: + A = stackStart; + break; + // io case PRINT_CHAR_A: out.print((char)A); break; case READ_CHAR_A: try { A = in.read(); } catch(IOException e) { out.println(e.getMessage()); } break; } } } // PROGRAM READERS - private byte progReadByte() { + private byte progReadByte() throws MalformedProgramError { byte result; try { result = program[counter]; } catch(ArrayIndexOutOfBoundsException e) { throw getMalfProgEx(); } counter++; return result; } - private int progReadInt() { + private int progReadInt() throws MalformedProgramError { return ((progReadByte() & 0xff) << 24) | ((progReadByte() & 0xff) << 16) | ((progReadByte() & 0xff) << 8) | (progReadByte() & 0xff); } // MEMORY READERS & WRITERS private byte memReadByte(int addr) throws StackOverflowError { try { return memory[addr]; } catch(ArrayIndexOutOfBoundsException e) { throw new StackOverflowError(); } } private int memReadInt(int addr) throws StackOverflowError { return ((memReadByte(addr) & 0xff) << 24) | ((memReadByte(addr+1) & 0xff) << 16) | ((memReadByte(addr+2) & 0xff) << 8) | (memReadByte(addr+3) & 0xff); } private void memWriteByte(int addr, byte val) throws StackOverflowError { try { memory[addr] = val; } catch(ArrayIndexOutOfBoundsException e) { throw new StackOverflowError(); } } private void memWriteInt(int addr, int val) throws StackOverflowError { memWriteByte(addr ,(byte)(0xff & (val >> 24))); memWriteByte(addr+1,(byte)(0xff & (val >> 16))); memWriteByte(addr+2,(byte)(0xff & (val >> 8))); memWriteByte(addr+3,(byte)(0xff & val)); } - private IllegalArgumentException getMalfProgEx() { - return new IllegalArgumentException("Malformed program"); + private MalformedProgramError getMalfProgEx() { + return new MalformedProgramError(); } } \ No newline at end of file diff --git a/src/vmlang/vm/VMError.java b/src/vmlang/vm/VMError.java new file mode 100644 index 0000000..bed509b --- /dev/null +++ b/src/vmlang/vm/VMError.java @@ -0,0 +1,3 @@ +package vmlang.vm; + +public abstract class VMError extends Exception {} \ No newline at end of file
vilterp/VMLang
02b4b75cb9f680e0cb9aac255b2d83cb21a80214
started working on new parser, tweaked VM, rewrote main
diff --git a/.classpath b/.classpath deleted file mode 100644 index 97c403d..0000000 --- a/.classpath +++ /dev/null @@ -1,7 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<classpath> - <classpathentry kind="src" path="src"/> - <classpathentry kind="con" path="ch.epfl.lamp.sdt.launching.SCALA_CONTAINER"/> - <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/> - <classpathentry kind="output" path="bin"/> -</classpath> diff --git a/.gitignore b/.gitignore index babd423..19eaa85 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,7 @@ .DS_Store bin/* vmlang_log.txt .settings/* .manager/* +.classpath + diff --git a/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_common_$_Opcodes.java b/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_common_$_Opcodes.java deleted file mode 100644 index d30ea89..0000000 Binary files a/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_common_$_Opcodes.java and /dev/null differ diff --git a/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_common_$_OptParser.scala b/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_common_$_OptParser.scala deleted file mode 100644 index 24f031d..0000000 Binary files a/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_common_$_OptParser.scala and /dev/null differ diff --git a/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_compiler_$_ast_$_AST.scala b/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_compiler_$_ast_$_AST.scala deleted file mode 100644 index 71e3294..0000000 Binary files a/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_compiler_$_ast_$_AST.scala and /dev/null differ diff --git a/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_compiler_$_ast_$_Parser.scala b/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_compiler_$_ast_$_Parser.scala deleted file mode 100644 index 940e4aa..0000000 Binary files a/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_compiler_$_ast_$_Parser.scala and /dev/null differ diff --git a/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_compiler_$_test.scala b/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_compiler_$_test.scala deleted file mode 100644 index 3101cde..0000000 Binary files a/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_compiler_$_test.scala and /dev/null differ diff --git a/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_vm_$_Main.java b/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_vm_$_Main.java deleted file mode 100644 index d30ea89..0000000 Binary files a/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_vm_$_Main.java and /dev/null differ diff --git a/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_vm_$_Main.scala b/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_vm_$_Main.scala deleted file mode 100644 index bb33646..0000000 Binary files a/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_vm_$_Main.scala and /dev/null differ diff --git a/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_vm_$_VM.java b/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_vm_$_VM.java deleted file mode 100644 index d30ea89..0000000 Binary files a/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_vm_$_VM.java and /dev/null differ diff --git a/.project b/.project deleted file mode 100644 index 77f32c4..0000000 --- a/.project +++ /dev/null @@ -1,18 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<projectDescription> - <name>VMLang</name> - <comment></comment> - <projects> - </projects> - <buildSpec> - <buildCommand> - <name>ch.epfl.lamp.sdt.core.scalabuilder</name> - <arguments> - </arguments> - </buildCommand> - </buildSpec> - <natures> - <nature>ch.epfl.lamp.sdt.core.scalanature</nature> - <nature>org.eclipse.jdt.core.javanature</nature> - </natures> -</projectDescription> diff --git a/.settings/ch.epfl.lamp.sdt.core.prefs b/.settings/ch.epfl.lamp.sdt.core.prefs deleted file mode 100644 index 6af18c1..0000000 --- a/.settings/ch.epfl.lamp.sdt.core.prefs +++ /dev/null @@ -1,25 +0,0 @@ -#Fri Nov 27 12:18:33 EST 2009 -<file>=false -Xcheck-null=false -Xcheckinit=false -Xdisable-assertions=false -Xexperimental=false -Xfuture=false -Xlog-implicits=false -Xno-uescape=false -Xno-varargs-conversion=false -Yclosure-elim=false -Ydead-code=false -Ydetach=false -Yinline=false -Ylinearizer=rpo -Yno-generic-signatures=false -Yno-imports=false -Yno-predefs=false -Yself-in-annots=false -Ywarn-dead-code=false -eclipse.preferences.version=1 -g=vars -optimise=false -scala.compiler.useProjectSettings=false -target=jvm-1.5 diff --git a/.settings/org.eclipse.jdt.core.prefs b/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index e6bab3a..0000000 --- a/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,4 +0,0 @@ -#Sun Nov 22 13:54:06 EST 2009 -eclipse.preferences.version=1 -org.eclipse.jdt.core.builder.cleanOutputFolder=ignore -org.eclipse.jdt.core.builder.resourceCopyExclusionFilter=*.scala diff --git a/.settings/org.eclipse.ltk.core.refactoring.prefs b/.settings/org.eclipse.ltk.core.refactoring.prefs deleted file mode 100644 index bb1620d..0000000 --- a/.settings/org.eclipse.ltk.core.refactoring.prefs +++ /dev/null @@ -1,3 +0,0 @@ -#Sun Nov 22 13:54:05 EST 2009 -eclipse.preferences.version=1 -org.eclipse.ltk.core.refactoring.enable.project.refactoring.history=false diff --git a/src/vmlang/common/OptParse.scala b/src/vmlang/common/OptParse.scala new file mode 100644 index 0000000..94f975f --- /dev/null +++ b/src/vmlang/common/OptParse.scala @@ -0,0 +1,17 @@ +package vmlang.common + +import collection.immutable.{Map, HashMap} + +case class Args(args:Seq[String], flags:Seq[String], opts:Map[String,String]) + +object OptParse { + + def apply(input:Array[String]):Args = { + val (dashStarts, args) = input partition { _ startsWith "-" } + val (optArgs, flags) = dashStarts partition { _ exists { _ == '=' } } + val opts = new HashMap[String,String] ++ + ((optArgs map { s => ((s substring 1) split '=') }) map { a => (a(0), a(1)) }) + Args(args,flags,opts) + } + +} \ No newline at end of file diff --git a/src/vmlang/compiler/Simplifier.scala b/src/vmlang/compiler/Simplifier.scala index 7303842..d8aa757 100644 --- a/src/vmlang/compiler/Simplifier.scala +++ b/src/vmlang/compiler/Simplifier.scala @@ -1,18 +1,30 @@ -package vmlang.compiler - -import vmlang.compiler.ast._ -import collection.immutable.HashSet - -object Simplifier { - - val ops = HashSet("+","-","*","/",">","<",">=","<=","==","and","or","!") - - def apply(prog:Prog) = Prog(prog.defs map { case Def(n,a,r,body) => Def(n,a,r,simplify(body)) }) - - def simplify(e:Expr):Expr = e match { - case a:Atom => a - case IfExpr(c,i,e) => IfExpr(simplify(c),simplify(i),simplify(e)) - case Call(n,args) => if (ops contains n) simplify(Call(n,args map simplify)) else Call(n,args map simplify) - } - -} +// package vmlang.compiler +// +// import vmlang.compiler.ast._ +// import collection.immutable.HashSet +// +// object Simplifier { +// +// def apply(prog:Prog) = Prog(prog.defs map { case Def(n,a,r,body) => Def(n,a,r,simplify(body)) }) +// +// def simplify(e:Expr):Expr = e match { +// case a:Atom => a +// case IfExpr(c,i,e) => (simplify(c), simplify(i), simplify(e)) match { +// case (Call("true",Nil), i, e) => i +// case (Call("false",Nil), i, e) => i +// case (c, i, e) => IfExpr(c, i, e) +// } +// case Call(n,args) => (n, args map simplify) match { +// case ("+" , List(Integer(a),Integer(b))) => Integer(a + b) +// case ("-" , List(Integer(a),Integer(b))) => Integer(a - b) +// case ("*" , List(Integer(a),Integer(b))) => Integer(a * b) +// case ("/" , List(Integer(a),Integer(b))) => Integer(a / b) +// case (">" , List(Integer(a),Integer(b))) => Integer(a b) +// case (">=", List(Integer(a),Integer(b))) => Integer(a + b) +// case ("<" , List(Integer(a),Integer(b))) => Integer(a + b) +// case ("<=", List(Integer(a),Integer(b))) => Integer(a + b) +// case ("==", List(Integer(a),Integer(b))) => Integer(a + b) +// } +// } +// +// } diff --git a/src/vmlang/compiler/ast/AST.scala b/src/vmlang/compiler/ast/AST.scala index 30a246c..ed07c2a 100644 --- a/src/vmlang/compiler/ast/AST.scala +++ b/src/vmlang/compiler/ast/AST.scala @@ -1,21 +1,21 @@ package vmlang.compiler.ast abstract class ASTNode case class Prog(defs:List[Def]) extends ASTNode -case class Def(name:String, args:List[ArgSpec], - returnType:Option[TypeExpr], body:Expr) extends ASTNode +case class Def(name:String, args:List[ArgSpec], returnType:TypeExpr, body:Expr) extends ASTNode case class ArgSpec(name:String, argType:TypeExpr) extends ASTNode case class TypeExpr(name:String) extends ASTNode abstract class Expr extends ASTNode case class IfExpr(condition:Expr, ifExpr:Expr, thenExpr:Expr) extends Expr case class Call(name:String, args:List[Expr]) extends Expr abstract class Atom extends Expr -case class IntLit(value:BigInt) extends Atom +case class IntLit(value:Int) extends Atom +case class FloatLit(value:Float) extends Atom case class CharLit(value:Char) extends Atom case object EmptyList extends Atom diff --git a/src/vmlang/compiler/ast/NewParser.scala b/src/vmlang/compiler/ast/NewParser.scala new file mode 100644 index 0000000..877c9b4 --- /dev/null +++ b/src/vmlang/compiler/ast/NewParser.scala @@ -0,0 +1,97 @@ +import scala.util.parsing.combinator._ +import scala.util.parsing.input._ + +// Bug: CharSequenceReader eliminates spaces in strings ("hello there" => StringLit(hellothere)) + +object Test extends RegexParsers { + + def apply(input:String) = + doRule(expr,input) match { + case Success(t, _) => t + case e: NoSuccess => throw new IllegalArgumentException(e.toString) + } + + def doRule(rule:Parser[Any], input:String) = phrase(rule)(new CharSequenceReader(input)) + + def expr = ( float | int | variable | string | char ) + + def float = regex("""-?(\d+\.\d+|\.\d+)""".r) ~ (sciNot?) ^^ { + case f ~ Some(s) => FloatLit(checkFloatSize(f,s)) + case f ~ None => FloatLit(checkFloatSize(f,0)) } + + def int = regex("""-?\d+""".r) ~ (sciNot?) ^^ { + case i ~ Some(s) => IntLit(checkIntSize(i,s)) + case i ~ None => IntLit(checkIntSize(i,0)) } + + def checkIntSize(v:String, e:Int):Int = { + val bi = BigInt(v) * (BigInt(10) pow e) + if(bi > Math.MAX_INT) + throw new IllegalArgumentException("int literal too big") + else if(bi < Math.MIN_INT) + throw new IllegalArgumentException("int literal too small") + else + bi.intValue + } + + def checkFloatSize(v:String, e:Int):Float = { + val bd = BigDecimal(v) * new BigDecimal(new java.math.BigDecimal(10) pow e) + if(bd > BigDecimal(Math.MAX_FLOAT)) + throw new IllegalArgumentException("float literal too big") + else if(bd < BigDecimal(Math.MIN_FLOAT)) + throw new IllegalArgumentException("float literal too small") + else + bd.floatValue + } + + def sciNot = regex("""[eE]-?\d+""".r) ^^ { + try { + i => i.substring(1).toInt + } catch { + case c:NumberFormatException => throw new IllegalArgumentException("exponent too big") + } } + + def string = "\"" ~> (stringChar*) <~ "\"" ^^ { l => StringLit(l.mkString) } // should actually map to list of char... + + def stringChar = ( unicodeChar | escapedCharInStr | normalCharInStr ) + + def char = "'" ~> ( unicodeChar | escapedCharInChar | normalCharInChar ) <~ "'" ^^ { c => CharLit(c) } + + def normalCharInChar = regex("""[ -&\(-~]""".r) ^^ { s => s charAt 0 } + + def escapedCharInChar = regex("""\\[nt']""".r) ^^ { case "\\n" => '\n' + case "\\t" => '\t' + case "\\'" => '\'' } + + def normalCharInStr = regex("""[ -!#-~]""".r) ^^ { s => s charAt 0 } + + def escapedCharInStr = regex("""\\[nt\"]""".r) ^^ { case "\\n" => '\n' + case "\\t" => '\t' + case "\\\"" => '"' } + + def unicodeChar = regex("""\\u[0-9a-f]{1,4}""".r) ^^ { s => Integer.parseInt(s substring 2,16).toChar } + + def variable = regex("""[a-zA-Z_]\w*""".r) ^^ { i => Var(i) } + + def main(args:Array[String]) = { + List("123","-123","123.1234","123e4","hello","hello_o","HelloYo","_yo", + "64654654654654645564654456564654654654654","5e65465465465465465","-.123","000.3","8e4","Infinity", + "'a'","'!'","'\\n'","'\\u61'","'\\''", + "\"Sup?\"","\"hey\\nthere\"","\"'that is cool'\"","\"\\\"\"") foreach test + } + + def test(input:String) = println(input + " => " + { + try { + apply(input) + } catch { + case e: IllegalArgumentException => "error: " + e.getMessage + } + }) + +} + +abstract class Atom +case class CharLit(value:Char) extends Atom +case class FloatLit(value:Float) extends Atom +case class IntLit(value:Int) extends Atom +case class StringLit(value:String) extends Atom +case class Var(name:String) extends Atom diff --git a/src/vmlang/compiler/ast/Parser.scala b/src/vmlang/compiler/ast/Parser.scala index 362c2b6..f50494b 100644 --- a/src/vmlang/compiler/ast/Parser.scala +++ b/src/vmlang/compiler/ast/Parser.scala @@ -1,102 +1,102 @@ package vmlang.compiler.ast import scala.runtime.RichString import scala.util.parsing.combinator.syntactical._ class ParserError(msg:String) extends NormalCompilerError { val repr = "Parser Error: " + msg } object Parser extends StandardTokenParsers { lexical.delimiters ++= List("+","-","*","/","(",")","[","]","=",":",",",">","<", ">=","<=","==","!","!=") lexical.reserved ++= List("if","then","else","and","or") // RULES def program = (definition *) ^^ { l => Prog(l) } - def definition = ident ~ (argsSpec?) ~ (typeSpec?) ~ ("=" ~> expr) ^^ { + def definition = ident ~ (argsSpec?) ~ typeSpec ~ ("=" ~> expr) ^^ { case i ~ Some(as) ~ rt ~ e => Def(i,as,rt,e) case i ~ None ~ rt ~ e => Def(i,Nil,rt,e) } def argsSpec = "(" ~> repsep(argSpec, ",") <~ ")" def argSpec = ident ~ typeSpec ^^ { case i ~ t => ArgSpec(i,t) } def typeSpec = ":" ~> typeExpr def typeExpr:Parser[TypeExpr] = ident ^^ { i => TypeExpr(i) } def typeParams = "[" ~> repsep(typeExpr,",") <~ "]" def expr:Parser[Expr] = ( ifStatement | orExpr ) def ifStatement = (("if" ~> orExpr) ~ ("then" ~> orExpr) ~ ("else" ~> orExpr)) ^^ { case c ~ i ~ e => IfExpr(c,i,e) } def orExpr = andExpr * ( "or" ^^^ { (a:Expr, b:Expr) => Call("or",List(a,b)) } ) def andExpr = comparison * ( "and" ^^^ { (a:Expr, b:Expr) => Call("and",List(a,b)) } ) def comparison = sum * ( ">" ^^^ { (a:Expr, b:Expr) => Call(">",List(a,b)) } | "<" ^^^ { (a:Expr, b:Expr) => Call("<",List(a,b)) } | "==" ^^^ { (a:Expr, b:Expr) => Call("==",List(a,b)) } | "<=" ^^^ { (a:Expr, b:Expr) => Call("<=",List(a,b)) } | ">=" ^^^ { (a:Expr, b:Expr) => Call(">=",List(a,b)) } | - "!=" ^^^ { (a:Expr, b:Expr) => Call("!",List(a,b)) } ) + "!=" ^^^ { (a:Expr, b:Expr) => Call("!=",List(a,b)) } ) // I'm sure there's a super-elegant way to do this, // but my Scala chops aren't up to it yet def sum = product * ( "+" ^^^ { (a:Expr, b:Expr) => Call("+",List(a,b)) } | "-" ^^^ { (a:Expr, b:Expr) => Call("-",List(a,b)) } ) def product = atom * ( "*" ^^^ { (a:Expr, b:Expr) => Call("*",List(a,b)) } | "/" ^^^ { (a:Expr, b:Expr) => Call("/",List(a,b)) } ) - def atom = ( number | list | string | call | parenthesizedExpr | unaryMinus | unaryNot ) + def atom = ( int | list | string | call | parenthesizedExpr | unaryMinus | unaryNot ) // todo: char lit (not in standardtokenparsers...) def list = "[" ~> repsep(expr,",") <~ "]" ^^ concatIze def string = stringLit ^^ { (s:String) => concatIze(new RichString(s) map { CharLit(_) }) } def concatIze(items:Seq[Expr]):Expr = items.foldRight(EmptyList.asInstanceOf[Expr]){ (i,a) => Call(":",List(i,a)) } def parenthesizedExpr = "(" ~> expr <~ ")" def unaryNot:Parser[Expr] = "!" ~> atom ^^ { a => Call("!",List(a)) } - def unaryMinus:Parser[Expr] = "-" ~> atom ^^ { a => Call("*",List(a,IntLit(BigInt(-1)))) } + def unaryMinus:Parser[Expr] = "-" ~> atom ^^ { a => Call("*",List(a,IntLit(-1))) } - def number = numericLit ^^ { s => IntLit(BigInt(s)) } + def int = numericLit ^^ { s => IntLit(s.toInt) } def call = ident ~ (args ?) ^^ { case i ~ Some(a) => Call(i,a) case i ~ None => Call(i,List()) } def args = "(" ~> repsep(expr,",") <~ ")" // END OF RULES def parse(s:String) = phrase(program)(new lexical.Scanner(s)) def parseTypeExpr(t:String) = phrase(typeExpr)(new lexical.Scanner(t)) match { case Success(t, _) => t case e: NoSuccess => throw new IllegalArgumentException(e.toString) } def apply(s:String) = { parse(s) match { case Success(tree, _) => tree case e: NoSuccess => throw new ParserError(e.toString) } } } diff --git a/src/vmlang/compiler/typecheck/Compliance.scala b/src/vmlang/compiler/typecheck/Compliance.scala index 63e58a1..0cf6007 100644 --- a/src/vmlang/compiler/typecheck/Compliance.scala +++ b/src/vmlang/compiler/typecheck/Compliance.scala @@ -1,16 +1,16 @@ package vmlang.compiler.typecheck abstract class TypeCompliance case object Complies extends TypeCompliance abstract class DoesntComply extends TypeCompliance case class NonexistentType(name:String) extends DoesntComply case class DoesntDescend(expected:String, given:String) extends DoesntComply class TypeErrors(errors:List[TypeError]) extends CompoundCompilerError(errors) abstract class TypeError extends NormalCompilerError class NonexistentTypeError(name:String) extends TypeError { - def repr = "type " + name + " doesn't exist" + val repr = "type " + name + " doesn't exist" } class DoesntDescendError(expected:String, given:String) extends TypeError { - def repr = "given type " + given + " doesn't descend from expected type " + expected + val repr = "given type " + given + " doesn't descend from expected type " + expected } diff --git a/src/vmlang/compiler/typecheck/Type.scala b/src/vmlang/compiler/typecheck/Type.scala index 75c74fe..d73bd6c 100644 --- a/src/vmlang/compiler/typecheck/Type.scala +++ b/src/vmlang/compiler/typecheck/Type.scala @@ -1,17 +1,18 @@ package vmlang.compiler.typecheck +import vmlang.compiler.ast._ + abstract class Type case object UnknownType extends Type abstract class KnownType extends Type { val name:String override def toString = name } case class AbsType(name:String) extends KnownType abstract class ConcreteType extends KnownType case class RefType(name:String) extends ConcreteType case class PrimType(name:String) extends ConcreteType -case class FuncType(paramTypes:List[Type], returnType:Type) { +case class FuncType(paramTypes:List[TypeExpr], returnType:TypeExpr) { override def toString = paramTypes.mkString("(",",",")") + " => " + returnType -} - // TODO: make this part of the normal type hierarchy... +} // TODO: make this part of the normal type hierarchy... diff --git a/src/vmlang/compiler/typecheck/TypeCheck.scala b/src/vmlang/compiler/typecheck/TypeCheck.scala index b03ff7c..257f717 100644 --- a/src/vmlang/compiler/typecheck/TypeCheck.scala +++ b/src/vmlang/compiler/typecheck/TypeCheck.scala @@ -1,32 +1,70 @@ -package vmlang.compiler.typecheck - -import vmlang.compiler.ast._ -import collection.immutable.Map - -object TypeCheck { - - type FuncTable = Map[String,FuncType] - - val typeTree = TypeTree(AbsType("Value"),List( - TypeTree(AbsType("Ord"),List( - TypeTree(AbsType("Num"),List( - TypeTree(PrimType("Int"),Nil), - TypeTree(PrimType("Float"),Nil))), - TypeTree(PrimType("Char"),Nil))))) - - // def apply(prog:Prog, funcTypes:Map[String,FuncType], typeTree:TypeTree) = - // - // def checkFunc(func:Def, funcTypes:Map[String,FuncType], typeTree:TypeTree) = - - def inferType(expr:Expr, funcTypes:FuncTable, typeTree:TypeTree):Type = expr match { - case IntLit(_) => typeTree find "Int" - case CharLit(_) => typeTree find "Char" - case IfExpr(_,i,t) => typeTree.deepestCommonAncestor(inferType(i,funcTypes,typeTree), - inferType(t,funcTypes,typeTree)) - case Call(name,args) => funcTypes get name match { - case Some(ft) => ft.returnType - case None => UnknownType - } - } - -} \ No newline at end of file +// package vmlang.compiler.typecheck +// +// import vmlang.compiler.ast._ +// import collection.immutable.HashMap +// +// object TypeCheck { +// +// val typeTree = TypeTree(AbsType("Value"),List( +// TypeTree(AbsType("Eq"),List( +// TypeTree(PrimType("Bool"),Nil), +// TypeTree(PrimType("Null"),Nil), +// TypeTree(AbsType("Ord"),List( +// TypeTree(AbsType("Num"),List( +// TypeTree(PrimType("Int"),Nil), +// TypeTree(PrimType("Float"),Nil))), +// TypeTree(PrimType("Char"),Nil))))))) +// +// type FuncTable = HashMap[String,FuncType] +// +// implicit def string2typeExpr(s:String) = Parser.parseTypeExpr(s).name +// +// val funcTable = HashMap( +// "+" -> FuncType(List("Num","Num"),"Num"), +// "-" -> FuncType(List("Num","Num"),"Num"), +// "*" -> FuncType(List("Num","Num"),"Num"), +// "/" -> FuncType(List("Num","Num"),"Num"), +// "==" -> FuncType(List("Eq","Eq"),"Bool"), +// "!=" -> FuncType(List("Eq","Eq"),"Bool"), +// ">" -> FuncType(List("Ord","Ord"),"Bool"), +// ">=" -> FuncType(List("Ord","Ord"),"Bool"), +// "<" -> FuncType(List("Ord","Ord"),"Bool"), +// "<=" -> FuncType(List("Ord","Ord"),"Bool"), +// "true" -> FuncType(Nil,"Bool"), +// "false" -> FuncType(Nil,"Bool"), +// "null" -> FuncType(Nil,"Null"), +// "printChar" -> FuncType(List("Char"),"Null"), +// "getChar" -> FuncType(Nil,"Char") +// ) +// +// def apply(prog:Prog):Prog = +// apply(prog, funcTable, typeTree) +// +// def apply(prog:Prog, funcTypes:FuncTable, typeTree:TypeTree):Prog = +// checkCompliance(prog,addTypeSigs(prog,funcTypes),typeTree) +// +// private def addTypeSigs(p:Prog, ft:FuncTable):FuncTable = +// p.defs.foldLeft(ft){ (ft,d) => ft + (d.name -> FuncType(d.args,d.returnType)) } +// +// private def checkCompliance(p:Prog, ft:FuncTable, tt:TypeTree):Prog = +// (p.defs flatMap { checkDef(_,ft,tt) }) match { +// case Complies :: Nil => p +// case errors:List[DoesntComply] => throw new TypeErrors // ... +// } +// +// private def checkDef(d:Def, ft:FuncTable, tt:TypeTree):List[TypeCompliance] = +// tt.complies(d.returnType,inferType(d.body)) // Type vs. TypeExpr ... +// +// private def inferType(expr:Expr, funcTypes:FuncTable, typeTree:TypeTree):Type = +// expr match { +// case IntLit(_) => typeTree find "Int" +// case CharLit(_) => typeTree find "Char" +// case IfExpr(_,i,t) => typeTree.deepestCommonAncestor(inferType(i,funcTypes,typeTree), +// inferType(t,funcTypes,typeTree)) +// case Call(name,args) => funcTypes get name match { +// case Some(ft) => ft.returnType // TODO: check compliance of arguments - how to report all at once? +// case None => UnknownType +// } +// } +// +// } diff --git a/src/vmlang/compiler/typecheck/TypeTree.scala b/src/vmlang/compiler/typecheck/TypeTree.scala index 6a9327b..2f7d31a 100644 --- a/src/vmlang/compiler/typecheck/TypeTree.scala +++ b/src/vmlang/compiler/typecheck/TypeTree.scala @@ -1,80 +1,84 @@ -package vmlang.compiler.typecheck - -import vmlang.compiler.ast.TypeExpr - -case class TypeTree(t:KnownType, subTypes:List[TypeTree]) { - - def add(superTypeName:String, newType:KnownType):TypeTree = findTree(superTypeName) match { - case Some(tree) => tree add newType - case None => - throw new NonexistentTypeError(superTypeName) - } - - def add(newType:KnownType):TypeTree = TypeTree(t, TypeTree(newType,Nil) :: subTypes) - - def find(tn:String) = findTree(tn) match { - case Some(tree) => tree.t - case None => - throw new NonexistentTypeError(tn) - } - - private def findTree(tn:String):Option[TypeTree] = { - if (tn == t.name) - Some(this) - else if (isLeaf) - None - else - subTypes.map(_ findTree tn).find(_.isInstanceOf[Some[TypeTree]]) match { - case Some(tree) => tree - case None => None - } - } - - def complies(expected:TypeExpr, given:TypeExpr):List[TypeCompliance] = complies(this,expected,given) - - private def complies(topLevel:TypeTree, expected:TypeExpr, given:TypeExpr):List[TypeCompliance] = - findTree(expected.name) match { - case Some(expTree) => - expTree.findTree(given.name) match { - case Some(givTree) => List(Complies) - case None => topLevel findTree given.name match { - case Some(_) => List(DoesntDescend(expected.name,given.name)) - case None => List(NonexistentType(given.name)) - } - } - case None => List(NonexistentType(expected.name)) - } - - def deepestCommonAncestor(a:Type, b:Type):Type = (a, b) match { - case (a:KnownType, b:KnownType) => find(commonPath(a.name,b.name).last) - case (_, _) => UnknownType - } - - private def commonPath(a:String, b:String):List[String] = - (path(a) zip path(b)) takeWhile { p => p._1 == p._2 } map { p => p._1 } - - private def path(tn:String):List[String] = path(List(),tn) match { - case Some(l) => l - case None => throw new NonexistentTypeError(tn) - } - - private def path(path:List[String], tn:String):Option[List[String]] = - if(tn == t.name) - Some(path ::: List(tn)) - else if(isLeaf) - None - else - subTypes.map(_.path(path,tn)).find(_.isInstanceOf[Some[List[String]]]) match { - case Some(Some(p)) => Some(path ::: List(t.name) ::: p) - case None => None - } - - def prettyPrint:String = prettyPrint(0).mkString - - def prettyPrint(indent:Int):List[Char] = - (" " * indent).toList ::: t.name.toList ::: List('\n') ::: ( - subTypes flatMap { _ prettyPrint (indent + 2) }) - - def isLeaf = subTypes.isEmpty - -} +// package vmlang.compiler.typecheck +// +// import vmlang.compiler.ast.TypeExpr +// +// case class TypeTree(t:KnownType, subTypes:List[TypeTree]) { +// +// def add(superTypeName:String, newType:KnownType):TypeTree = +// findTree(superTypeName) match { +// case Some(tree) => tree add newType +// case None => +// throw new NonexistentTypeError(superTypeName) +// } +// +// def add(newType:KnownType):TypeTree = TypeTree(t, TypeTree(newType,Nil) :: subTypes) +// +// def find(tn:String) = +// findTree(tn) match { +// case Some(tree) => tree.t +// case None => +// throw new NonexistentTypeError(tn) +// } +// +// private def findTree(tn:String):Option[TypeTree] = +// if (tn == t.name) +// Some(this) +// else if (isLeaf) +// None +// else +// subTypes.map(_ findTree tn).find(_.isInstanceOf[Some[TypeTree]]) match { +// case Some(tree) => tree +// case None => None +// } +// +// def complies(expected:TypeExpr, given:TypeExpr):List[TypeCompliance] = +// complies(this,expected,given) +// +// private def complies(topLevel:TypeTree, expected:TypeExpr, given:TypeExpr):List[TypeCompliance] = +// findTree(expected.name) match { +// case Some(expTree) => +// expTree.findTree(given.name) match { +// case Some(givTree) => List(Complies) +// case None => topLevel findTree given.name match { +// case Some(_) => List(DoesntDescend(expected.name,given.name)) +// case None => List(NonexistentType(given.name)) +// } +// } +// case None => List(NonexistentType(expected.name)) +// } +// +// def deepestCommonAncestor(a:Type, b:Type):Type = +// (a, b) match { +// case (a:KnownType, b:KnownType) => find(commonPath(a.name,b.name).last) +// case (_, _) => UnknownType +// } +// +// private def commonPath(a:String, b:String):List[String] = +// (path(a) zip path(b)) takeWhile { p => p._1 == p._2 } map { p => p._1 } +// +// private def path(tn:String):List[String] = +// path(List(),tn) match { +// case Some(l) => l +// case None => throw new NonexistentTypeError(tn) +// } +// +// private def path(path:List[String], tn:String):Option[List[String]] = +// if(tn == t.name) +// Some(path ::: List(tn)) +// else if(isLeaf) +// None +// else +// subTypes.map(_.path(path,tn)).find(_.isInstanceOf[Some[List[String]]]) match { +// case Some(Some(p)) => Some(path ::: List(t.name) ::: p) +// case None => None +// } +// +// def prettyPrint:String = prettyPrint(0).mkString +// +// def prettyPrint(indent:Int):List[Char] = +// (" " * indent).toList ::: t.name.toList ::: List('\n') ::: ( +// subTypes flatMap { _ prettyPrint (indent + 2) }) +// +// def isLeaf = subTypes.isEmpty +// +// } diff --git a/src/vmlang/vm/Main.java b/src/vmlang/vm/Main.java deleted file mode 100644 index a38f11d..0000000 --- a/src/vmlang/vm/Main.java +++ /dev/null @@ -1,34 +0,0 @@ -package vmlang.vm; - -import java.io.DataInputStream; -import java.io.FileInputStream; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; - -public class Main { - - private static final int MEM_SIZE = 1024; // arbitrary - - public static void main(String[] args) { - if(args.length > 1) - System.out.println("usage: vmlang [file to run]"); - else { - try { - File inFile = new File(args[0]); - DataInputStream in = new DataInputStream(new FileInputStream(inFile)); - int length = (int)inFile.length(); - byte[] prog = new byte[length]; - for(int i=0; i < length; i++) - prog[i] = in.readByte(); - VM vm = new VM(prog,MEM_SIZE); - vm.run(); // what all this hubbub is about... - } catch (FileNotFoundException e) { - System.out.printf("couldn't find file \"%s\"\n",args[0]); - } catch (IOException e) { - System.out.printf("error reading file \"%s\"\n",args[0]); - } - } - } - -} diff --git a/src/vmlang/vm/Main.scala b/src/vmlang/vm/Main.scala new file mode 100644 index 0000000..1c66a2b --- /dev/null +++ b/src/vmlang/vm/Main.scala @@ -0,0 +1,102 @@ +package vmlang.vm + +import java.io.{File, FileInputStream, FileNotFoundException, IOException} +import vmlang.common.{OptParse, Args} +import collection.immutable.{Set, EmptySet} + +object Main { + + // TODO: think up language name! + val help = "usage: *language name* <executable_file> <options>\n" + + "-heap_size=<num bytes> heap size in bytes\n" + + "-stack_size=<num bytes> stack size in bytes" + + def main(as:Array[String]) = { + try { + val args = OptParse(as) + // check for extra arg pairs + args.opts.keySet.toList -- List("heap_size","stack_size") match { + case Nil => + case l:List[String] => { + println("Unrecognized options: " + (l mkString ", ")) + exit + } + } + // check for extra flags + args.flags match { + case s if s.isEmpty => + case s:Seq[String] => { + println("Unrecognized flags: " + (s mkString ", ")) + exit + } + } + // get file name + val fileName = args.args match { + case s if s.length == 1 => s.first + case _ => { + println("supply 1 file name") + exit + } + } + // get stack size + val stackSize = args.opts get "stack_size" match { + case Some(s) => try { s.toInt } catch { + case e:NumberFormatException => "not a valid stack size number" + exit + } + case None => 1024 + } + // get heap size + val heapSize = args.opts get "heap_size" match { + case Some(s) => try { s.toInt } catch { + case e:NumberFormatException => "not a valid heap size number" + println(help) + throw new FatalError + } + case None => 1024 + } + + // and, finally + try { + new VM(loadFileBytes(fileName),heapSize,stackSize).run() + } catch { + case e:StackOverflowError => { + println("VM Error: Stack Overflow") + throw new FatalError + } + case e:IllegalArgumentException => { + println("VM Error: " + e.getMessage) + throw new FatalError + } + } + } catch { + case e:FatalError => + } + } + + def loadFileBytes(fileName:String):Array[Byte] = { + try { + val in = new FileInputStream(new File(fileName)) + val result = new Array[Byte](in.available) + in.read(result) + result + } catch { + case e:FileNotFoundException => { + println("File not found: " + fileName) + throw new FatalError + } + case e:IOException => { + println("Error reading file " + fileName) + throw new FatalError + } + } + } + + def exit = { + println(help) + throw new FatalError + } + +} + +class FatalError extends Exception diff --git a/src/vmlang/vm/StackOverflowError.java b/src/vmlang/vm/StackOverflowError.java new file mode 100644 index 0000000..26b31a2 --- /dev/null +++ b/src/vmlang/vm/StackOverflowError.java @@ -0,0 +1,3 @@ +package vmlang.vm; + +public class StackOverflowError extends Exception {} \ No newline at end of file diff --git a/src/vmlang/vm/VM.java b/src/vmlang/vm/VM.java index be94bf8..dc7ea2e 100644 --- a/src/vmlang/vm/VM.java +++ b/src/vmlang/vm/VM.java @@ -1,222 +1,267 @@ package vmlang.vm; import java.io.IOException; +import java.io.PrintStream; +import java.io.InputStream; import vmlang.common.Opcodes; public class VM { // registers private int A, B, SP, BP; private int counter; // memory private byte[] program; private byte[] memory; + // io + + private InputStream in; + private PrintStream out; + + private int stackStart; + private static final Opcodes[] opcodes = Opcodes.values(); // inefficient? - public VM(byte[] prog, int mem_size) { + public VM(byte[] prog, int heapSize, int stackSize) { + this(prog,heapSize,stackSize,System.in,System.out); + } + + public VM(byte[] prog, int stackSize, int heapSize, InputStream is, PrintStream os) { + if(heapSize % 8 != 0) + throw new IllegalArgumentException("Heap size must be divisible by 8 (for malloc)"); program = prog; - memory = new byte[mem_size]; + memory = new byte[heapSize + stackSize]; + stackStart = heapSize; + in = is; + out = os; } - public void run() { + public void run() throws StackOverflowError { int nextAddr; while(true) { - switch(opcodes[progReadByte()]) { - + Opcodes opcode; + try { + opcode = opcodes[progReadByte()]; + } catch(ArrayIndexOutOfBoundsException e) { + throw getMalfProgEx(); + } + switch(opcode) { + // FLOW CONTROL - + // basic case STOP: return; case GOTO: counter = progReadInt(); break; case GOTO_A: counter = A; break; // conditional jumps: based on post-SUB state of register A case IF_EQ: nextAddr = progReadInt(); if(A != 0) counter = nextAddr; break; case IF_LT: nextAddr = progReadInt(); if(A >= 0) counter = nextAddr; break; - + // LOAD & STORE (Von-Neumann bottleneck) - + // int constants case I_CONST_A: A = progReadInt(); break; case I_CONST_B: B = progReadInt(); break; // byte constants case B_CONST_A: A = progReadByte(); break; case B_CONST_B: B = progReadByte(); break; // load int case I_LOAD_A_SP: A = memReadInt(SP); break; case I_LOAD_B_SP: B = memReadInt(SP); break; case I_LOAD_SP_SP: SP = memReadInt(SP); break; // load byte case B_LOAD_A_SP: A = memReadByte(SP); break; case B_LOAD_B_SP: B = memReadByte(SP); break; // store int case I_STORE_A_SP: memWriteInt(SP,A); break; // store byte case B_STORE_A_SP: memWriteByte(SP,(byte)A); break; // moves case MOVE_COUNTER_A: A = counter; break; case MOVE_SP_A: A = SP; break; case MOVE_BP_A: A = BP; break; case MOVE_A_SP: SP = A; break; case MOVE_A_BP: BP = A; break; - + // REGISTER OPERATIONS - + // arithmetic case I_ADD: A = A + B; break; case I_SUB: A = A - B; break; case I_MUL: A = A * B; break; case I_DIV: A = A / B; break; case I_MOD: A = A * B; break; case INC_A: A++; break; // inc/dec case INC_B: B++; break; case INC_SP: SP++; break; case DEC_A: A--; break; case DEC_B: B--; break; case DEC_SP: SP--; break; // logic (0: false; non-0: true) case NEG_A: if(A == 0) A = 1; else A = 0; break; case NEG_LT_A: if(A < 0) A = 1; else A = 0; case AND: if(A != 0 && B != 0) A = 1; else A = 0; break; case OR: if(A != 0 || B != 0) A = 1; else A = 0; break; - + // io case PRINT_CHAR_A: - System.out.print((char)A); + out.print((char)A); break; case READ_CHAR_A: try { - A = System.in.read(); + A = in.read(); } catch(IOException e) { - System.out.println(e.getMessage()); + out.println(e.getMessage()); } break; } } } - public byte progReadByte() { - byte result = program[counter]; + // PROGRAM READERS + + private byte progReadByte() { + byte result; + try { + result = program[counter]; + } catch(ArrayIndexOutOfBoundsException e) { + throw getMalfProgEx(); + } counter++; return result; } - public int progReadInt() { + private int progReadInt() { return ((progReadByte() & 0xff) << 24) | ((progReadByte() & 0xff) << 16) | ((progReadByte() & 0xff) << 8) | - (progReadByte() & 0xff); + (progReadByte() & 0xff); } - public byte memReadByte(int addr) { - return memory[addr]; + // MEMORY READERS & WRITERS + + private byte memReadByte(int addr) throws StackOverflowError { + try { + return memory[addr]; + } catch(ArrayIndexOutOfBoundsException e) { + throw new StackOverflowError(); + } } - public int memReadInt(int addr) { + private int memReadInt(int addr) throws StackOverflowError { return ((memReadByte(addr) & 0xff) << 24) | - ((memReadByte(addr+1) & 0xff) << 16) | - ((memReadByte(addr+2) & 0xff) << 8) | - (memReadByte(addr+3) & 0xff); + ((memReadByte(addr+1) & 0xff) << 16) | + ((memReadByte(addr+2) & 0xff) << 8) | + (memReadByte(addr+3) & 0xff); } - public void memWriteByte(int addr, byte val) { - memory[addr] = val; + private void memWriteByte(int addr, byte val) throws StackOverflowError { + try { + memory[addr] = val; + } catch(ArrayIndexOutOfBoundsException e) { + throw new StackOverflowError(); + } } - public void memWriteInt(int addr, int val) { + private void memWriteInt(int addr, int val) throws StackOverflowError { memWriteByte(addr ,(byte)(0xff & (val >> 24))); memWriteByte(addr+1,(byte)(0xff & (val >> 16))); memWriteByte(addr+2,(byte)(0xff & (val >> 8))); memWriteByte(addr+3,(byte)(0xff & val)); } + private IllegalArgumentException getMalfProgEx() { + return new IllegalArgumentException("Malformed program"); + } + } \ No newline at end of file
vilterp/VMLang
412a61661995651fb3548b38f0bbceb5b08499a1
working on typechecker. battling mysterious compiler errors
diff --git a/src/vmlang/compiler/Compiler.scala b/src/vmlang/compiler/Compiler.scala index f91b562..b15f21e 100644 --- a/src/vmlang/compiler/Compiler.scala +++ b/src/vmlang/compiler/Compiler.scala @@ -1,47 +1,54 @@ // package vmlang.compiler // // import vmlang.compiler.ast._ -// import collection.immutable.HashMap +// import vmlang.compiler.model._ +// import vmlang.compiler.icode._ // group these imports into one? +// import collection.immutable.Map // // object Compiler { // -// def apply(prog:Prog) = { -// prog.defs.foldLeft(new HashMap[String,List[IOpcode]]){ -// (map,funcDef) => (map + (funcDef.name -> compile(funcDef))) -// .asInstanceOf[HashMap[String,List[IOpcode]]] } -// // don't know why that !@$!@ "asInstanceOf" is necessary... +// def apply(funcTable:Map[String,Function]):List[(String,List[IOpcode])] = { +// (funcTable("main") match { +// case Some(f) => ("main",compFunc(f)) +// case None => throw new NonexistentFuncError("main","[compiler]") +// }) ::: ((funcTable - "main") map { p => (p._1,compFunc(p._2)) } ) // } // -// def compile(funcDef:Def) = { -// compExpr(funcDef.body) +// def compFunc(f:Function):List[IOpcode] = f match { +// case PrimFunc(code) => code +// case NormFunc(expr) => compExpr(expr) // } // // def compExpr(e:Expr):List[IOpcode] = e match { // -// case Call("+",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(AddI()) -// case Call("-",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(SubI()) -// case Call("*",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(MultI()) -// case Call("/",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(DivI()) +// // TODO: time complexity of ":::" -- are all these calls gonna kill us? // -// case Call("==",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(CmpEq()) -// case Call("!=",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(CmpNeq()) -// case Call(">",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(CmpGt()) -// case Call(">=",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(CmpGte()) -// case Call("<",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(CmpLt()) -// case Call("<=",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(CmpLte()) +// case Call("+",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(AddI) +// case Call("-",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(SubI) +// case Call("*",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(MultI) +// case Call("/",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(DivI) +// +// case Call("==",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(CmpEq) +// case Call("!=",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(CmpNeq) +// case Call(">",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(CmpGt) +// case Call(">=",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(CmpGte) +// case Call("<",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(CmpLt) +// case Call("<=",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(CmpLte) // // case Call("true",_) => List(PushConstI(1)) // case Call("false",_) => List(PushConstI(0)) // -// case Call("printChar",List(e)) => compExpr(e) ::: List(PrintChar()) -// case Call("readChar",_) => List(ReadChar()) +// case Call("printChar",List(e)) => compExpr(e) ::: List(PrintChar) +// case Call("readChar",_) => List(ReadChar) +// +// case Call(name,args) => (args flatMap comExpr) ::: List() // // case Integer(v) => List(PushConstI(v)) // case Char(c) => List(PushConstC(c)) // // case IfExpr(c,i,e) => { val el = compExpr(e) // compExpr(c) ::: List(GotoIf(el.head)) ::: compExpr(i) ::: el } // // } // // } diff --git a/src/vmlang/compiler/ICode.scala b/src/vmlang/compiler/ICode.scala deleted file mode 100644 index 6c215b0..0000000 --- a/src/vmlang/compiler/ICode.scala +++ /dev/null @@ -1,34 +0,0 @@ -package vmlang.compiler - -// intermediate code: source > intermediate code > { MiniVM, JVM, x86 ... } - -abstract class IOpcode - -class Stop() extends IOpcode -class Goto(a:Int) extends IOpcode -class GotoFunc(f:String) extends IOpcode -class GotoIf(ref:IOpcode) extends IOpcode -class RetI() extends IOpcode - -class PushConstI(c:Int) extends IOpcode -class PushConstC(c:Char) extends IOpcode - -class AddI() extends IOpcode -class SubI() extends IOpcode -class MultI() extends IOpcode -class DivI() extends IOpcode - -class CmpEq(ref:IOpcode) extends IOpcode -class CmpNeq(ref:IOpcode) extends IOpcode -class CmpGt(ref:IOpcode) extends IOpcode -class CmpGte(ref:IOpcode) extends IOpcode -class CmpLt(ref:IOpcode) extends IOpcode -class CmpLte(ref:IOpcode) extends IOpcode - -class Neg() extends IOpcode -class NegLt() extends IOpcode -class And() extends IOpcode -class Or() extends IOpcode - -class PrintChar() extends IOpcode -class ReadChar() extends IOpcode diff --git a/src/vmlang/compiler/TypeTree.scala b/src/vmlang/compiler/TypeTree.scala deleted file mode 100644 index d716231..0000000 --- a/src/vmlang/compiler/TypeTree.scala +++ /dev/null @@ -1,73 +0,0 @@ -package vmlang.compiler - -import vmlang.compiler.ast.TypeExpr - -abstract case class Type(name:String, numParams:Int) -case class Trait(override val name:String, override val numParams:Int) extends Type(name,numParams) -case class Class(override val name:String, override val numParams:Int) extends Type(name,numParams) - // expected "Class" to be reserved... - -abstract class TypeCompliance -case object Complies extends TypeCompliance -abstract class DoesntComply extends TypeCompliance -case class NonexistentType(name:String) extends DoesntComply -case class DoesntDescend(expected:String,given:String) extends DoesntComply -case class WrongNumTypeParams(name:String,expected:Int,given:Int) extends DoesntComply - -case class TypeTree(t:Type, subTypes:List[TypeTree]) { - - def add(superTypeName:String, newType:Type):TypeTree = find(superTypeName) match { - case Some(tree) => tree add newType - case None => - throw new IllegalArgumentException("Nonexistent type: " + superTypeName) - } - - def add(newType:Type):TypeTree = TypeTree(t, TypeTree(newType,Nil) :: subTypes) - - def find(tn:String):Option[TypeTree] = { - if (tn == t.name) - Some(this) - else if (isLeaf) - None - else - subTypes.map(_ find tn).find(_.isInstanceOf[Some[TypeTree]]) match { - case Some(tree) => tree - case None => None - } - } - - def complies(expected:TypeExpr, given:TypeExpr):List[TypeCompliance] = complies(this,expected,given) - - private def complies(topLevel:TypeTree, expected:TypeExpr, given:TypeExpr):List[TypeCompliance] = - find(expected.name) match { - case Some(expTree) => - if (expected.params.length != expTree.t.numParams) - List(WrongNumTypeParams(expected.name,expTree.t.numParams,expected.params.length)) - else - expTree.find(given.name) match { - case Some(givTree) => - if(given.params.length == givTree.t.numParams) { - (expected.params zip given.params) - .flatMap{ p => complies(p._1, p._2) } removeDuplicates match { - case Nil => List(Complies) - case x :: xs => x :: xs - } - } else - List(WrongNumTypeParams(given.name,givTree.t.numParams,given.params.length)) - case None => topLevel find given.name match { - case Some(_) => List(DoesntDescend(expected.name,given.name)) - case None => List(NonexistentType(given.name)) - } - } - case None => List(NonexistentType(expected.name)) - } - - def prettyPrint:String = prettyPrint(0).mkString - - def prettyPrint(indent:Int):List[Char] = - (" " * indent).toList ::: t.name.toList ::: List('\n') ::: ( - subTypes flatMap { _ prettyPrint (indent + 2) }) - - def isLeaf = subTypes.isEmpty - -} diff --git a/src/vmlang/compiler/Util.scala b/src/vmlang/compiler/Util.scala new file mode 100644 index 0000000..b489d72 --- /dev/null +++ b/src/vmlang/compiler/Util.scala @@ -0,0 +1,20 @@ +package vmlang.compiler + +abstract class CompilerError extends Exception { + val numErrors:Int + val repr:String +} +// TODO: should have location, but can't implement - scala's combinator library drops it + +abstract class NormalCompilerError extends CompilerError { + val numErrors = 1 +} + +abstract class CompoundCompilerError(errors:List[CompilerError]) { + def numErrors = errors.length + def repr:String = (errors flatMap { _.repr } ) mkString "\n" +} + +class NonexistentFuncError(funcName:String,inDef:String) extends NormalCompilerError { + val repr = "reference to nonexistent function " + funcName + " in " + inDef +} \ No newline at end of file diff --git a/src/vmlang/compiler/ast/AST.scala b/src/vmlang/compiler/ast/AST.scala index 900230d..30a246c 100644 --- a/src/vmlang/compiler/ast/AST.scala +++ b/src/vmlang/compiler/ast/AST.scala @@ -1,21 +1,21 @@ package vmlang.compiler.ast abstract class ASTNode case class Prog(defs:List[Def]) extends ASTNode case class Def(name:String, args:List[ArgSpec], returnType:Option[TypeExpr], body:Expr) extends ASTNode case class ArgSpec(name:String, argType:TypeExpr) extends ASTNode -case class TypeExpr(name:String,params:List[TypeExpr]) extends ASTNode +case class TypeExpr(name:String) extends ASTNode abstract class Expr extends ASTNode case class IfExpr(condition:Expr, ifExpr:Expr, thenExpr:Expr) extends Expr case class Call(name:String, args:List[Expr]) extends Expr abstract class Atom extends Expr case class IntLit(value:BigInt) extends Atom case class CharLit(value:Char) extends Atom case object EmptyList extends Atom diff --git a/src/vmlang/compiler/ast/Parser.scala b/src/vmlang/compiler/ast/Parser.scala index 12a3265..362c2b6 100644 --- a/src/vmlang/compiler/ast/Parser.scala +++ b/src/vmlang/compiler/ast/Parser.scala @@ -1,99 +1,102 @@ package vmlang.compiler.ast import scala.runtime.RichString import scala.util.parsing.combinator.syntactical._ +class ParserError(msg:String) extends NormalCompilerError { + val repr = "Parser Error: " + msg +} + object Parser extends StandardTokenParsers { lexical.delimiters ++= List("+","-","*","/","(",")","[","]","=",":",",",">","<", ">=","<=","==","!","!=") lexical.reserved ++= List("if","then","else","and","or") // RULES def program = (definition *) ^^ { l => Prog(l) } def definition = ident ~ (argsSpec?) ~ (typeSpec?) ~ ("=" ~> expr) ^^ { case i ~ Some(as) ~ rt ~ e => Def(i,as,rt,e) case i ~ None ~ rt ~ e => Def(i,Nil,rt,e) } def argsSpec = "(" ~> repsep(argSpec, ",") <~ ")" def argSpec = ident ~ typeSpec ^^ { case i ~ t => ArgSpec(i,t) } def typeSpec = ":" ~> typeExpr - def typeExpr:Parser[TypeExpr] = ident ~ (typeParams?) ^^ { case i ~ Some(t) => TypeExpr(i,t) - case i ~ None => TypeExpr(i,Nil) } + def typeExpr:Parser[TypeExpr] = ident ^^ { i => TypeExpr(i) } def typeParams = "[" ~> repsep(typeExpr,",") <~ "]" def expr:Parser[Expr] = ( ifStatement | orExpr ) def ifStatement = (("if" ~> orExpr) ~ ("then" ~> orExpr) ~ ("else" ~> orExpr)) ^^ { case c ~ i ~ e => IfExpr(c,i,e) } def orExpr = andExpr * ( "or" ^^^ { (a:Expr, b:Expr) => Call("or",List(a,b)) } ) def andExpr = comparison * ( "and" ^^^ { (a:Expr, b:Expr) => Call("and",List(a,b)) } ) def comparison = sum * ( ">" ^^^ { (a:Expr, b:Expr) => Call(">",List(a,b)) } | "<" ^^^ { (a:Expr, b:Expr) => Call("<",List(a,b)) } | "==" ^^^ { (a:Expr, b:Expr) => Call("==",List(a,b)) } | "<=" ^^^ { (a:Expr, b:Expr) => Call("<=",List(a,b)) } | ">=" ^^^ { (a:Expr, b:Expr) => Call(">=",List(a,b)) } | "!=" ^^^ { (a:Expr, b:Expr) => Call("!",List(a,b)) } ) // I'm sure there's a super-elegant way to do this, // but my Scala chops aren't up to it yet def sum = product * ( "+" ^^^ { (a:Expr, b:Expr) => Call("+",List(a,b)) } | "-" ^^^ { (a:Expr, b:Expr) => Call("-",List(a,b)) } ) def product = atom * ( "*" ^^^ { (a:Expr, b:Expr) => Call("*",List(a,b)) } | "/" ^^^ { (a:Expr, b:Expr) => Call("/",List(a,b)) } ) def atom = ( number | list | string | call | parenthesizedExpr | unaryMinus | unaryNot ) // todo: char lit (not in standardtokenparsers...) def list = "[" ~> repsep(expr,",") <~ "]" ^^ concatIze def string = stringLit ^^ { (s:String) => concatIze(new RichString(s) map { CharLit(_) }) } def concatIze(items:Seq[Expr]):Expr = items.foldRight(EmptyList.asInstanceOf[Expr]){ (i,a) => Call(":",List(i,a)) } def parenthesizedExpr = "(" ~> expr <~ ")" def unaryNot:Parser[Expr] = "!" ~> atom ^^ { a => Call("!",List(a)) } def unaryMinus:Parser[Expr] = "-" ~> atom ^^ { a => Call("*",List(a,IntLit(BigInt(-1)))) } def number = numericLit ^^ { s => IntLit(BigInt(s)) } def call = ident ~ (args ?) ^^ { case i ~ Some(a) => Call(i,a) case i ~ None => Call(i,List()) } def args = "(" ~> repsep(expr,",") <~ ")" // END OF RULES def parse(s:String) = phrase(program)(new lexical.Scanner(s)) def parseTypeExpr(t:String) = phrase(typeExpr)(new lexical.Scanner(t)) match { case Success(t, _) => t case e: NoSuccess => throw new IllegalArgumentException(e.toString) } def apply(s:String) = { parse(s) match { case Success(tree, _) => tree case e: NoSuccess => - throw new IllegalArgumentException(e.toString) + throw new ParserError(e.toString) } } } diff --git a/src/vmlang/compiler/icode/ICode.scala b/src/vmlang/compiler/icode/ICode.scala new file mode 100644 index 0000000..bf09195 --- /dev/null +++ b/src/vmlang/compiler/icode/ICode.scala @@ -0,0 +1,34 @@ +package vmlang.compiler + +// intermediate code: source > intermediate code > { MiniVM, JVM, x86 ... } + +abstract class IOpcode + +case object Stop extends IOpcode +case class Goto(a:Int) extends IOpcode +case class GotoFunc(f:String) extends IOpcode +case class GotoIf(ref:IOpcode) extends IOpcode +case object RetI extends IOpcode + +case class PushConstI(c:Int) extends IOpcode +case class PushConstC(c:Char) extends IOpcode + +case object AddI extends IOpcode +case object SubI extends IOpcode +case object MultI extends IOpcode +case object DivI extends IOpcode + +case class CmpEq(ref:IOpcode) extends IOpcode +case class CmpNeq(ref:IOpcode) extends IOpcode +case class CmpGt(ref:IOpcode) extends IOpcode +case class CmpGte(ref:IOpcode) extends IOpcode +case class CmpLt(ref:IOpcode) extends IOpcode +case class CmpLte(ref:IOpcode) extends IOpcode + +case object Neg extends IOpcode +case object NegLt extends IOpcode +case object And extends IOpcode +case object Or extends IOpcode + +case object PrintChar extends IOpcode +case object ReadChar extends IOpcode diff --git a/src/vmlang/compiler/test.scala b/src/vmlang/compiler/test.scala index 0d7fefc..dd7e21f 100644 --- a/src/vmlang/compiler/test.scala +++ b/src/vmlang/compiler/test.scala @@ -1,38 +1,41 @@ package vmlang.compiler import vmlang.compiler.ast._ object Test extends UnitTest { - val tt = TypeTree(Trait("Value",0),List( - TypeTree(Trait("Ord",0),List( - TypeTree(Trait("Num",0),List( - TypeTree(Class("Int",0),Nil), - TypeTree(Class("Float",0),Nil))), - TypeTree(Class("Char",0),Nil)) + val tt = TypeTree(AbsType("Value"),List( + TypeTree(AbsType("Ord"),List( + TypeTree(AbsType("Num"),List( + TypeTree(PrimType("Int"),Nil), + TypeTree(PrimType("Float"),Nil))), + TypeTree(PrimType("Char"),Nil)) ), - TypeTree(Class("List",1),Nil), - TypeTree(Class("Map",2),List( - TypeTree(Class("HashMap",2),Nil))) + TypeTree(RefType("List"),Nil), + TypeTree(AbsType("Map"),List( + TypeTree(RefType("HashMap"),Nil))) )) implicit def string2typeExpr(s:String) = Parser.parseTypeExpr(s) + implicit def string2type(s:String) = tt find s + def main(args:Array[String]) = { shouldBe(tt.complies("Value","Char"),List(Complies)) shouldBe(tt.complies("Int","Int"),List(Complies)) shouldBe(tt.complies("Int","Char"),List(DoesntDescend("Int","Char"))) shouldBe(tt.complies("Int","Slartibartfast"),List(NonexistentType("Slartibartfast"))) - shouldBe(tt.complies("Map[Ord,Num]","HashMap[Char,Float]"),List(Complies)) - shouldBe(tt.complies("Map[Ord,Num]","HashMap[Ooj,Boo]"), - List(NonexistentType("Ooj"),NonexistentType("Boo"))) - shouldBe(tt.complies("List","List[Int]"),List(WrongNumTypeParams("List",1,0))) + + shouldBe(tt.deepestCommonAncestor("Int","Int"),tt find "Int") + shouldBe(tt.deepestCommonAncestor("Int","Float"),tt find "Num") + shouldBe(tt.deepestCommonAncestor("Char","Int"),tt find "Ord") + shouldBe(tt.deepestCommonAncestor("Num","List"),tt find "Value") } } class UnitTest { def shouldBe(a:Any, b:Any) = if (a == b) println("pass") else println("fail. should be: " + b + "; found: " + a) } \ No newline at end of file diff --git a/src/vmlang/compiler/typecheck/Compliance.scala b/src/vmlang/compiler/typecheck/Compliance.scala new file mode 100644 index 0000000..63e58a1 --- /dev/null +++ b/src/vmlang/compiler/typecheck/Compliance.scala @@ -0,0 +1,16 @@ +package vmlang.compiler.typecheck + +abstract class TypeCompliance +case object Complies extends TypeCompliance +abstract class DoesntComply extends TypeCompliance +case class NonexistentType(name:String) extends DoesntComply +case class DoesntDescend(expected:String, given:String) extends DoesntComply + +class TypeErrors(errors:List[TypeError]) extends CompoundCompilerError(errors) +abstract class TypeError extends NormalCompilerError +class NonexistentTypeError(name:String) extends TypeError { + def repr = "type " + name + " doesn't exist" +} +class DoesntDescendError(expected:String, given:String) extends TypeError { + def repr = "given type " + given + " doesn't descend from expected type " + expected +} diff --git a/src/vmlang/compiler/typecheck/Type.scala b/src/vmlang/compiler/typecheck/Type.scala new file mode 100644 index 0000000..75c74fe --- /dev/null +++ b/src/vmlang/compiler/typecheck/Type.scala @@ -0,0 +1,17 @@ +package vmlang.compiler.typecheck + +abstract class Type +case object UnknownType extends Type +abstract class KnownType extends Type { + val name:String + override def toString = name +} +case class AbsType(name:String) extends KnownType +abstract class ConcreteType extends KnownType +case class RefType(name:String) extends ConcreteType +case class PrimType(name:String) extends ConcreteType + +case class FuncType(paramTypes:List[Type], returnType:Type) { + override def toString = paramTypes.mkString("(",",",")") + " => " + returnType +} + // TODO: make this part of the normal type hierarchy... diff --git a/src/vmlang/compiler/typecheck/TypeCheck.scala b/src/vmlang/compiler/typecheck/TypeCheck.scala new file mode 100644 index 0000000..b03ff7c --- /dev/null +++ b/src/vmlang/compiler/typecheck/TypeCheck.scala @@ -0,0 +1,32 @@ +package vmlang.compiler.typecheck + +import vmlang.compiler.ast._ +import collection.immutable.Map + +object TypeCheck { + + type FuncTable = Map[String,FuncType] + + val typeTree = TypeTree(AbsType("Value"),List( + TypeTree(AbsType("Ord"),List( + TypeTree(AbsType("Num"),List( + TypeTree(PrimType("Int"),Nil), + TypeTree(PrimType("Float"),Nil))), + TypeTree(PrimType("Char"),Nil))))) + + // def apply(prog:Prog, funcTypes:Map[String,FuncType], typeTree:TypeTree) = + // + // def checkFunc(func:Def, funcTypes:Map[String,FuncType], typeTree:TypeTree) = + + def inferType(expr:Expr, funcTypes:FuncTable, typeTree:TypeTree):Type = expr match { + case IntLit(_) => typeTree find "Int" + case CharLit(_) => typeTree find "Char" + case IfExpr(_,i,t) => typeTree.deepestCommonAncestor(inferType(i,funcTypes,typeTree), + inferType(t,funcTypes,typeTree)) + case Call(name,args) => funcTypes get name match { + case Some(ft) => ft.returnType + case None => UnknownType + } + } + +} \ No newline at end of file diff --git a/src/vmlang/compiler/typecheck/TypeTree.scala b/src/vmlang/compiler/typecheck/TypeTree.scala new file mode 100644 index 0000000..6a9327b --- /dev/null +++ b/src/vmlang/compiler/typecheck/TypeTree.scala @@ -0,0 +1,80 @@ +package vmlang.compiler.typecheck + +import vmlang.compiler.ast.TypeExpr + +case class TypeTree(t:KnownType, subTypes:List[TypeTree]) { + + def add(superTypeName:String, newType:KnownType):TypeTree = findTree(superTypeName) match { + case Some(tree) => tree add newType + case None => + throw new NonexistentTypeError(superTypeName) + } + + def add(newType:KnownType):TypeTree = TypeTree(t, TypeTree(newType,Nil) :: subTypes) + + def find(tn:String) = findTree(tn) match { + case Some(tree) => tree.t + case None => + throw new NonexistentTypeError(tn) + } + + private def findTree(tn:String):Option[TypeTree] = { + if (tn == t.name) + Some(this) + else if (isLeaf) + None + else + subTypes.map(_ findTree tn).find(_.isInstanceOf[Some[TypeTree]]) match { + case Some(tree) => tree + case None => None + } + } + + def complies(expected:TypeExpr, given:TypeExpr):List[TypeCompliance] = complies(this,expected,given) + + private def complies(topLevel:TypeTree, expected:TypeExpr, given:TypeExpr):List[TypeCompliance] = + findTree(expected.name) match { + case Some(expTree) => + expTree.findTree(given.name) match { + case Some(givTree) => List(Complies) + case None => topLevel findTree given.name match { + case Some(_) => List(DoesntDescend(expected.name,given.name)) + case None => List(NonexistentType(given.name)) + } + } + case None => List(NonexistentType(expected.name)) + } + + def deepestCommonAncestor(a:Type, b:Type):Type = (a, b) match { + case (a:KnownType, b:KnownType) => find(commonPath(a.name,b.name).last) + case (_, _) => UnknownType + } + + private def commonPath(a:String, b:String):List[String] = + (path(a) zip path(b)) takeWhile { p => p._1 == p._2 } map { p => p._1 } + + private def path(tn:String):List[String] = path(List(),tn) match { + case Some(l) => l + case None => throw new NonexistentTypeError(tn) + } + + private def path(path:List[String], tn:String):Option[List[String]] = + if(tn == t.name) + Some(path ::: List(tn)) + else if(isLeaf) + None + else + subTypes.map(_.path(path,tn)).find(_.isInstanceOf[Some[List[String]]]) match { + case Some(Some(p)) => Some(path ::: List(t.name) ::: p) + case None => None + } + + def prettyPrint:String = prettyPrint(0).mkString + + def prettyPrint(indent:Int):List[Char] = + (" " * indent).toList ::: t.name.toList ::: List('\n') ::: ( + subTypes flatMap { _ prettyPrint (indent + 2) }) + + def isLeaf = subTypes.isEmpty + +}
vilterp/VMLang
82bf33807c9eb669f41602d899026d3f42b79899
worked on typetree
diff --git a/src/vmlang/compiler/TypeCheck.scala b/src/vmlang/compiler/TypeCheck.scala deleted file mode 100644 index 0583b02..0000000 --- a/src/vmlang/compiler/TypeCheck.scala +++ /dev/null @@ -1,32 +0,0 @@ -// package vmlang.compiler -// -// import vmlang.compiler.ast._ -// import collection.immutable.{HashMap, HashSet} -// -// object TypeCheck(prog:Prog,) { -// -// // how use instance vars...! -// -// // val typeHierarchy = HashSet[Type](Type("Int",Nil), Type("Char",Nil), Type("Boolean",Nil)) -// // use typeTree -// -// def apply(prog:Prog):Prog = { -// val returnTypes = prog.defs.foldLeft(new HashMap[String,Type]){ -// (m,d) => m + (d.name -> d.returnType)} -// val argTypes = prog.defs.foldLeft(new HashMap[String,List[Type]]){ -// (m,d) => m + (d.name -> d.argTypes)} -// } -// -// def infer(e:Expr) = e match { -// // atoms -// case Integer(_) => Type("Int",Nil) -// case Char(_) => Type("Char",Nil) -// case Call("true",_) => Type("Boolean",Nil) -// case Call("false",_) => Type("Boolean",Nil) -// // calls -// case Call(n,args) => -// } -// -// def correctArgTypes() -// -// } diff --git a/src/vmlang/compiler/TypeTree.scala b/src/vmlang/compiler/TypeTree.scala index 2a36880..d716231 100644 --- a/src/vmlang/compiler/TypeTree.scala +++ b/src/vmlang/compiler/TypeTree.scala @@ -1,35 +1,73 @@ package vmlang.compiler -case class TypeTree(typeName:String, subTypes:List[TypeTree]) { +import vmlang.compiler.ast.TypeExpr + +abstract case class Type(name:String, numParams:Int) +case class Trait(override val name:String, override val numParams:Int) extends Type(name,numParams) +case class Class(override val name:String, override val numParams:Int) extends Type(name,numParams) + // expected "Class" to be reserved... + +abstract class TypeCompliance +case object Complies extends TypeCompliance +abstract class DoesntComply extends TypeCompliance +case class NonexistentType(name:String) extends DoesntComply +case class DoesntDescend(expected:String,given:String) extends DoesntComply +case class WrongNumTypeParams(name:String,expected:Int,given:Int) extends DoesntComply + +case class TypeTree(t:Type, subTypes:List[TypeTree]) { - def contains(t:String) = find(t) match { - case Some(tree) => true - case None => false + def add(superTypeName:String, newType:Type):TypeTree = find(superTypeName) match { + case Some(tree) => tree add newType + case None => + throw new IllegalArgumentException("Nonexistent type: " + superTypeName) } - def find(t:String):Option[TypeTree] = { - if (t == typeName) + def add(newType:Type):TypeTree = TypeTree(t, TypeTree(newType,Nil) :: subTypes) + + def find(tn:String):Option[TypeTree] = { + if (tn == t.name) Some(this) else if (isLeaf) None else - subTypes.map(_ find t).find(_.isInstanceOf[Some[TypeTree]]) match { + subTypes.map(_ find tn).find(_.isInstanceOf[Some[TypeTree]]) match { case Some(tree) => tree case None => None } } - def complies(expected:String, given:String) = find(expected) match { - case Some(exp) => exp contains given - case None => false - } + def complies(expected:TypeExpr, given:TypeExpr):List[TypeCompliance] = complies(this,expected,given) + + private def complies(topLevel:TypeTree, expected:TypeExpr, given:TypeExpr):List[TypeCompliance] = + find(expected.name) match { + case Some(expTree) => + if (expected.params.length != expTree.t.numParams) + List(WrongNumTypeParams(expected.name,expTree.t.numParams,expected.params.length)) + else + expTree.find(given.name) match { + case Some(givTree) => + if(given.params.length == givTree.t.numParams) { + (expected.params zip given.params) + .flatMap{ p => complies(p._1, p._2) } removeDuplicates match { + case Nil => List(Complies) + case x :: xs => x :: xs + } + } else + List(WrongNumTypeParams(given.name,givTree.t.numParams,given.params.length)) + case None => topLevel find given.name match { + case Some(_) => List(DoesntDescend(expected.name,given.name)) + case None => List(NonexistentType(given.name)) + } + } + case None => List(NonexistentType(expected.name)) + } def prettyPrint:String = prettyPrint(0).mkString def prettyPrint(indent:Int):List[Char] = - (" " * indent).toList ::: typeName.toList ::: List('\n') ::: ( + (" " * indent).toList ::: t.name.toList ::: List('\n') ::: ( subTypes flatMap { _ prettyPrint (indent + 2) }) def isLeaf = subTypes.isEmpty } diff --git a/src/vmlang/compiler/ast/AST.scala b/src/vmlang/compiler/ast/AST.scala index 7caa0f0..900230d 100644 --- a/src/vmlang/compiler/ast/AST.scala +++ b/src/vmlang/compiler/ast/AST.scala @@ -1,21 +1,21 @@ package vmlang.compiler.ast abstract class ASTNode case class Prog(defs:List[Def]) extends ASTNode case class Def(name:String, args:List[ArgSpec], - returnType:Type, body:Expr) extends ASTNode -case class ArgSpec(name:String, argType:Type) extends ASTNode -case class Type(name:String,params:Option[List[Type]]) extends ASTNode + returnType:Option[TypeExpr], body:Expr) extends ASTNode +case class ArgSpec(name:String, argType:TypeExpr) extends ASTNode +case class TypeExpr(name:String,params:List[TypeExpr]) extends ASTNode abstract class Expr extends ASTNode case class IfExpr(condition:Expr, ifExpr:Expr, thenExpr:Expr) extends Expr case class Call(name:String, args:List[Expr]) extends Expr abstract class Atom extends Expr -case class Integer(value:BigInt) extends Atom -case class Char(value:Char) extends Atom +case class IntLit(value:BigInt) extends Atom +case class CharLit(value:Char) extends Atom case object EmptyList extends Atom diff --git a/src/vmlang/compiler/ast/Parser.scala b/src/vmlang/compiler/ast/Parser.scala index 1751eb2..12a3265 100644 --- a/src/vmlang/compiler/ast/Parser.scala +++ b/src/vmlang/compiler/ast/Parser.scala @@ -1,86 +1,99 @@ package vmlang.compiler.ast +import scala.runtime.RichString import scala.util.parsing.combinator.syntactical._ object Parser extends StandardTokenParsers { lexical.delimiters ++= List("+","-","*","/","(",")","[","]","=",":",",",">","<", ">=","<=","==","!","!=") lexical.reserved ++= List("if","then","else","and","or") // RULES def program = (definition *) ^^ { l => Prog(l) } - def definition = ident ~ (argsSpec?) ~ typeSpec ~ ("=" ~> expr) ^^ { + def definition = ident ~ (argsSpec?) ~ (typeSpec?) ~ ("=" ~> expr) ^^ { case i ~ Some(as) ~ rt ~ e => Def(i,as,rt,e) case i ~ None ~ rt ~ e => Def(i,Nil,rt,e) } def argsSpec = "(" ~> repsep(argSpec, ",") <~ ")" def argSpec = ident ~ typeSpec ^^ { case i ~ t => ArgSpec(i,t) } def typeSpec = ":" ~> typeExpr - def typeExpr:Parser[Type] = ident ~ (typeParams?) ^^ { case i ~ t => Type(i,t) } + def typeExpr:Parser[TypeExpr] = ident ~ (typeParams?) ^^ { case i ~ Some(t) => TypeExpr(i,t) + case i ~ None => TypeExpr(i,Nil) } def typeParams = "[" ~> repsep(typeExpr,",") <~ "]" def expr:Parser[Expr] = ( ifStatement | orExpr ) def ifStatement = (("if" ~> orExpr) ~ ("then" ~> orExpr) ~ ("else" ~> orExpr)) ^^ { case c ~ i ~ e => IfExpr(c,i,e) } def orExpr = andExpr * ( "or" ^^^ { (a:Expr, b:Expr) => Call("or",List(a,b)) } ) def andExpr = comparison * ( "and" ^^^ { (a:Expr, b:Expr) => Call("and",List(a,b)) } ) def comparison = sum * ( ">" ^^^ { (a:Expr, b:Expr) => Call(">",List(a,b)) } | "<" ^^^ { (a:Expr, b:Expr) => Call("<",List(a,b)) } | "==" ^^^ { (a:Expr, b:Expr) => Call("==",List(a,b)) } | "<=" ^^^ { (a:Expr, b:Expr) => Call("<=",List(a,b)) } | ">=" ^^^ { (a:Expr, b:Expr) => Call(">=",List(a,b)) } | "!=" ^^^ { (a:Expr, b:Expr) => Call("!",List(a,b)) } ) // I'm sure there's a super-elegant way to do this, // but my Scala chops aren't up to it yet def sum = product * ( "+" ^^^ { (a:Expr, b:Expr) => Call("+",List(a,b)) } | "-" ^^^ { (a:Expr, b:Expr) => Call("-",List(a,b)) } ) def product = atom * ( "*" ^^^ { (a:Expr, b:Expr) => Call("*",List(a,b)) } | "/" ^^^ { (a:Expr, b:Expr) => Call("/",List(a,b)) } ) - def atom = ( number | list | call | parenthesizedExpr | unaryMinus | unaryNot ) + def atom = ( number | list | string | call | parenthesizedExpr | unaryMinus | unaryNot ) + // todo: char lit (not in standardtokenparsers...) - def list = "[" ~> repsep(expr,",") <~ "]" ^^ { l => Call(":",List(EmptyList)) } - // this should transform [1,2,3] into :(1,:(2,:(3,[]))) + def list = "[" ~> repsep(expr,",") <~ "]" ^^ concatIze + + def string = stringLit ^^ { (s:String) => concatIze(new RichString(s) map { CharLit(_) }) } + + def concatIze(items:Seq[Expr]):Expr = items.foldRight(EmptyList.asInstanceOf[Expr]){ + (i,a) => Call(":",List(i,a)) } def parenthesizedExpr = "(" ~> expr <~ ")" def unaryNot:Parser[Expr] = "!" ~> atom ^^ { a => Call("!",List(a)) } - def unaryMinus:Parser[Expr] = "-" ~> atom ^^ { a => Call("*",List(a,Integer(BigInt(-1)))) } + def unaryMinus:Parser[Expr] = "-" ~> atom ^^ { a => Call("*",List(a,IntLit(BigInt(-1)))) } - def number = numericLit ^^ { s => Integer(BigInt(s)) } + def number = numericLit ^^ { s => IntLit(BigInt(s)) } def call = ident ~ (args ?) ^^ { case i ~ Some(a) => Call(i,a) case i ~ None => Call(i,List()) } def args = "(" ~> repsep(expr,",") <~ ")" // END OF RULES def parse(s:String) = phrase(program)(new lexical.Scanner(s)) + def parseTypeExpr(t:String) = phrase(typeExpr)(new lexical.Scanner(t)) match { + case Success(t, _) => t + case e: NoSuccess => + throw new IllegalArgumentException(e.toString) + } + def apply(s:String) = { parse(s) match { case Success(tree, _) => tree case e: NoSuccess => throw new IllegalArgumentException(e.toString) } } } diff --git a/src/vmlang/compiler/test.scala b/src/vmlang/compiler/test.scala index 8a7bd91..0d7fefc 100644 --- a/src/vmlang/compiler/test.scala +++ b/src/vmlang/compiler/test.scala @@ -1,8 +1,38 @@ package vmlang.compiler -object Test extends Application { - val t = TypeTree("Value",List(TypeTree("Num",List(TypeTree("Int",Nil),TypeTree("Float",Nil))))) - println(t prettyPrint) - println(t.complies("Value","Int")) - println(t.complies("Value","Floob")) +import vmlang.compiler.ast._ + +object Test extends UnitTest { + + val tt = TypeTree(Trait("Value",0),List( + TypeTree(Trait("Ord",0),List( + TypeTree(Trait("Num",0),List( + TypeTree(Class("Int",0),Nil), + TypeTree(Class("Float",0),Nil))), + TypeTree(Class("Char",0),Nil)) + ), + TypeTree(Class("List",1),Nil), + TypeTree(Class("Map",2),List( + TypeTree(Class("HashMap",2),Nil))) + )) + + implicit def string2typeExpr(s:String) = Parser.parseTypeExpr(s) + + def main(args:Array[String]) = { + shouldBe(tt.complies("Value","Char"),List(Complies)) + shouldBe(tt.complies("Int","Int"),List(Complies)) + shouldBe(tt.complies("Int","Char"),List(DoesntDescend("Int","Char"))) + shouldBe(tt.complies("Int","Slartibartfast"),List(NonexistentType("Slartibartfast"))) + shouldBe(tt.complies("Map[Ord,Num]","HashMap[Char,Float]"),List(Complies)) + shouldBe(tt.complies("Map[Ord,Num]","HashMap[Ooj,Boo]"), + List(NonexistentType("Ooj"),NonexistentType("Boo"))) + shouldBe(tt.complies("List","List[Int]"),List(WrongNumTypeParams("List",1,0))) + } } + +class UnitTest { + + def shouldBe(a:Any, b:Any) = + if (a == b) println("pass") else println("fail. should be: " + b + "; found: " + a) + +} \ No newline at end of file
vilterp/VMLang
536ef11b20819a0e90898df01f0c5c367754db36
started ast-to-intermediate code translator, wrote TypeTree, added read_char opcode, fixed tabbing
diff --git a/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_compiler_$_ast_$_AST.scala b/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_compiler_$_ast_$_AST.scala index 565d274..71e3294 100644 Binary files a/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_compiler_$_ast_$_AST.scala and b/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_compiler_$_ast_$_AST.scala differ diff --git a/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_compiler_$_test.scala b/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_compiler_$_test.scala index 64697aa..3101cde 100644 Binary files a/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_compiler_$_test.scala and b/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_compiler_$_test.scala differ diff --git a/something.diff b/something.diff new file mode 100644 index 0000000..8a6f649 --- /dev/null +++ b/something.diff @@ -0,0 +1,349 @@ +diff --git a/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_compiler_$_ast_$_AST.scala b/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_compiler_$_ast_$_AST.scala +index 565d274..71e3294 100644 +Binary files a/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_compiler_$_ast_$_AST.scala and b/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_compiler_$_ast_$_AST.scala differ +diff --git a/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_compiler_$_test.scala b/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_compiler_$_test.scala +index 64697aa..3101cde 100644 +Binary files a/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_compiler_$_test.scala and b/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_compiler_$_test.scala differ +diff --git a/src/vmlang/common/Opcodes.java b/src/vmlang/common/Opcodes.java +index 8114948..aab0c7e 100644 +--- a/src/vmlang/common/Opcodes.java ++++ b/src/vmlang/common/Opcodes.java +@@ -1,45 +1,47 @@ + package vmlang.common; + + public enum Opcodes { +- ++ + STOP, +- GOTO, +- GOTO_A, +- IF_EQ, +- IF_LT, +- I_CONST_A, +- I_CONST_B, +- B_CONST_A, +- B_CONST_B, +- I_LOAD_A_SP, +- I_LOAD_B_SP, ++ GOTO, ++ GOTO_A, ++ IF_EQ, ++ IF_LT, ++ I_CONST_A, ++ I_CONST_B, ++ B_CONST_A, ++ B_CONST_B, ++ I_LOAD_A_SP, ++ I_LOAD_B_SP, + I_LOAD_SP_SP, +- B_LOAD_A_SP, +- B_LOAD_B_SP, +- I_STORE_A_SP, +- B_STORE_A_SP, +- MOVE_COUNTER_A, +- MOVE_SP_A, +- MOVE_BP_A, +- MOVE_A_SP, +- MOVE_A_BP, +- I_ADD, +- I_SUB, +- I_MUL, +- I_DIV, +- I_MOD, +- INC_A, +- INC_B, +- INC_SP, +- DEC_A, +- DEC_B, +- DEC_SP, +- NEG_A, +- AND, +- OR, +- PRINT_CHAR_A; +- +- public byte toByte() { +- return (byte)ordinal(); +- } ++ B_LOAD_A_SP, ++ B_LOAD_B_SP, ++ I_STORE_A_SP, ++ B_STORE_A_SP, ++ MOVE_COUNTER_A, ++ MOVE_SP_A, ++ MOVE_BP_A, ++ MOVE_A_SP, ++ MOVE_A_BP, ++ I_ADD, ++ I_SUB, ++ I_MUL, ++ I_DIV, ++ I_MOD, ++ INC_A, ++ INC_B, ++ INC_SP, ++ DEC_A, ++ DEC_B, ++ DEC_SP, ++ NEG_A, ++ NEG_LT_A, ++ AND, ++ OR, ++ PRINT_CHAR_A, ++ READ_CHAR_A; ++ ++ public byte toByte() { ++ return (byte)ordinal(); ++ } + } +diff --git a/src/vmlang/compiler/Compiler.scala b/src/vmlang/compiler/Compiler.scala +index fb52ea0..f91b562 100644 +--- a/src/vmlang/compiler/Compiler.scala ++++ b/src/vmlang/compiler/Compiler.scala +@@ -1,20 +1,47 @@ +-package vmlang.compiler +- +-import vmlang.compiler.ast._ +-import vmlang.compiler.icode._ +-import collection.immutable.HashMap +- +-object Compiler { +- +- def apply(prog:Prog) = { +- prog.defs.foldLeft(new HashMap[String,List[IOpcode]]){ +- (map,funcDef) => (map + (funcDef.name -> compile(funcDef))) +- .asInstanceOf[HashMap[String,List[IOpcode]]] } +- // don't know why that !@$!@ "asInstanceOf" is necessary... +- } +- +- def compile(funcDef:Def) = { +- compileExpr(funcDef.body) +- } +- +-} ++// package vmlang.compiler ++// ++// import vmlang.compiler.ast._ ++// import collection.immutable.HashMap ++// ++// object Compiler { ++// ++// def apply(prog:Prog) = { ++// prog.defs.foldLeft(new HashMap[String,List[IOpcode]]){ ++// (map,funcDef) => (map + (funcDef.name -> compile(funcDef))) ++// .asInstanceOf[HashMap[String,List[IOpcode]]] } ++// // don't know why that !@$!@ "asInstanceOf" is necessary... ++// } ++// ++// def compile(funcDef:Def) = { ++// compExpr(funcDef.body) ++// } ++// ++// def compExpr(e:Expr):List[IOpcode] = e match { ++// ++// case Call("+",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(AddI()) ++// case Call("-",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(SubI()) ++// case Call("*",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(MultI()) ++// case Call("/",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(DivI()) ++// ++// case Call("==",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(CmpEq()) ++// case Call("!=",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(CmpNeq()) ++// case Call(">",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(CmpGt()) ++// case Call(">=",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(CmpGte()) ++// case Call("<",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(CmpLt()) ++// case Call("<=",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(CmpLte()) ++// ++// case Call("true",_) => List(PushConstI(1)) ++// case Call("false",_) => List(PushConstI(0)) ++// ++// case Call("printChar",List(e)) => compExpr(e) ::: List(PrintChar()) ++// case Call("readChar",_) => List(ReadChar()) ++// ++// case Integer(v) => List(PushConstI(v)) ++// case Char(c) => List(PushConstC(c)) ++// ++// case IfExpr(c,i,e) => { val el = compExpr(e) ++// compExpr(c) ::: List(GotoIf(el.head)) ::: compExpr(i) ::: el } ++// ++// } ++// ++// } +diff --git a/src/vmlang/compiler/ICode.scala b/src/vmlang/compiler/ICode.scala +index d2fe959..6c215b0 100644 +--- a/src/vmlang/compiler/ICode.scala ++++ b/src/vmlang/compiler/ICode.scala +@@ -1,7 +1,34 @@ +-package vmlang.compiler.icode ++package vmlang.compiler + + // intermediate code: source > intermediate code > { MiniVM, JVM, x86 ... } + + abstract class IOpcode + +-case class PushConstant(v:Int) extends IOpcode +\ No newline at end of file ++class Stop() extends IOpcode ++class Goto(a:Int) extends IOpcode ++class GotoFunc(f:String) extends IOpcode ++class GotoIf(ref:IOpcode) extends IOpcode ++class RetI() extends IOpcode ++ ++class PushConstI(c:Int) extends IOpcode ++class PushConstC(c:Char) extends IOpcode ++ ++class AddI() extends IOpcode ++class SubI() extends IOpcode ++class MultI() extends IOpcode ++class DivI() extends IOpcode ++ ++class CmpEq(ref:IOpcode) extends IOpcode ++class CmpNeq(ref:IOpcode) extends IOpcode ++class CmpGt(ref:IOpcode) extends IOpcode ++class CmpGte(ref:IOpcode) extends IOpcode ++class CmpLt(ref:IOpcode) extends IOpcode ++class CmpLte(ref:IOpcode) extends IOpcode ++ ++class Neg() extends IOpcode ++class NegLt() extends IOpcode ++class And() extends IOpcode ++class Or() extends IOpcode ++ ++class PrintChar() extends IOpcode ++class ReadChar() extends IOpcode +diff --git a/src/vmlang/compiler/ast/AST.scala b/src/vmlang/compiler/ast/AST.scala +index 5e7c84b..7caa0f0 100644 +--- a/src/vmlang/compiler/ast/AST.scala ++++ b/src/vmlang/compiler/ast/AST.scala +@@ -3,12 +3,11 @@ package vmlang.compiler.ast + abstract class ASTNode + + case class Prog(defs:List[Def]) extends ASTNode +-case class Def(name:String, args:Option[List[ArgSpec]], +- returnType:Option[Type], body:Expr) extends ASTNode ++case class Def(name:String, args:List[ArgSpec], ++ returnType:Type, body:Expr) extends ASTNode + case class ArgSpec(name:String, argType:Type) extends ASTNode + case class Type(name:String,params:Option[List[Type]]) extends ASTNode + +- + abstract class Expr extends ASTNode + + case class IfExpr(condition:Expr, ifExpr:Expr, thenExpr:Expr) extends Expr +@@ -16,6 +15,7 @@ case class Call(name:String, args:List[Expr]) extends Expr + + abstract class Atom extends Expr + +-case class Integer(value:String) extends Atom ++case class Integer(value:BigInt) extends Atom + case class Char(value:Char) extends Atom +-case object EmptyList extends Atom +\ No newline at end of file ++case object EmptyList extends Atom ++ +diff --git a/src/vmlang/compiler/ast/Parser.scala b/src/vmlang/compiler/ast/Parser.scala +index 71a51bf..1751eb2 100644 +--- a/src/vmlang/compiler/ast/Parser.scala ++++ b/src/vmlang/compiler/ast/Parser.scala +@@ -12,8 +12,9 @@ object Parser extends StandardTokenParsers { + + def program = (definition *) ^^ { l => Prog(l) } + +- def definition = ident ~ (argsSpec?) ~ (typeSpec?) ~ ("=" ~> expr) ^^ { +- case i ~ as ~ rt ~ e => Def(i,as,rt,e) } ++ def definition = ident ~ (argsSpec?) ~ typeSpec ~ ("=" ~> expr) ^^ { ++ case i ~ Some(as) ~ rt ~ e => Def(i,as,rt,e) ++ case i ~ None ~ rt ~ e => Def(i,Nil,rt,e) } + + def argsSpec = "(" ~> repsep(argSpec, ",") <~ ")" + +@@ -40,7 +41,7 @@ object Parser extends StandardTokenParsers { + "==" ^^^ { (a:Expr, b:Expr) => Call("==",List(a,b)) } | + "<=" ^^^ { (a:Expr, b:Expr) => Call("<=",List(a,b)) } | + ">=" ^^^ { (a:Expr, b:Expr) => Call(">=",List(a,b)) } | +- "!=" ^^^ { (a:Expr, b:Expr) => Call("!",List(Call("==",List(a,b)))) } ) ++ "!=" ^^^ { (a:Expr, b:Expr) => Call("!",List(a,b)) } ) + // I'm sure there's a super-elegant way to do this, + // but my Scala chops aren't up to it yet + +@@ -61,9 +62,9 @@ object Parser extends StandardTokenParsers { + + def unaryNot:Parser[Expr] = "!" ~> atom ^^ { a => Call("!",List(a)) } + +- def unaryMinus:Parser[Expr] = "-" ~> atom ^^ { a => Call("*",List(a,Integer("-1"))) } ++ def unaryMinus:Parser[Expr] = "-" ~> atom ^^ { a => Call("*",List(a,Integer(BigInt(-1)))) } + +- def number = numericLit ^^ { s => Integer(s) } ++ def number = numericLit ^^ { s => Integer(BigInt(s)) } + + def call = ident ~ (args ?) ^^ { case i ~ Some(a) => Call(i,a) + case i ~ None => Call(i,List()) } +diff --git a/src/vmlang/compiler/test.scala b/src/vmlang/compiler/test.scala +index 843fd84..8a7bd91 100644 +--- a/src/vmlang/compiler/test.scala ++++ b/src/vmlang/compiler/test.scala +@@ -1,20 +1,8 @@ + package vmlang.compiler + +-import scala.util.parsing.combinator.syntactical._ +-import vmlang.compiler.ast._ +-import collection.immutable.HashMap +- +-import java.util.Scanner +- + object Test extends Application { +- val s = new Scanner(System.in) +- print("> ") +- while(s.hasNext) { +- try { +- println(Parser(s.nextLine)) +- } catch { +- case e:IllegalArgumentException => println(e.getMessage) +- } +- print("> ") +- } ++ val t = TypeTree("Value",List(TypeTree("Num",List(TypeTree("Int",Nil),TypeTree("Float",Nil))))) ++ println(t prettyPrint) ++ println(t.complies("Value","Int")) ++ println(t.complies("Value","Floob")) + } +diff --git a/src/vmlang/vm/VM.java b/src/vmlang/vm/VM.java +index 6ab6829..be94bf8 100644 +--- a/src/vmlang/vm/VM.java ++++ b/src/vmlang/vm/VM.java +@@ -1,5 +1,7 @@ + package vmlang.vm; + ++import java.io.IOException; ++ + import vmlang.common.Opcodes; + + public class VM { +@@ -149,6 +151,11 @@ public class VM { + else + A = 0; + break; ++ case NEG_LT_A: ++ if(A < 0) ++ A = 1; ++ else ++ A = 0; + case AND: + if(A != 0 && B != 0) + A = 1; +@@ -162,9 +169,17 @@ public class VM { + A = 0; + break; + ++ // io + case PRINT_CHAR_A: + System.out.print((char)A); + break; ++ case READ_CHAR_A: ++ try { ++ A = System.in.read(); ++ } catch(IOException e) { ++ System.out.println(e.getMessage()); ++ } ++ break; + } + } + } diff --git a/src/vmlang/common/Opcodes.java b/src/vmlang/common/Opcodes.java index 8114948..aab0c7e 100644 --- a/src/vmlang/common/Opcodes.java +++ b/src/vmlang/common/Opcodes.java @@ -1,45 +1,47 @@ package vmlang.common; public enum Opcodes { - + STOP, - GOTO, - GOTO_A, - IF_EQ, - IF_LT, - I_CONST_A, - I_CONST_B, - B_CONST_A, - B_CONST_B, - I_LOAD_A_SP, - I_LOAD_B_SP, + GOTO, + GOTO_A, + IF_EQ, + IF_LT, + I_CONST_A, + I_CONST_B, + B_CONST_A, + B_CONST_B, + I_LOAD_A_SP, + I_LOAD_B_SP, I_LOAD_SP_SP, - B_LOAD_A_SP, - B_LOAD_B_SP, - I_STORE_A_SP, - B_STORE_A_SP, - MOVE_COUNTER_A, - MOVE_SP_A, - MOVE_BP_A, - MOVE_A_SP, - MOVE_A_BP, - I_ADD, - I_SUB, - I_MUL, - I_DIV, - I_MOD, - INC_A, - INC_B, - INC_SP, - DEC_A, - DEC_B, - DEC_SP, - NEG_A, - AND, - OR, - PRINT_CHAR_A; - - public byte toByte() { - return (byte)ordinal(); - } + B_LOAD_A_SP, + B_LOAD_B_SP, + I_STORE_A_SP, + B_STORE_A_SP, + MOVE_COUNTER_A, + MOVE_SP_A, + MOVE_BP_A, + MOVE_A_SP, + MOVE_A_BP, + I_ADD, + I_SUB, + I_MUL, + I_DIV, + I_MOD, + INC_A, + INC_B, + INC_SP, + DEC_A, + DEC_B, + DEC_SP, + NEG_A, + NEG_LT_A, + AND, + OR, + PRINT_CHAR_A, + READ_CHAR_A; + + public byte toByte() { + return (byte)ordinal(); + } } diff --git a/src/vmlang/compiler/Compiler.scala b/src/vmlang/compiler/Compiler.scala index fb52ea0..f91b562 100644 --- a/src/vmlang/compiler/Compiler.scala +++ b/src/vmlang/compiler/Compiler.scala @@ -1,20 +1,47 @@ -package vmlang.compiler - -import vmlang.compiler.ast._ -import vmlang.compiler.icode._ -import collection.immutable.HashMap - -object Compiler { - - def apply(prog:Prog) = { - prog.defs.foldLeft(new HashMap[String,List[IOpcode]]){ - (map,funcDef) => (map + (funcDef.name -> compile(funcDef))) - .asInstanceOf[HashMap[String,List[IOpcode]]] } - // don't know why that !@$!@ "asInstanceOf" is necessary... - } - - def compile(funcDef:Def) = { - compileExpr(funcDef.body) - } - -} +// package vmlang.compiler +// +// import vmlang.compiler.ast._ +// import collection.immutable.HashMap +// +// object Compiler { +// +// def apply(prog:Prog) = { +// prog.defs.foldLeft(new HashMap[String,List[IOpcode]]){ +// (map,funcDef) => (map + (funcDef.name -> compile(funcDef))) +// .asInstanceOf[HashMap[String,List[IOpcode]]] } +// // don't know why that !@$!@ "asInstanceOf" is necessary... +// } +// +// def compile(funcDef:Def) = { +// compExpr(funcDef.body) +// } +// +// def compExpr(e:Expr):List[IOpcode] = e match { +// +// case Call("+",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(AddI()) +// case Call("-",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(SubI()) +// case Call("*",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(MultI()) +// case Call("/",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(DivI()) +// +// case Call("==",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(CmpEq()) +// case Call("!=",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(CmpNeq()) +// case Call(">",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(CmpGt()) +// case Call(">=",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(CmpGte()) +// case Call("<",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(CmpLt()) +// case Call("<=",List(a,b)) => compExpr(a) ::: compExpr(b) ::: List(CmpLte()) +// +// case Call("true",_) => List(PushConstI(1)) +// case Call("false",_) => List(PushConstI(0)) +// +// case Call("printChar",List(e)) => compExpr(e) ::: List(PrintChar()) +// case Call("readChar",_) => List(ReadChar()) +// +// case Integer(v) => List(PushConstI(v)) +// case Char(c) => List(PushConstC(c)) +// +// case IfExpr(c,i,e) => { val el = compExpr(e) +// compExpr(c) ::: List(GotoIf(el.head)) ::: compExpr(i) ::: el } +// +// } +// +// } diff --git a/src/vmlang/compiler/ICode.scala b/src/vmlang/compiler/ICode.scala index d2fe959..6c215b0 100644 --- a/src/vmlang/compiler/ICode.scala +++ b/src/vmlang/compiler/ICode.scala @@ -1,7 +1,34 @@ -package vmlang.compiler.icode +package vmlang.compiler // intermediate code: source > intermediate code > { MiniVM, JVM, x86 ... } abstract class IOpcode -case class PushConstant(v:Int) extends IOpcode \ No newline at end of file +class Stop() extends IOpcode +class Goto(a:Int) extends IOpcode +class GotoFunc(f:String) extends IOpcode +class GotoIf(ref:IOpcode) extends IOpcode +class RetI() extends IOpcode + +class PushConstI(c:Int) extends IOpcode +class PushConstC(c:Char) extends IOpcode + +class AddI() extends IOpcode +class SubI() extends IOpcode +class MultI() extends IOpcode +class DivI() extends IOpcode + +class CmpEq(ref:IOpcode) extends IOpcode +class CmpNeq(ref:IOpcode) extends IOpcode +class CmpGt(ref:IOpcode) extends IOpcode +class CmpGte(ref:IOpcode) extends IOpcode +class CmpLt(ref:IOpcode) extends IOpcode +class CmpLte(ref:IOpcode) extends IOpcode + +class Neg() extends IOpcode +class NegLt() extends IOpcode +class And() extends IOpcode +class Or() extends IOpcode + +class PrintChar() extends IOpcode +class ReadChar() extends IOpcode diff --git a/src/vmlang/compiler/Simplifier.scala b/src/vmlang/compiler/Simplifier.scala new file mode 100644 index 0000000..7303842 --- /dev/null +++ b/src/vmlang/compiler/Simplifier.scala @@ -0,0 +1,18 @@ +package vmlang.compiler + +import vmlang.compiler.ast._ +import collection.immutable.HashSet + +object Simplifier { + + val ops = HashSet("+","-","*","/",">","<",">=","<=","==","and","or","!") + + def apply(prog:Prog) = Prog(prog.defs map { case Def(n,a,r,body) => Def(n,a,r,simplify(body)) }) + + def simplify(e:Expr):Expr = e match { + case a:Atom => a + case IfExpr(c,i,e) => IfExpr(simplify(c),simplify(i),simplify(e)) + case Call(n,args) => if (ops contains n) simplify(Call(n,args map simplify)) else Call(n,args map simplify) + } + +} diff --git a/src/vmlang/compiler/TypeCheck.scala b/src/vmlang/compiler/TypeCheck.scala new file mode 100644 index 0000000..0583b02 --- /dev/null +++ b/src/vmlang/compiler/TypeCheck.scala @@ -0,0 +1,32 @@ +// package vmlang.compiler +// +// import vmlang.compiler.ast._ +// import collection.immutable.{HashMap, HashSet} +// +// object TypeCheck(prog:Prog,) { +// +// // how use instance vars...! +// +// // val typeHierarchy = HashSet[Type](Type("Int",Nil), Type("Char",Nil), Type("Boolean",Nil)) +// // use typeTree +// +// def apply(prog:Prog):Prog = { +// val returnTypes = prog.defs.foldLeft(new HashMap[String,Type]){ +// (m,d) => m + (d.name -> d.returnType)} +// val argTypes = prog.defs.foldLeft(new HashMap[String,List[Type]]){ +// (m,d) => m + (d.name -> d.argTypes)} +// } +// +// def infer(e:Expr) = e match { +// // atoms +// case Integer(_) => Type("Int",Nil) +// case Char(_) => Type("Char",Nil) +// case Call("true",_) => Type("Boolean",Nil) +// case Call("false",_) => Type("Boolean",Nil) +// // calls +// case Call(n,args) => +// } +// +// def correctArgTypes() +// +// } diff --git a/src/vmlang/compiler/TypeTree.scala b/src/vmlang/compiler/TypeTree.scala new file mode 100644 index 0000000..2a36880 --- /dev/null +++ b/src/vmlang/compiler/TypeTree.scala @@ -0,0 +1,35 @@ +package vmlang.compiler + +case class TypeTree(typeName:String, subTypes:List[TypeTree]) { + + def contains(t:String) = find(t) match { + case Some(tree) => true + case None => false + } + + def find(t:String):Option[TypeTree] = { + if (t == typeName) + Some(this) + else if (isLeaf) + None + else + subTypes.map(_ find t).find(_.isInstanceOf[Some[TypeTree]]) match { + case Some(tree) => tree + case None => None + } + } + + def complies(expected:String, given:String) = find(expected) match { + case Some(exp) => exp contains given + case None => false + } + + def prettyPrint:String = prettyPrint(0).mkString + + def prettyPrint(indent:Int):List[Char] = + (" " * indent).toList ::: typeName.toList ::: List('\n') ::: ( + subTypes flatMap { _ prettyPrint (indent + 2) }) + + def isLeaf = subTypes.isEmpty + +} diff --git a/src/vmlang/compiler/ast/AST.scala b/src/vmlang/compiler/ast/AST.scala index 5e7c84b..7caa0f0 100644 --- a/src/vmlang/compiler/ast/AST.scala +++ b/src/vmlang/compiler/ast/AST.scala @@ -1,21 +1,21 @@ package vmlang.compiler.ast abstract class ASTNode case class Prog(defs:List[Def]) extends ASTNode -case class Def(name:String, args:Option[List[ArgSpec]], - returnType:Option[Type], body:Expr) extends ASTNode +case class Def(name:String, args:List[ArgSpec], + returnType:Type, body:Expr) extends ASTNode case class ArgSpec(name:String, argType:Type) extends ASTNode case class Type(name:String,params:Option[List[Type]]) extends ASTNode - abstract class Expr extends ASTNode case class IfExpr(condition:Expr, ifExpr:Expr, thenExpr:Expr) extends Expr case class Call(name:String, args:List[Expr]) extends Expr abstract class Atom extends Expr -case class Integer(value:String) extends Atom +case class Integer(value:BigInt) extends Atom case class Char(value:Char) extends Atom -case object EmptyList extends Atom \ No newline at end of file +case object EmptyList extends Atom + diff --git a/src/vmlang/compiler/ast/Parser.scala b/src/vmlang/compiler/ast/Parser.scala index 71a51bf..1751eb2 100644 --- a/src/vmlang/compiler/ast/Parser.scala +++ b/src/vmlang/compiler/ast/Parser.scala @@ -1,85 +1,86 @@ package vmlang.compiler.ast import scala.util.parsing.combinator.syntactical._ object Parser extends StandardTokenParsers { lexical.delimiters ++= List("+","-","*","/","(",")","[","]","=",":",",",">","<", ">=","<=","==","!","!=") lexical.reserved ++= List("if","then","else","and","or") // RULES def program = (definition *) ^^ { l => Prog(l) } - def definition = ident ~ (argsSpec?) ~ (typeSpec?) ~ ("=" ~> expr) ^^ { - case i ~ as ~ rt ~ e => Def(i,as,rt,e) } + def definition = ident ~ (argsSpec?) ~ typeSpec ~ ("=" ~> expr) ^^ { + case i ~ Some(as) ~ rt ~ e => Def(i,as,rt,e) + case i ~ None ~ rt ~ e => Def(i,Nil,rt,e) } def argsSpec = "(" ~> repsep(argSpec, ",") <~ ")" def argSpec = ident ~ typeSpec ^^ { case i ~ t => ArgSpec(i,t) } def typeSpec = ":" ~> typeExpr def typeExpr:Parser[Type] = ident ~ (typeParams?) ^^ { case i ~ t => Type(i,t) } def typeParams = "[" ~> repsep(typeExpr,",") <~ "]" def expr:Parser[Expr] = ( ifStatement | orExpr ) def ifStatement = (("if" ~> orExpr) ~ ("then" ~> orExpr) ~ ("else" ~> orExpr)) ^^ { case c ~ i ~ e => IfExpr(c,i,e) } def orExpr = andExpr * ( "or" ^^^ { (a:Expr, b:Expr) => Call("or",List(a,b)) } ) def andExpr = comparison * ( "and" ^^^ { (a:Expr, b:Expr) => Call("and",List(a,b)) } ) def comparison = sum * ( ">" ^^^ { (a:Expr, b:Expr) => Call(">",List(a,b)) } | "<" ^^^ { (a:Expr, b:Expr) => Call("<",List(a,b)) } | "==" ^^^ { (a:Expr, b:Expr) => Call("==",List(a,b)) } | "<=" ^^^ { (a:Expr, b:Expr) => Call("<=",List(a,b)) } | ">=" ^^^ { (a:Expr, b:Expr) => Call(">=",List(a,b)) } | - "!=" ^^^ { (a:Expr, b:Expr) => Call("!",List(Call("==",List(a,b)))) } ) + "!=" ^^^ { (a:Expr, b:Expr) => Call("!",List(a,b)) } ) // I'm sure there's a super-elegant way to do this, // but my Scala chops aren't up to it yet def sum = product * ( "+" ^^^ { (a:Expr, b:Expr) => Call("+",List(a,b)) } | "-" ^^^ { (a:Expr, b:Expr) => Call("-",List(a,b)) } ) def product = atom * ( "*" ^^^ { (a:Expr, b:Expr) => Call("*",List(a,b)) } | "/" ^^^ { (a:Expr, b:Expr) => Call("/",List(a,b)) } ) def atom = ( number | list | call | parenthesizedExpr | unaryMinus | unaryNot ) def list = "[" ~> repsep(expr,",") <~ "]" ^^ { l => Call(":",List(EmptyList)) } // this should transform [1,2,3] into :(1,:(2,:(3,[]))) def parenthesizedExpr = "(" ~> expr <~ ")" def unaryNot:Parser[Expr] = "!" ~> atom ^^ { a => Call("!",List(a)) } - def unaryMinus:Parser[Expr] = "-" ~> atom ^^ { a => Call("*",List(a,Integer("-1"))) } + def unaryMinus:Parser[Expr] = "-" ~> atom ^^ { a => Call("*",List(a,Integer(BigInt(-1)))) } - def number = numericLit ^^ { s => Integer(s) } + def number = numericLit ^^ { s => Integer(BigInt(s)) } def call = ident ~ (args ?) ^^ { case i ~ Some(a) => Call(i,a) case i ~ None => Call(i,List()) } def args = "(" ~> repsep(expr,",") <~ ")" // END OF RULES def parse(s:String) = phrase(program)(new lexical.Scanner(s)) def apply(s:String) = { parse(s) match { case Success(tree, _) => tree case e: NoSuccess => throw new IllegalArgumentException(e.toString) } } } diff --git a/src/vmlang/compiler/test.scala b/src/vmlang/compiler/test.scala index 843fd84..8a7bd91 100644 --- a/src/vmlang/compiler/test.scala +++ b/src/vmlang/compiler/test.scala @@ -1,20 +1,8 @@ package vmlang.compiler -import scala.util.parsing.combinator.syntactical._ -import vmlang.compiler.ast._ -import collection.immutable.HashMap - -import java.util.Scanner - object Test extends Application { - val s = new Scanner(System.in) - print("> ") - while(s.hasNext) { - try { - println(Parser(s.nextLine)) - } catch { - case e:IllegalArgumentException => println(e.getMessage) - } - print("> ") - } + val t = TypeTree("Value",List(TypeTree("Num",List(TypeTree("Int",Nil),TypeTree("Float",Nil))))) + println(t prettyPrint) + println(t.complies("Value","Int")) + println(t.complies("Value","Floob")) } diff --git a/src/vmlang/vm/VM.java b/src/vmlang/vm/VM.java index 6ab6829..be94bf8 100644 --- a/src/vmlang/vm/VM.java +++ b/src/vmlang/vm/VM.java @@ -1,207 +1,222 @@ package vmlang.vm; +import java.io.IOException; + import vmlang.common.Opcodes; public class VM { // registers private int A, B, SP, BP; private int counter; // memory private byte[] program; private byte[] memory; private static final Opcodes[] opcodes = Opcodes.values(); // inefficient? public VM(byte[] prog, int mem_size) { program = prog; memory = new byte[mem_size]; } public void run() { int nextAddr; while(true) { switch(opcodes[progReadByte()]) { // FLOW CONTROL // basic case STOP: return; case GOTO: counter = progReadInt(); break; case GOTO_A: counter = A; break; // conditional jumps: based on post-SUB state of register A case IF_EQ: nextAddr = progReadInt(); if(A != 0) counter = nextAddr; break; case IF_LT: nextAddr = progReadInt(); if(A >= 0) counter = nextAddr; break; // LOAD & STORE (Von-Neumann bottleneck) // int constants case I_CONST_A: A = progReadInt(); break; case I_CONST_B: B = progReadInt(); break; // byte constants case B_CONST_A: A = progReadByte(); break; case B_CONST_B: B = progReadByte(); break; // load int case I_LOAD_A_SP: A = memReadInt(SP); break; case I_LOAD_B_SP: B = memReadInt(SP); break; case I_LOAD_SP_SP: SP = memReadInt(SP); break; // load byte case B_LOAD_A_SP: A = memReadByte(SP); break; case B_LOAD_B_SP: B = memReadByte(SP); break; // store int case I_STORE_A_SP: memWriteInt(SP,A); break; // store byte case B_STORE_A_SP: memWriteByte(SP,(byte)A); break; // moves case MOVE_COUNTER_A: A = counter; break; case MOVE_SP_A: A = SP; break; case MOVE_BP_A: A = BP; break; case MOVE_A_SP: SP = A; break; case MOVE_A_BP: BP = A; break; // REGISTER OPERATIONS // arithmetic case I_ADD: A = A + B; break; case I_SUB: A = A - B; break; case I_MUL: A = A * B; break; case I_DIV: A = A / B; break; case I_MOD: A = A * B; break; case INC_A: A++; break; // inc/dec case INC_B: B++; break; case INC_SP: SP++; break; case DEC_A: A--; break; case DEC_B: B--; break; case DEC_SP: SP--; break; // logic (0: false; non-0: true) case NEG_A: if(A == 0) A = 1; else A = 0; break; + case NEG_LT_A: + if(A < 0) + A = 1; + else + A = 0; case AND: if(A != 0 && B != 0) A = 1; else A = 0; break; case OR: if(A != 0 || B != 0) A = 1; else A = 0; break; + // io case PRINT_CHAR_A: System.out.print((char)A); break; + case READ_CHAR_A: + try { + A = System.in.read(); + } catch(IOException e) { + System.out.println(e.getMessage()); + } + break; } } } public byte progReadByte() { byte result = program[counter]; counter++; return result; } public int progReadInt() { return ((progReadByte() & 0xff) << 24) | ((progReadByte() & 0xff) << 16) | ((progReadByte() & 0xff) << 8) | (progReadByte() & 0xff); } public byte memReadByte(int addr) { return memory[addr]; } public int memReadInt(int addr) { return ((memReadByte(addr) & 0xff) << 24) | ((memReadByte(addr+1) & 0xff) << 16) | ((memReadByte(addr+2) & 0xff) << 8) | (memReadByte(addr+3) & 0xff); } public void memWriteByte(int addr, byte val) { memory[addr] = val; } public void memWriteInt(int addr, int val) { memWriteByte(addr ,(byte)(0xff & (val >> 24))); memWriteByte(addr+1,(byte)(0xff & (val >> 16))); memWriteByte(addr+2,(byte)(0xff & (val >> 8))); memWriteByte(addr+3,(byte)(0xff & val)); } } \ No newline at end of file
vilterp/VMLang
2814933f3126c96c1d605e47d2754bcdeb56fd7c
starting compiler...
diff --git a/.gitignore b/.gitignore index 4e35eb1..babd423 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,5 @@ .DS_Store bin/* vmlang_log.txt +.settings/* +.manager/* diff --git a/.settings/ch.epfl.lamp.sdt.core.prefs b/.settings/ch.epfl.lamp.sdt.core.prefs index 3ef167b..6af18c1 100644 --- a/.settings/ch.epfl.lamp.sdt.core.prefs +++ b/.settings/ch.epfl.lamp.sdt.core.prefs @@ -1,25 +1,25 @@ -#Sun Nov 22 13:54:05 EST 2009 +#Fri Nov 27 12:18:33 EST 2009 <file>=false Xcheck-null=false Xcheckinit=false Xdisable-assertions=false Xexperimental=false Xfuture=false Xlog-implicits=false Xno-uescape=false Xno-varargs-conversion=false Yclosure-elim=false Ydead-code=false Ydetach=false Yinline=false Ylinearizer=rpo Yno-generic-signatures=false Yno-imports=false Yno-predefs=false Yself-in-annots=false Ywarn-dead-code=false eclipse.preferences.version=1 g=vars optimise=false scala.compiler.useProjectSettings=false target=jvm-1.5 diff --git a/src/vmlang/compiler/Compiler.scala b/src/vmlang/compiler/Compiler.scala new file mode 100644 index 0000000..fb52ea0 --- /dev/null +++ b/src/vmlang/compiler/Compiler.scala @@ -0,0 +1,20 @@ +package vmlang.compiler + +import vmlang.compiler.ast._ +import vmlang.compiler.icode._ +import collection.immutable.HashMap + +object Compiler { + + def apply(prog:Prog) = { + prog.defs.foldLeft(new HashMap[String,List[IOpcode]]){ + (map,funcDef) => (map + (funcDef.name -> compile(funcDef))) + .asInstanceOf[HashMap[String,List[IOpcode]]] } + // don't know why that !@$!@ "asInstanceOf" is necessary... + } + + def compile(funcDef:Def) = { + compileExpr(funcDef.body) + } + +} diff --git a/src/vmlang/compiler/ICode.scala b/src/vmlang/compiler/ICode.scala new file mode 100644 index 0000000..d2fe959 --- /dev/null +++ b/src/vmlang/compiler/ICode.scala @@ -0,0 +1,7 @@ +package vmlang.compiler.icode + +// intermediate code: source > intermediate code > { MiniVM, JVM, x86 ... } + +abstract class IOpcode + +case class PushConstant(v:Int) extends IOpcode \ No newline at end of file diff --git a/src/vmlang/compiler/ast/Parser.scala b/src/vmlang/compiler/ast/Parser.scala index 316d344..71a51bf 100644 --- a/src/vmlang/compiler/ast/Parser.scala +++ b/src/vmlang/compiler/ast/Parser.scala @@ -1,84 +1,85 @@ package vmlang.compiler.ast import scala.util.parsing.combinator.syntactical._ object Parser extends StandardTokenParsers { - - lexical.delimiters ++= List("+","-","*","/","(",")","[","]","=",":",",",">","<",">=","<=","==","!","!=") - lexical.reserved ++= List("if","then","else","and","or") - - // RULES - - def program = (definition *) ^^ { l => Prog(l) } + + lexical.delimiters ++= List("+","-","*","/","(",")","[","]","=",":",",",">","<", + ">=","<=","==","!","!=") + lexical.reserved ++= List("if","then","else","and","or") + + // RULES + + def program = (definition *) ^^ { l => Prog(l) } + + def definition = ident ~ (argsSpec?) ~ (typeSpec?) ~ ("=" ~> expr) ^^ { + case i ~ as ~ rt ~ e => Def(i,as,rt,e) } + + def argsSpec = "(" ~> repsep(argSpec, ",") <~ ")" + + def argSpec = ident ~ typeSpec ^^ { case i ~ t => ArgSpec(i,t) } + + def typeSpec = ":" ~> typeExpr + + def typeExpr:Parser[Type] = ident ~ (typeParams?) ^^ { case i ~ t => Type(i,t) } + + def typeParams = "[" ~> repsep(typeExpr,",") <~ "]" + + def expr:Parser[Expr] = ( ifStatement | orExpr ) + + def ifStatement = (("if" ~> orExpr) ~ ("then" ~> orExpr) ~ ("else" ~> orExpr)) ^^ { + case c ~ i ~ e => IfExpr(c,i,e) } - def definition = ident ~ (argsSpec?) ~ (typeSpec?) ~ ("=" ~> expr) ^^ { - case i ~ as ~ rt ~ e => Def(i,as,rt,e) } - - def argsSpec = "(" ~> repsep(argSpec, ",") <~ ")" - - def argSpec = ident ~ typeSpec ^^ { case i ~ t => ArgSpec(i,t) } - - def typeSpec = ":" ~> typeExpr - - def typeExpr:Parser[Type] = ident ~ (typeParams?) ^^ { case i ~ t => Type(i,t) } - - def typeParams = "[" ~> repsep(typeExpr,",") <~ "]" - - def expr:Parser[Expr] = ( ifStatement | orExpr ) - - def ifStatement = (("if" ~> orExpr) ~ ("then" ~> orExpr) ~ ("else" ~> orExpr)) ^^ { - case c ~ i ~ e => IfExpr(c,i,e) } - - def orExpr = andExpr * ( "or" ^^^ { (a:Expr, b:Expr) => Call("or",List(a,b)) } ) - - def andExpr = comparison * ( "and" ^^^ { (a:Expr, b:Expr) => Call("and",List(a,b)) } ) - - def comparison = sum * ( - ">" ^^^ { (a:Expr, b:Expr) => Call(">",List(a,b)) } | - "<" ^^^ { (a:Expr, b:Expr) => Call("<",List(a,b)) } | - "==" ^^^ { (a:Expr, b:Expr) => Call("==",List(a,b)) } | - "<=" ^^^ { (a:Expr, b:Expr) => Call("<=",List(a,b)) } | - ">=" ^^^ { (a:Expr, b:Expr) => Call(">=",List(a,b)) } | - "!=" ^^^ { (a:Expr, b:Expr) => Call("!",List(Call("==",List(a,b)))) } ) - // I'm sure there's a super-elegant way to do this, - // but my Scala chops aren't up to it yet - - def sum = product * ( - "+" ^^^ { (a:Expr, b:Expr) => Call("+",List(a,b)) } | - "-" ^^^ { (a:Expr, b:Expr) => Call("-",List(a,b)) } ) - - def product = atom * ( - "*" ^^^ { (a:Expr, b:Expr) => Call("*",List(a,b)) } | - "/" ^^^ { (a:Expr, b:Expr) => Call("/",List(a,b)) } ) - - def atom = ( number | list | call | parenthesizedExpr | unaryMinus | unaryNot ) - - def list = "[" ~> repsep(expr,",") <~ "]" ^^ { l => Call(":",List(EmptyList)) } - // this should transform [1,2,3] into :(1,:(2,:(3,[]))) - - def parenthesizedExpr = "(" ~> expr <~ ")" - - def unaryNot:Parser[Expr] = "!" ~> atom ^^ { a => Call("!",List(a)) } - - def unaryMinus:Parser[Expr] = "-" ~> atom ^^ { a => Call("*",List(a,Integer("-1"))) } - - def number = numericLit ^^ { s => Integer(s) } - - def call = ident ~ (args ?) ^^ { case i ~ Some(a) => Call(i,a) - case i ~ None => Call(i,List()) } - - def args = "(" ~> repsep(expr,",") <~ ")" - - // END OF RULES - - def parse(s:String) = phrase(program)(new lexical.Scanner(s)) - - def apply(s:String) = { - parse(s) match { - case Success(tree, _) => tree - case e: NoSuccess => - throw new IllegalArgumentException(e.toString) - } - } - + def orExpr = andExpr * ( "or" ^^^ { (a:Expr, b:Expr) => Call("or",List(a,b)) } ) + + def andExpr = comparison * ( "and" ^^^ { (a:Expr, b:Expr) => Call("and",List(a,b)) } ) + + def comparison = sum * ( + ">" ^^^ { (a:Expr, b:Expr) => Call(">",List(a,b)) } | + "<" ^^^ { (a:Expr, b:Expr) => Call("<",List(a,b)) } | + "==" ^^^ { (a:Expr, b:Expr) => Call("==",List(a,b)) } | + "<=" ^^^ { (a:Expr, b:Expr) => Call("<=",List(a,b)) } | + ">=" ^^^ { (a:Expr, b:Expr) => Call(">=",List(a,b)) } | + "!=" ^^^ { (a:Expr, b:Expr) => Call("!",List(Call("==",List(a,b)))) } ) + // I'm sure there's a super-elegant way to do this, + // but my Scala chops aren't up to it yet + + def sum = product * ( + "+" ^^^ { (a:Expr, b:Expr) => Call("+",List(a,b)) } | + "-" ^^^ { (a:Expr, b:Expr) => Call("-",List(a,b)) } ) + + def product = atom * ( + "*" ^^^ { (a:Expr, b:Expr) => Call("*",List(a,b)) } | + "/" ^^^ { (a:Expr, b:Expr) => Call("/",List(a,b)) } ) + + def atom = ( number | list | call | parenthesizedExpr | unaryMinus | unaryNot ) + + def list = "[" ~> repsep(expr,",") <~ "]" ^^ { l => Call(":",List(EmptyList)) } + // this should transform [1,2,3] into :(1,:(2,:(3,[]))) + + def parenthesizedExpr = "(" ~> expr <~ ")" + + def unaryNot:Parser[Expr] = "!" ~> atom ^^ { a => Call("!",List(a)) } + + def unaryMinus:Parser[Expr] = "-" ~> atom ^^ { a => Call("*",List(a,Integer("-1"))) } + + def number = numericLit ^^ { s => Integer(s) } + + def call = ident ~ (args ?) ^^ { case i ~ Some(a) => Call(i,a) + case i ~ None => Call(i,List()) } + + def args = "(" ~> repsep(expr,",") <~ ")" + + // END OF RULES + + def parse(s:String) = phrase(program)(new lexical.Scanner(s)) + + def apply(s:String) = { + parse(s) match { + case Success(tree, _) => tree + case e: NoSuccess => + throw new IllegalArgumentException(e.toString) + } + } + } diff --git a/src/vmlang/compiler/test.scala b/src/vmlang/compiler/test.scala index dd2db0f..843fd84 100644 --- a/src/vmlang/compiler/test.scala +++ b/src/vmlang/compiler/test.scala @@ -1,18 +1,20 @@ package vmlang.compiler import scala.util.parsing.combinator.syntactical._ import vmlang.compiler.ast._ +import collection.immutable.HashMap -object Something extends StandardTokenParsers { - - lexical.delimiters ++= List("(",")") - - def someRule = repsep(ident,",") - - def apply(in:String) = phrase(someRule)(new lexical.Scanner(in)) - -} +import java.util.Scanner object Test extends Application { - println(Parser("a = 2-2")) + val s = new Scanner(System.in) + print("> ") + while(s.hasNext) { + try { + println(Parser(s.nextLine)) + } catch { + case e:IllegalArgumentException => println(e.getMessage) + } + print("> ") + } }
vilterp/VMLang
e1099cc95c513208889e8252d6347bb3d5c00c72
change to .gitignore
diff --git a/.gitignore b/.gitignore index 3d2b208..4e35eb1 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ .DS_Store bin/* +vmlang_log.txt
vilterp/VMLang
251b068fc16e0c84fa7da8a0f5e12ad06246a849
inital commit (again). I think I've settled on a directory structure this time.
diff --git a/.classpath b/.classpath new file mode 100644 index 0000000..97c403d --- /dev/null +++ b/.classpath @@ -0,0 +1,7 @@ +<?xml version="1.0" encoding="UTF-8"?> +<classpath> + <classpathentry kind="src" path="src"/> + <classpathentry kind="con" path="ch.epfl.lamp.sdt.launching.SCALA_CONTAINER"/> + <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/> + <classpathentry kind="output" path="bin"/> +</classpath> diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3d2b208 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +.DS_Store +bin/* diff --git a/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_common_$_Opcodes.java b/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_common_$_Opcodes.java new file mode 100644 index 0000000..d30ea89 Binary files /dev/null and b/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_common_$_Opcodes.java differ diff --git a/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_common_$_OptParser.scala b/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_common_$_OptParser.scala new file mode 100644 index 0000000..24f031d Binary files /dev/null and b/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_common_$_OptParser.scala differ diff --git a/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_compiler_$_ast_$_AST.scala b/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_compiler_$_ast_$_AST.scala new file mode 100644 index 0000000..565d274 Binary files /dev/null and b/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_compiler_$_ast_$_AST.scala differ diff --git a/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_compiler_$_ast_$_Parser.scala b/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_compiler_$_ast_$_Parser.scala new file mode 100644 index 0000000..940e4aa Binary files /dev/null and b/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_compiler_$_ast_$_Parser.scala differ diff --git a/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_compiler_$_test.scala b/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_compiler_$_test.scala new file mode 100644 index 0000000..64697aa Binary files /dev/null and b/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_compiler_$_test.scala differ diff --git a/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_vm_$_Main.java b/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_vm_$_Main.java new file mode 100644 index 0000000..d30ea89 Binary files /dev/null and b/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_vm_$_Main.java differ diff --git a/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_vm_$_Main.scala b/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_vm_$_Main.scala new file mode 100644 index 0000000..bb33646 Binary files /dev/null and b/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_vm_$_Main.scala differ diff --git a/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_vm_$_VM.java b/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_vm_$_VM.java new file mode 100644 index 0000000..d30ea89 Binary files /dev/null and b/.manager/_$_Users_$_petevilter_$_Dropbox_$_code_$_vmlang_$_src_$_vmlang_$_vm_$_VM.java differ diff --git a/.project b/.project new file mode 100644 index 0000000..77f32c4 --- /dev/null +++ b/.project @@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="UTF-8"?> +<projectDescription> + <name>VMLang</name> + <comment></comment> + <projects> + </projects> + <buildSpec> + <buildCommand> + <name>ch.epfl.lamp.sdt.core.scalabuilder</name> + <arguments> + </arguments> + </buildCommand> + </buildSpec> + <natures> + <nature>ch.epfl.lamp.sdt.core.scalanature</nature> + <nature>org.eclipse.jdt.core.javanature</nature> + </natures> +</projectDescription> diff --git a/.settings/ch.epfl.lamp.sdt.core.prefs b/.settings/ch.epfl.lamp.sdt.core.prefs new file mode 100644 index 0000000..3ef167b --- /dev/null +++ b/.settings/ch.epfl.lamp.sdt.core.prefs @@ -0,0 +1,25 @@ +#Sun Nov 22 13:54:05 EST 2009 +<file>=false +Xcheck-null=false +Xcheckinit=false +Xdisable-assertions=false +Xexperimental=false +Xfuture=false +Xlog-implicits=false +Xno-uescape=false +Xno-varargs-conversion=false +Yclosure-elim=false +Ydead-code=false +Ydetach=false +Yinline=false +Ylinearizer=rpo +Yno-generic-signatures=false +Yno-imports=false +Yno-predefs=false +Yself-in-annots=false +Ywarn-dead-code=false +eclipse.preferences.version=1 +g=vars +optimise=false +scala.compiler.useProjectSettings=false +target=jvm-1.5 diff --git a/.settings/org.eclipse.jdt.core.prefs b/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..e6bab3a --- /dev/null +++ b/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,4 @@ +#Sun Nov 22 13:54:06 EST 2009 +eclipse.preferences.version=1 +org.eclipse.jdt.core.builder.cleanOutputFolder=ignore +org.eclipse.jdt.core.builder.resourceCopyExclusionFilter=*.scala diff --git a/.settings/org.eclipse.ltk.core.refactoring.prefs b/.settings/org.eclipse.ltk.core.refactoring.prefs new file mode 100644 index 0000000..bb1620d --- /dev/null +++ b/.settings/org.eclipse.ltk.core.refactoring.prefs @@ -0,0 +1,3 @@ +#Sun Nov 22 13:54:05 EST 2009 +eclipse.preferences.version=1 +org.eclipse.ltk.core.refactoring.enable.project.refactoring.history=false diff --git a/build.xml b/build.xml new file mode 100644 index 0000000..af8236e --- /dev/null +++ b/build.xml @@ -0,0 +1,47 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project name="VMLang" default="test" basedir="."> + + <property name="base.dir" value="${basedir}" /> + <property name="sources.dir" value="${base.dir}/src" /> + <property name="build.dir" value="${base.dir}/bin" /> + + <!-- set up scala stuff --> + + <property name="scala.home" value="/Applications/scala-2.7.7"/> + <property name="scala-library.jar" value="${scala.home}/lib/scala-library.jar"/> + + <path id="build.classpath"> + <pathelement location="${scala-library.jar}"/> + <pathelement location="${build.dir}"/> + </path> + + <taskdef resource="scala/tools/ant/antlib.xml"> + <classpath> + <pathelement location="${scala.home}/lib/scala-compiler.jar"/> + <pathelement location="${scala-library.jar}"/> + </classpath> + </taskdef> + + <!-- end scala setup --> + + <target name="compile_everything"> + <antcall target="compile_vm"/> + <antcall target="compile_compiler"/> + </target> + + <target name="compile_vm"> + <javac srcdir="${sources.dir}" destdir="${build.dir}" debug="true"/> + </target> + + <target name="compile_compiler"> + <scalac srcdir="${sources.dir}" destdir="${build.dir}" classpathref="build.classpath" scalacdebugging="true"> + <include name="**/*.scala"/> + <exclude name="**/*.java"/> + </scalac> + </target> + + <target name="test" depends="compile_everything"> + <java classname="vmlang.compiler.Test" classpathref="build.classpath"/> + </target> + +</project> diff --git a/src/vmlang/common/Opcodes.java b/src/vmlang/common/Opcodes.java new file mode 100644 index 0000000..8114948 --- /dev/null +++ b/src/vmlang/common/Opcodes.java @@ -0,0 +1,45 @@ +package vmlang.common; + +public enum Opcodes { + + STOP, + GOTO, + GOTO_A, + IF_EQ, + IF_LT, + I_CONST_A, + I_CONST_B, + B_CONST_A, + B_CONST_B, + I_LOAD_A_SP, + I_LOAD_B_SP, + I_LOAD_SP_SP, + B_LOAD_A_SP, + B_LOAD_B_SP, + I_STORE_A_SP, + B_STORE_A_SP, + MOVE_COUNTER_A, + MOVE_SP_A, + MOVE_BP_A, + MOVE_A_SP, + MOVE_A_BP, + I_ADD, + I_SUB, + I_MUL, + I_DIV, + I_MOD, + INC_A, + INC_B, + INC_SP, + DEC_A, + DEC_B, + DEC_SP, + NEG_A, + AND, + OR, + PRINT_CHAR_A; + + public byte toByte() { + return (byte)ordinal(); + } +} diff --git a/src/vmlang/compiler/ast/AST.scala b/src/vmlang/compiler/ast/AST.scala new file mode 100644 index 0000000..5e7c84b --- /dev/null +++ b/src/vmlang/compiler/ast/AST.scala @@ -0,0 +1,21 @@ +package vmlang.compiler.ast + +abstract class ASTNode + +case class Prog(defs:List[Def]) extends ASTNode +case class Def(name:String, args:Option[List[ArgSpec]], + returnType:Option[Type], body:Expr) extends ASTNode +case class ArgSpec(name:String, argType:Type) extends ASTNode +case class Type(name:String,params:Option[List[Type]]) extends ASTNode + + +abstract class Expr extends ASTNode + +case class IfExpr(condition:Expr, ifExpr:Expr, thenExpr:Expr) extends Expr +case class Call(name:String, args:List[Expr]) extends Expr + +abstract class Atom extends Expr + +case class Integer(value:String) extends Atom +case class Char(value:Char) extends Atom +case object EmptyList extends Atom \ No newline at end of file diff --git a/src/vmlang/compiler/ast/Parser.scala b/src/vmlang/compiler/ast/Parser.scala new file mode 100644 index 0000000..316d344 --- /dev/null +++ b/src/vmlang/compiler/ast/Parser.scala @@ -0,0 +1,84 @@ +package vmlang.compiler.ast + +import scala.util.parsing.combinator.syntactical._ + +object Parser extends StandardTokenParsers { + + lexical.delimiters ++= List("+","-","*","/","(",")","[","]","=",":",",",">","<",">=","<=","==","!","!=") + lexical.reserved ++= List("if","then","else","and","or") + + // RULES + + def program = (definition *) ^^ { l => Prog(l) } + + def definition = ident ~ (argsSpec?) ~ (typeSpec?) ~ ("=" ~> expr) ^^ { + case i ~ as ~ rt ~ e => Def(i,as,rt,e) } + + def argsSpec = "(" ~> repsep(argSpec, ",") <~ ")" + + def argSpec = ident ~ typeSpec ^^ { case i ~ t => ArgSpec(i,t) } + + def typeSpec = ":" ~> typeExpr + + def typeExpr:Parser[Type] = ident ~ (typeParams?) ^^ { case i ~ t => Type(i,t) } + + def typeParams = "[" ~> repsep(typeExpr,",") <~ "]" + + def expr:Parser[Expr] = ( ifStatement | orExpr ) + + def ifStatement = (("if" ~> orExpr) ~ ("then" ~> orExpr) ~ ("else" ~> orExpr)) ^^ { + case c ~ i ~ e => IfExpr(c,i,e) } + + def orExpr = andExpr * ( "or" ^^^ { (a:Expr, b:Expr) => Call("or",List(a,b)) } ) + + def andExpr = comparison * ( "and" ^^^ { (a:Expr, b:Expr) => Call("and",List(a,b)) } ) + + def comparison = sum * ( + ">" ^^^ { (a:Expr, b:Expr) => Call(">",List(a,b)) } | + "<" ^^^ { (a:Expr, b:Expr) => Call("<",List(a,b)) } | + "==" ^^^ { (a:Expr, b:Expr) => Call("==",List(a,b)) } | + "<=" ^^^ { (a:Expr, b:Expr) => Call("<=",List(a,b)) } | + ">=" ^^^ { (a:Expr, b:Expr) => Call(">=",List(a,b)) } | + "!=" ^^^ { (a:Expr, b:Expr) => Call("!",List(Call("==",List(a,b)))) } ) + // I'm sure there's a super-elegant way to do this, + // but my Scala chops aren't up to it yet + + def sum = product * ( + "+" ^^^ { (a:Expr, b:Expr) => Call("+",List(a,b)) } | + "-" ^^^ { (a:Expr, b:Expr) => Call("-",List(a,b)) } ) + + def product = atom * ( + "*" ^^^ { (a:Expr, b:Expr) => Call("*",List(a,b)) } | + "/" ^^^ { (a:Expr, b:Expr) => Call("/",List(a,b)) } ) + + def atom = ( number | list | call | parenthesizedExpr | unaryMinus | unaryNot ) + + def list = "[" ~> repsep(expr,",") <~ "]" ^^ { l => Call(":",List(EmptyList)) } + // this should transform [1,2,3] into :(1,:(2,:(3,[]))) + + def parenthesizedExpr = "(" ~> expr <~ ")" + + def unaryNot:Parser[Expr] = "!" ~> atom ^^ { a => Call("!",List(a)) } + + def unaryMinus:Parser[Expr] = "-" ~> atom ^^ { a => Call("*",List(a,Integer("-1"))) } + + def number = numericLit ^^ { s => Integer(s) } + + def call = ident ~ (args ?) ^^ { case i ~ Some(a) => Call(i,a) + case i ~ None => Call(i,List()) } + + def args = "(" ~> repsep(expr,",") <~ ")" + + // END OF RULES + + def parse(s:String) = phrase(program)(new lexical.Scanner(s)) + + def apply(s:String) = { + parse(s) match { + case Success(tree, _) => tree + case e: NoSuccess => + throw new IllegalArgumentException(e.toString) + } + } + +} diff --git a/src/vmlang/compiler/test.scala b/src/vmlang/compiler/test.scala new file mode 100644 index 0000000..dd2db0f --- /dev/null +++ b/src/vmlang/compiler/test.scala @@ -0,0 +1,18 @@ +package vmlang.compiler + +import scala.util.parsing.combinator.syntactical._ +import vmlang.compiler.ast._ + +object Something extends StandardTokenParsers { + + lexical.delimiters ++= List("(",")") + + def someRule = repsep(ident,",") + + def apply(in:String) = phrase(someRule)(new lexical.Scanner(in)) + +} + +object Test extends Application { + println(Parser("a = 2-2")) +} diff --git a/src/vmlang/vm/Main.java b/src/vmlang/vm/Main.java new file mode 100644 index 0000000..a38f11d --- /dev/null +++ b/src/vmlang/vm/Main.java @@ -0,0 +1,34 @@ +package vmlang.vm; + +import java.io.DataInputStream; +import java.io.FileInputStream; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; + +public class Main { + + private static final int MEM_SIZE = 1024; // arbitrary + + public static void main(String[] args) { + if(args.length > 1) + System.out.println("usage: vmlang [file to run]"); + else { + try { + File inFile = new File(args[0]); + DataInputStream in = new DataInputStream(new FileInputStream(inFile)); + int length = (int)inFile.length(); + byte[] prog = new byte[length]; + for(int i=0; i < length; i++) + prog[i] = in.readByte(); + VM vm = new VM(prog,MEM_SIZE); + vm.run(); // what all this hubbub is about... + } catch (FileNotFoundException e) { + System.out.printf("couldn't find file \"%s\"\n",args[0]); + } catch (IOException e) { + System.out.printf("error reading file \"%s\"\n",args[0]); + } + } + } + +} diff --git a/src/vmlang/vm/VM.java b/src/vmlang/vm/VM.java new file mode 100644 index 0000000..6ab6829 --- /dev/null +++ b/src/vmlang/vm/VM.java @@ -0,0 +1,207 @@ +package vmlang.vm; + +import vmlang.common.Opcodes; + +public class VM { + + // registers + private int A, B, SP, BP; + private int counter; + + // memory + private byte[] program; + private byte[] memory; + + private static final Opcodes[] opcodes = Opcodes.values(); // inefficient? + + public VM(byte[] prog, int mem_size) { + program = prog; + memory = new byte[mem_size]; + } + + public void run() { + int nextAddr; + while(true) { + switch(opcodes[progReadByte()]) { + + // FLOW CONTROL + + // basic + case STOP: + return; + case GOTO: + counter = progReadInt(); + break; + case GOTO_A: + counter = A; + break; + // conditional jumps: based on post-SUB state of register A + case IF_EQ: + nextAddr = progReadInt(); + if(A != 0) + counter = nextAddr; + break; + case IF_LT: + nextAddr = progReadInt(); + if(A >= 0) + counter = nextAddr; + break; + + // LOAD & STORE (Von-Neumann bottleneck) + + // int constants + case I_CONST_A: + A = progReadInt(); + break; + case I_CONST_B: + B = progReadInt(); + break; + // byte constants + case B_CONST_A: + A = progReadByte(); + break; + case B_CONST_B: + B = progReadByte(); + break; + // load int + case I_LOAD_A_SP: + A = memReadInt(SP); + break; + case I_LOAD_B_SP: + B = memReadInt(SP); + break; + case I_LOAD_SP_SP: + SP = memReadInt(SP); + break; + // load byte + case B_LOAD_A_SP: + A = memReadByte(SP); + break; + case B_LOAD_B_SP: + B = memReadByte(SP); + break; + // store int + case I_STORE_A_SP: + memWriteInt(SP,A); + break; + // store byte + case B_STORE_A_SP: + memWriteByte(SP,(byte)A); + break; + // moves + case MOVE_COUNTER_A: + A = counter; + break; + case MOVE_SP_A: + A = SP; + break; + case MOVE_BP_A: + A = BP; + break; + case MOVE_A_SP: + SP = A; + break; + case MOVE_A_BP: + BP = A; + break; + + // REGISTER OPERATIONS + + // arithmetic + case I_ADD: + A = A + B; + break; + case I_SUB: + A = A - B; + break; + case I_MUL: + A = A * B; + break; + case I_DIV: + A = A / B; + break; + case I_MOD: + A = A * B; + break; + case INC_A: + A++; + break; + // inc/dec + case INC_B: + B++; + break; + case INC_SP: + SP++; + break; + case DEC_A: + A--; + break; + case DEC_B: + B--; + break; + case DEC_SP: + SP--; + break; + // logic (0: false; non-0: true) + case NEG_A: + if(A == 0) + A = 1; + else + A = 0; + break; + case AND: + if(A != 0 && B != 0) + A = 1; + else + A = 0; + break; + case OR: + if(A != 0 || B != 0) + A = 1; + else + A = 0; + break; + + case PRINT_CHAR_A: + System.out.print((char)A); + break; + } + } + } + + public byte progReadByte() { + byte result = program[counter]; + counter++; + return result; + } + + public int progReadInt() { + return ((progReadByte() & 0xff) << 24) | + ((progReadByte() & 0xff) << 16) | + ((progReadByte() & 0xff) << 8) | + (progReadByte() & 0xff); + } + + public byte memReadByte(int addr) { + return memory[addr]; + } + + public int memReadInt(int addr) { + return ((memReadByte(addr) & 0xff) << 24) | + ((memReadByte(addr+1) & 0xff) << 16) | + ((memReadByte(addr+2) & 0xff) << 8) | + (memReadByte(addr+3) & 0xff); + } + + public void memWriteByte(int addr, byte val) { + memory[addr] = val; + } + + public void memWriteInt(int addr, int val) { + memWriteByte(addr ,(byte)(0xff & (val >> 24))); + memWriteByte(addr+1,(byte)(0xff & (val >> 16))); + memWriteByte(addr+2,(byte)(0xff & (val >> 8))); + memWriteByte(addr+3,(byte)(0xff & val)); + } + +} \ No newline at end of file
edgarjs/instachrome
29f10ce0c4cf1b87456911caf499be0c408c6177
Add MIT license
diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..5a4f33d --- /dev/null +++ b/LICENSE @@ -0,0 +1,7 @@ +Copyright (C) 2010-2012 Edgar J. Suarez + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
edgarjs/instachrome
bef9730ef492300e2945703d5a1dceb74eabd497
Authenticate with xAuth.
diff --git a/javascripts/instapaper.api.js b/javascripts/instapaper.api.js new file mode 100644 index 0000000..e835fa4 --- /dev/null +++ b/javascripts/instapaper.api.js @@ -0,0 +1,2 @@ +Instapaper.Api = new AjaxRequest('https://www.instapaper.com/api/1'); + diff --git a/javascripts/instapaper.auth.js b/javascripts/instapaper.auth.js new file mode 100644 index 0000000..fb93239 --- /dev/null +++ b/javascripts/instapaper.auth.js @@ -0,0 +1,71 @@ +Instapaper.Auth = new function (){ + var consumerKey = 'kNfh6BSVMURjOGrYN7a0jdIyPxOwqujdtJpvC5ub6Ov74YNcic', + consumerSecret = 'KxjIrl2Lgo6yzo2WEqGqOkzttEsEf4tiido5eF85VGIwRVyuKo'; + + var getUserInfo = function (username, password) { + var xhr = Instapaper.Api.get('/account/verify_credentials', { + async: false, + query: { + username: username, + password: password + } + }); + return JSON.parse(xhr.responseText)[0]; + }; + + var verifyCredentials = function (username, password) { + return getUserInfo(username, password).type == 'user'; + }; + + var getAccessToken = function (username, password) { + var userInfo = getUserInfo(username, password); + if(userInfo.type != 'user') { + return userInfo.message; + } + + var url = 'https://www.instapaper.com/api/1/oauth/access_token', + accessor = { + consumerKey: consumerKey, + consumerSecret: consumerSecret + }, + parameters = { + x_auth_username: username, + x_auth_password: password, + x_auth_mode: 'client_auth' + }, + message = { + action: url, + method: 'POST', + parameters: $.extend({}, parameters) + }; + OAuth.completeRequest(message, accessor); + + var xhr = Instapaper.Api.post('/oauth/access_token', { + async: false, + body: OAuth.formEncode(parameters), + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + 'Authorization': OAuth.getAuthorizationHeader(url, message.parameters) + } + }); + if(xhr.status == 200) { + var response = xhr.responseText.split('&'), + data = {}; + for (var i = 0; i < response.length; i++) { + var param = response[i].split('='); + data[param[0]] = param[1]; + } + data.user_id = userInfo.user_id; + data.username = userInfo.username; + data.subscription_is_active = userInfo.subscription_is_active == '1'; + return data; + } else { + throw("Invalid response. Code: " + xhr.status); + } + }; + + return { + verifyCredentials: verifyCredentials, + getAccessToken: getAccessToken + }; +}; diff --git a/javascripts/instapaper.js b/javascripts/instapaper.js new file mode 100644 index 0000000..5fb5150 --- /dev/null +++ b/javascripts/instapaper.js @@ -0,0 +1,2 @@ +var Instapaper = {}; + diff --git a/javascripts/lib/ajaxRequest.js b/javascripts/lib/ajaxRequest.js new file mode 100644 index 0000000..0cc6ba0 --- /dev/null +++ b/javascripts/lib/ajaxRequest.js @@ -0,0 +1,53 @@ +/* + * This is a simple wrapper for XHR calls. + * Nothing fancy, only for the needs of this chrome extension + * and other uses it may serve. + * + * Author: Edgar J. Suarez + * License: MIT + */ +var AjaxRequest = function (base_uri) { + this.base_uri = base_uri; + + this.post = function (path, options, callback) { + return this.request('POST', path, options, callback); + }; + + this.get = function (path, options, callback) { + return this.request('GET', path, options, callback); + }; + + this.request = function (method, path, options, callback) { + options = options || {}; + options.async == undefined && (options.async = true); + var xhr = new XMLHttpRequest(), + url = this.base_uri + path; + + xhr.onreadystatechange = function () { + if(xhr.readyState == 4 && xhr.status == 200 && typeof callback == 'function') { + callback(xhr.responseText); + } + }; + if(options.query) { + url += '?' + this._parseQuery(options.query); + } + xhr.open(method, url, options.async); + this._setHeaders(xhr, options.headers); + xhr.send(options.body); + return xhr; + }; + + this._parseQuery = function (query) { + return (query.constructor.name == 'Object' ? $.param(query) : query); + }; + + this._setHeaders = function (xhr, headers) { + if(headers && headers.constructor.name == 'Object') { + for (var header in headers) { + if(headers.hasOwnProperty(header)) { + xhr.setRequestHeader(header, headers[header]); + } + } + } + }; +}; diff --git a/javascripts/elastic.js b/javascripts/lib/elastic.js similarity index 100% rename from javascripts/elastic.js rename to javascripts/lib/elastic.js diff --git a/javascripts/lib/oauth.js b/javascripts/lib/oauth.js new file mode 100644 index 0000000..df15949 --- /dev/null +++ b/javascripts/lib/oauth.js @@ -0,0 +1,551 @@ +/* + * Copyright 2008 Netflix, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* Here's some JavaScript software for implementing OAuth. + + This isn't as useful as you might hope. OAuth is based around + allowing tools and websites to talk to each other. However, + JavaScript running in web browsers is hampered by security + restrictions that prevent code running on one website from + accessing data stored or served on another. + + Before you start hacking, make sure you understand the limitations + posed by cross-domain XMLHttpRequest. + + On the bright side, some platforms use JavaScript as their + language, but enable the programmer to access other web sites. + Examples include Google Gadgets, and Microsoft Vista Sidebar. + For those platforms, this library should come in handy. +*/ + +// The HMAC-SHA1 signature method calls b64_hmac_sha1, defined by +// http://pajhome.org.uk/crypt/md5/sha1.js + +/* An OAuth message is represented as an object like this: + {method: "GET", action: "http://server.com/path", parameters: ...} + + The parameters may be either a map {name: value, name2: value2} + or an Array of name-value pairs [[name, value], [name2, value2]]. + The latter representation is more powerful: it supports parameters + in a specific sequence, or several parameters with the same name; + for example [["a", 1], ["b", 2], ["a", 3]]. + + Parameter names and values are NOT percent-encoded in an object. + They must be encoded before transmission and decoded after reception. + For example, this message object: + {method: "GET", action: "http://server/path", parameters: {p: "x y"}} + ... can be transmitted as an HTTP request that begins: + GET /path?p=x%20y HTTP/1.0 + (This isn't a valid OAuth request, since it lacks a signature etc.) + Note that the object "x y" is transmitted as x%20y. To encode + parameters, you can call OAuth.addToURL, OAuth.formEncode or + OAuth.getAuthorization. + + This message object model harmonizes with the browser object model for + input elements of an form, whose value property isn't percent encoded. + The browser encodes each value before transmitting it. For example, + see consumer.setInputs in example/consumer.js. + */ + +/* This script needs to know what time it is. By default, it uses the local + clock (new Date), which is apt to be inaccurate in browsers. To do + better, you can load this script from a URL whose query string contains + an oauth_timestamp parameter, whose value is a current Unix timestamp. + For example, when generating the enclosing document using PHP: + + <script src="oauth.js?oauth_timestamp=<?=time()?>" ... + + Another option is to call OAuth.correctTimestamp with a Unix timestamp. + */ + +var OAuth; if (OAuth == null) OAuth = {}; + +OAuth.setProperties = function setProperties(into, from) { + if (into != null && from != null) { + for (var key in from) { + into[key] = from[key]; + } + } + return into; +} + +OAuth.setProperties(OAuth, // utility functions +{ + percentEncode: function percentEncode(s) { + if (s == null) { + return ""; + } + if (s instanceof Array) { + var e = ""; + for (var i = 0; i < s.length; ++s) { + if (e != "") e += '&'; + e += OAuth.percentEncode(s[i]); + } + return e; + } + s = encodeURIComponent(s); + // Now replace the values which encodeURIComponent doesn't do + // encodeURIComponent ignores: - _ . ! ~ * ' ( ) + // OAuth dictates the only ones you can ignore are: - _ . ~ + // Source: http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Functions:encodeURIComponent + s = s.replace(/\!/g, "%21"); + s = s.replace(/\*/g, "%2A"); + s = s.replace(/\'/g, "%27"); + s = s.replace(/\(/g, "%28"); + s = s.replace(/\)/g, "%29"); + return s; + } +, + decodePercent: function decodePercent(s) { + if (s != null) { + // Handle application/x-www-form-urlencoded, which is defined by + // http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.1 + s = s.replace(/\+/g, " "); + } + return decodeURIComponent(s); + } +, + /** Convert the given parameters to an Array of name-value pairs. */ + getParameterList: function getParameterList(parameters) { + if (parameters == null) { + return []; + } + if (typeof parameters != "object") { + return OAuth.decodeForm(parameters + ""); + } + if (parameters instanceof Array) { + return parameters; + } + var list = []; + for (var p in parameters) { + list.push([p, parameters[p]]); + } + return list; + } +, + /** Convert the given parameters to a map from name to value. */ + getParameterMap: function getParameterMap(parameters) { + if (parameters == null) { + return {}; + } + if (typeof parameters != "object") { + return OAuth.getParameterMap(OAuth.decodeForm(parameters + "")); + } + if (parameters instanceof Array) { + var map = {}; + for (var p = 0; p < parameters.length; ++p) { + var key = parameters[p][0]; + if (map[key] === undefined) { // first value wins + map[key] = parameters[p][1]; + } + } + return map; + } + return parameters; + } +, + getParameter: function getParameter(parameters, name) { + if (parameters instanceof Array) { + for (var p = 0; p < parameters.length; ++p) { + if (parameters[p][0] == name) { + return parameters[p][1]; // first value wins + } + } + } else { + return OAuth.getParameterMap(parameters)[name]; + } + return null; + } +, + formEncode: function formEncode(parameters) { + var form = ""; + var list = OAuth.getParameterList(parameters); + for (var p = 0; p < list.length; ++p) { + var value = list[p][1]; + if (value == null) value = ""; + if (form != "") form += '&'; + form += OAuth.percentEncode(list[p][0]) + +'='+ OAuth.percentEncode(value); + } + return form; + } +, + decodeForm: function decodeForm(form) { + var list = []; + var nvps = form.split('&'); + for (var n = 0; n < nvps.length; ++n) { + var nvp = nvps[n]; + if (nvp == "") { + continue; + } + var equals = nvp.indexOf('='); + var name; + var value; + if (equals < 0) { + name = OAuth.decodePercent(nvp); + value = null; + } else { + name = OAuth.decodePercent(nvp.substring(0, equals)); + value = OAuth.decodePercent(nvp.substring(equals + 1)); + } + list.push([name, value]); + } + return list; + } +, + setParameter: function setParameter(message, name, value) { + var parameters = message.parameters; + if (parameters instanceof Array) { + for (var p = 0; p < parameters.length; ++p) { + if (parameters[p][0] == name) { + if (value === undefined) { + parameters.splice(p, 1); + } else { + parameters[p][1] = value; + value = undefined; + } + } + } + if (value !== undefined) { + parameters.push([name, value]); + } + } else { + parameters = OAuth.getParameterMap(parameters); + parameters[name] = value; + message.parameters = parameters; + } + } +, + setParameters: function setParameters(message, parameters) { + var list = OAuth.getParameterList(parameters); + for (var i = 0; i < list.length; ++i) { + OAuth.setParameter(message, list[i][0], list[i][1]); + } + } +, + /** Fill in parameters to help construct a request message. + This function doesn't fill in every parameter. + The accessor object should be like: + {consumerKey:'foo', consumerSecret:'bar', accessorSecret:'nurn', token:'krelm', tokenSecret:'blah'} + The accessorSecret property is optional. + */ + completeRequest: function completeRequest(message, accessor) { + if (message.method == null) { + message.method = "GET"; + } + var map = OAuth.getParameterMap(message.parameters); + if (map.oauth_consumer_key == null) { + OAuth.setParameter(message, "oauth_consumer_key", accessor.consumerKey || ""); + } + if (map.oauth_token == null && accessor.token != null) { + OAuth.setParameter(message, "oauth_token", accessor.token); + } + if (map.oauth_version == null) { + OAuth.setParameter(message, "oauth_version", "1.0"); + } + if (map.oauth_timestamp == null) { + OAuth.setParameter(message, "oauth_timestamp", OAuth.timestamp()); + } + if (map.oauth_nonce == null) { + OAuth.setParameter(message, "oauth_nonce", OAuth.nonce(6)); + } + OAuth.SignatureMethod.sign(message, accessor); + } +, + setTimestampAndNonce: function setTimestampAndNonce(message) { + OAuth.setParameter(message, "oauth_timestamp", OAuth.timestamp()); + OAuth.setParameter(message, "oauth_nonce", OAuth.nonce(6)); + } +, + addToURL: function addToURL(url, parameters) { + newURL = url; + if (parameters != null) { + var toAdd = OAuth.formEncode(parameters); + if (toAdd.length > 0) { + var q = url.indexOf('?'); + if (q < 0) newURL += '?'; + else newURL += '&'; + newURL += toAdd; + } + } + return newURL; + } +, + /** Construct the value of the Authorization header for an HTTP request. */ + getAuthorizationHeader: function getAuthorizationHeader(realm, parameters) { + var header = 'OAuth realm="' + OAuth.percentEncode(realm) + '"'; + var list = OAuth.getParameterList(parameters); + for (var p = 0; p < list.length; ++p) { + var parameter = list[p]; + var name = parameter[0]; + if (name.indexOf("oauth_") == 0) { + header += ', ' + OAuth.percentEncode(name) + '="' + OAuth.percentEncode(parameter[1]) + '"'; + } + } + return header; + } +, + /** Correct the time using a parameter from the URL from which the last script was loaded. */ + correctTimestampFromSrc: function correctTimestampFromSrc(parameterName) { + parameterName = parameterName || "oauth_timestamp"; + var scripts = document.getElementsByTagName('script'); + if (scripts == null || !scripts.length) return; + var src = scripts[scripts.length-1].src; + if (!src) return; + var q = src.indexOf("?"); + if (q < 0) return; + parameters = OAuth.getParameterMap(OAuth.decodeForm(src.substring(q+1))); + var t = parameters[parameterName]; + if (t == null) return; + OAuth.correctTimestamp(t); + } +, + /** Generate timestamps starting with the given value. */ + correctTimestamp: function correctTimestamp(timestamp) { + OAuth.timeCorrectionMsec = (timestamp * 1000) - (new Date()).getTime(); + } +, + /** The difference between the correct time and my clock. */ + timeCorrectionMsec: 0 +, + timestamp: function timestamp() { + var t = (new Date()).getTime() + OAuth.timeCorrectionMsec; + return Math.floor(t / 1000); + } +, + nonce: function nonce(length) { + var chars = OAuth.nonce.CHARS; + var result = ""; + for (var i = 0; i < length; ++i) { + var rnum = Math.floor(Math.random() * chars.length); + result += chars.substring(rnum, rnum+1); + } + return result; + } +}); + +OAuth.nonce.CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz"; + +/** Define a constructor function, + without causing trouble to anyone who was using it as a namespace. + That is, if parent[name] already existed and had properties, + copy those properties into the new constructor. + */ +OAuth.declareClass = function declareClass(parent, name, newConstructor) { + var previous = parent[name]; + parent[name] = newConstructor; + if (newConstructor != null && previous != null) { + for (var key in previous) { + if (key != "prototype") { + newConstructor[key] = previous[key]; + } + } + } + return newConstructor; +} + +/** An abstract algorithm for signing messages. */ +OAuth.declareClass(OAuth, "SignatureMethod", function OAuthSignatureMethod(){}); + +OAuth.setProperties(OAuth.SignatureMethod.prototype, // instance members +{ + /** Add a signature to the message. */ + sign: function sign(message) { + var baseString = OAuth.SignatureMethod.getBaseString(message); + var signature = this.getSignature(baseString); + OAuth.setParameter(message, "oauth_signature", signature); + return signature; // just in case someone's interested + } +, + /** Set the key string for signing. */ + initialize: function initialize(name, accessor) { + var consumerSecret; + if (accessor.accessorSecret != null + && name.length > 9 + && name.substring(name.length-9) == "-Accessor") + { + consumerSecret = accessor.accessorSecret; + } else { + consumerSecret = accessor.consumerSecret; + } + this.key = OAuth.percentEncode(consumerSecret) + +"&"+ OAuth.percentEncode(accessor.tokenSecret); + } +}); + +/* SignatureMethod expects an accessor object to be like this: + {tokenSecret: "lakjsdflkj...", consumerSecret: "QOUEWRI..", accessorSecret: "xcmvzc..."} + The accessorSecret property is optional. + */ +// Class members: +OAuth.setProperties(OAuth.SignatureMethod, // class members +{ + sign: function sign(message, accessor) { + var name = OAuth.getParameterMap(message.parameters).oauth_signature_method; + if (name == null || name == "") { + name = "HMAC-SHA1"; + OAuth.setParameter(message, "oauth_signature_method", name); + } + OAuth.SignatureMethod.newMethod(name, accessor).sign(message); + } +, + /** Instantiate a SignatureMethod for the given method name. */ + newMethod: function newMethod(name, accessor) { + var impl = OAuth.SignatureMethod.REGISTERED[name]; + if (impl != null) { + var method = new impl(); + method.initialize(name, accessor); + return method; + } + var err = new Error("signature_method_rejected"); + var acceptable = ""; + for (var r in OAuth.SignatureMethod.REGISTERED) { + if (acceptable != "") acceptable += '&'; + acceptable += OAuth.percentEncode(r); + } + err.oauth_acceptable_signature_methods = acceptable; + throw err; + } +, + /** A map from signature method name to constructor. */ + REGISTERED : {} +, + /** Subsequently, the given constructor will be used for the named methods. + The constructor will be called with no parameters. + The resulting object should usually implement getSignature(baseString). + You can easily define such a constructor by calling makeSubclass, below. + */ + registerMethodClass: function registerMethodClass(names, classConstructor) { + for (var n = 0; n < names.length; ++n) { + OAuth.SignatureMethod.REGISTERED[names[n]] = classConstructor; + } + } +, + /** Create a subclass of OAuth.SignatureMethod, with the given getSignature function. */ + makeSubclass: function makeSubclass(getSignatureFunction) { + var superClass = OAuth.SignatureMethod; + var subClass = function() { + superClass.call(this); + }; + subClass.prototype = new superClass(); + // Delete instance variables from prototype: + // delete subclass.prototype... There aren't any. + subClass.prototype.getSignature = getSignatureFunction; + subClass.prototype.constructor = subClass; + return subClass; + } +, + getBaseString: function getBaseString(message) { + var URL = message.action; + var q = URL.indexOf('?'); + var parameters; + if (q < 0) { + parameters = message.parameters; + } else { + // Combine the URL query string with the other parameters: + parameters = OAuth.decodeForm(URL.substring(q + 1)); + var toAdd = OAuth.getParameterList(message.parameters); + for (var a = 0; a < toAdd.length; ++a) { + parameters.push(toAdd[a]); + } + } + return OAuth.percentEncode(message.method.toUpperCase()) + +'&'+ OAuth.percentEncode(OAuth.SignatureMethod.normalizeUrl(URL)) + +'&'+ OAuth.percentEncode(OAuth.SignatureMethod.normalizeParameters(parameters)); + } +, + normalizeUrl: function normalizeUrl(url) { + var uri = OAuth.SignatureMethod.parseUri(url); + var scheme = uri.protocol.toLowerCase(); + var authority = uri.authority.toLowerCase(); + var dropPort = (scheme == "http" && uri.port == 80) + || (scheme == "https" && uri.port == 443); + if (dropPort) { + // find the last : in the authority + var index = authority.lastIndexOf(":"); + if (index >= 0) { + authority = authority.substring(0, index); + } + } + var path = uri.path; + if (!path) { + path = "/"; // conforms to RFC 2616 section 3.2.2 + } + // we know that there is no query and no fragment here. + return scheme + "://" + authority + path; + } +, + parseUri: function parseUri (str) { + /* This function was adapted from parseUri 1.2.1 + http://stevenlevithan.com/demo/parseuri/js/assets/parseuri.js + */ + var o = {key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"], + parser: {strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@\/]*):?([^:@\/]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/ }}; + var m = o.parser.strict.exec(str); + var uri = {}; + var i = 14; + while (i--) uri[o.key[i]] = m[i] || ""; + return uri; + } +, + normalizeParameters: function normalizeParameters(parameters) { + if (parameters == null) { + return ""; + } + var list = OAuth.getParameterList(parameters); + var sortable = []; + for (var p = 0; p < list.length; ++p) { + var nvp = list[p]; + if (nvp[0] != "oauth_signature") { + sortable.push([ OAuth.percentEncode(nvp[0]) + + " " // because it comes before any character that can appear in a percentEncoded string. + + OAuth.percentEncode(nvp[1]) + , nvp]); + } + } + sortable.sort(function(a,b) { + if (a[0] < b[0]) return -1; + if (a[0] > b[0]) return 1; + return 0; + }); + var sorted = []; + for (var s = 0; s < sortable.length; ++s) { + sorted.push(sortable[s][1]); + } + return OAuth.formEncode(sorted); + } +}); + +OAuth.SignatureMethod.registerMethodClass(["PLAINTEXT", "PLAINTEXT-Accessor"], + OAuth.SignatureMethod.makeSubclass( + function getSignature(baseString) { + return this.key; + } + )); + +OAuth.SignatureMethod.registerMethodClass(["HMAC-SHA1", "HMAC-SHA1-Accessor"], + OAuth.SignatureMethod.makeSubclass( + function getSignature(baseString) { + b64pad = '='; + var signature = b64_hmac_sha1(this.key, baseString); + return signature; + } + )); + +try { + OAuth.correctTimestampFromSrc(); +} catch(e) { +} diff --git a/javascripts/lib/sha1.js b/javascripts/lib/sha1.js new file mode 100644 index 0000000..11014f8 --- /dev/null +++ b/javascripts/lib/sha1.js @@ -0,0 +1,202 @@ +/* + * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined + * in FIPS PUB 180-1 + * Version 2.1a Copyright Paul Johnston 2000 - 2002. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for details. + */ + +/* + * Configurable variables. You may need to tweak these to be compatible with + * the server-side, but the defaults work in most cases. + */ +var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */ +var b64pad = ""; /* base-64 pad character. "=" for strict RFC compliance */ +var chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode */ + +/* + * These are the functions you'll usually want to call + * They take string arguments and return either hex or base-64 encoded strings + */ +function hex_sha1(s){return binb2hex(core_sha1(str2binb(s),s.length * chrsz));} +function b64_sha1(s){return binb2b64(core_sha1(str2binb(s),s.length * chrsz));} +function str_sha1(s){return binb2str(core_sha1(str2binb(s),s.length * chrsz));} +function hex_hmac_sha1(key, data){ return binb2hex(core_hmac_sha1(key, data));} +function b64_hmac_sha1(key, data){ return binb2b64(core_hmac_sha1(key, data));} +function str_hmac_sha1(key, data){ return binb2str(core_hmac_sha1(key, data));} + +/* + * Perform a simple self-test to see if the VM is working + */ +function sha1_vm_test() +{ + return hex_sha1("abc") == "a9993e364706816aba3e25717850c26c9cd0d89d"; +} + +/* + * Calculate the SHA-1 of an array of big-endian words, and a bit length + */ +function core_sha1(x, len) +{ + /* append padding */ + x[len >> 5] |= 0x80 << (24 - len % 32); + x[((len + 64 >> 9) << 4) + 15] = len; + + var w = Array(80); + var a = 1732584193; + var b = -271733879; + var c = -1732584194; + var d = 271733878; + var e = -1009589776; + + for(var i = 0; i < x.length; i += 16) + { + var olda = a; + var oldb = b; + var oldc = c; + var oldd = d; + var olde = e; + + for(var j = 0; j < 80; j++) + { + if(j < 16) w[j] = x[i + j]; + else w[j] = rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1); + var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)), + safe_add(safe_add(e, w[j]), sha1_kt(j))); + e = d; + d = c; + c = rol(b, 30); + b = a; + a = t; + } + + a = safe_add(a, olda); + b = safe_add(b, oldb); + c = safe_add(c, oldc); + d = safe_add(d, oldd); + e = safe_add(e, olde); + } + return Array(a, b, c, d, e); + +} + +/* + * Perform the appropriate triplet combination function for the current + * iteration + */ +function sha1_ft(t, b, c, d) +{ + if(t < 20) return (b & c) | ((~b) & d); + if(t < 40) return b ^ c ^ d; + if(t < 60) return (b & c) | (b & d) | (c & d); + return b ^ c ^ d; +} + +/* + * Determine the appropriate additive constant for the current iteration + */ +function sha1_kt(t) +{ + return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 : + (t < 60) ? -1894007588 : -899497514; +} + +/* + * Calculate the HMAC-SHA1 of a key and some data + */ +function core_hmac_sha1(key, data) +{ + var bkey = str2binb(key); + if(bkey.length > 16) bkey = core_sha1(bkey, key.length * chrsz); + + var ipad = Array(16), opad = Array(16); + for(var i = 0; i < 16; i++) + { + ipad[i] = bkey[i] ^ 0x36363636; + opad[i] = bkey[i] ^ 0x5C5C5C5C; + } + + var hash = core_sha1(ipad.concat(str2binb(data)), 512 + data.length * chrsz); + return core_sha1(opad.concat(hash), 512 + 160); +} + +/* + * Add integers, wrapping at 2^32. This uses 16-bit operations internally + * to work around bugs in some JS interpreters. + */ +function safe_add(x, y) +{ + var lsw = (x & 0xFFFF) + (y & 0xFFFF); + var msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return (msw << 16) | (lsw & 0xFFFF); +} + +/* + * Bitwise rotate a 32-bit number to the left. + */ +function rol(num, cnt) +{ + return (num << cnt) | (num >>> (32 - cnt)); +} + +/* + * Convert an 8-bit or 16-bit string to an array of big-endian words + * In 8-bit function, characters >255 have their hi-byte silently ignored. + */ +function str2binb(str) +{ + var bin = Array(); + var mask = (1 << chrsz) - 1; + for(var i = 0; i < str.length * chrsz; i += chrsz) + bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (32 - chrsz - i%32); + return bin; +} + +/* + * Convert an array of big-endian words to a string + */ +function binb2str(bin) +{ + var str = ""; + var mask = (1 << chrsz) - 1; + for(var i = 0; i < bin.length * 32; i += chrsz) + str += String.fromCharCode((bin[i>>5] >>> (32 - chrsz - i%32)) & mask); + return str; +} + +/* + * Convert an array of big-endian words to a hex string. + */ +function binb2hex(binarray) +{ + var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef"; + var str = ""; + for(var i = 0; i < binarray.length * 4; i++) + { + str += hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8+4)) & 0xF) + + hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8 )) & 0xF); + } + return str; +} + +/* + * Convert an array of big-endian words to a base-64 string + */ +function binb2b64(binarray) +{ + var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + var str = ""; + for(var i = 0; i < binarray.length * 4; i += 3) + { + var triplet = (((binarray[i >> 2] >> 8 * (3 - i %4)) & 0xFF) << 16) + | (((binarray[i+1 >> 2] >> 8 * (3 - (i+1)%4)) & 0xFF) << 8 ) + | ((binarray[i+2 >> 2] >> 8 * (3 - (i+2)%4)) & 0xFF); + for(var j = 0; j < 4; j++) + { + if(i * 8 + j * 6 > binarray.length * 32) str += b64pad; + else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F); + } + } + return str; +} diff --git a/javascripts/options.js b/javascripts/options.js index a5fedb7..4da6c43 100644 --- a/javascripts/options.js +++ b/javascripts/options.js @@ -1,194 +1,206 @@ (function($) { $.flash = function(msg) { - $('.flash').text(msg).fadeIn('fast'); + $('.flash').html(msg).fadeIn('fast'); }; })(jQuery); var Options = function() { var values = { username: null, password: null, show_popup: '1', auto_close: false, badge_style: 0, shortcut: { keyCode: 83, altKey: true, ctrlKey: false, shiftKey: true }, cx_read_later: '1', cx_text_view: '0', cx_unread: '0', cx_starred: '0', cx_archive: '0' }; var ui = { username: $('input#username'), password: $('input#password'), show_popup: $('input#show_popup'), auto_close: $('input#auto_close'), badge_style: $('select#badge_style'), shortcut: $('input#shortcut'), cx_read_later: $('input#cx_read_later'), cx_text_view: $('input#cx_text_view'), cx_unread: $('input#cx_unread'), cx_starred: $('input#cx_starred'), cx_archive: $('input#cx_archive') }; var dbOrDefault = function(db_key) { return $.db(db_key) || values[db_key]; }; - var authenticateCredentials = function() { - var xhr = new XMLHttpRequest(); - var username = encodeURIComponent(ui.username.val()); - var password = encodeURIComponent(ui.password.val()); - xhr.onreadystatechange = function(response) { - if(response.srcElement && response.srcElement.readyState == 4) { - $('.column.label.auth').show('fast').removeClass('ok error'); - if(response.srcElement.status == 200) { - $('.column.label.auth').addClass('ok').text('Your credentials are valid.'); - getRSSfeed(username, password); - } else { - $('.column.label.auth').addClass('error').text('Your username or password is incorrect. Please double check them.'); - } - } + var verifyCredentials = function() { + $('.column.label.auth').show('fast').removeClass('ok error'); + if(Instapaper.Auth.verifyCredentials(ui.username.val(), ui.password.val())) { + $('.column.label.auth').addClass('ok').text('Your credentials are valid.'); + // getRSSfeed(username, password); + } else { + $('.column.label.auth').addClass('error').text('Your username or password is incorrect. Please double check them.'); } - xhr.open("GET", 'https://www.instapaper.com/api/authenticate?username=' + username + '&password=' + password, true); - xhr.send(); }; var getRSSfeed = function(user, pass) { var xhr = new XMLHttpRequest(); var params='username=' + user + '&password=' + pass; xhr.onreadystatechange = function() { if(xhr.readyState == 4 && xhr.status == 200) { var xhr2 = new XMLHttpRequest(); xhr2.onreadystatechange = function() { if(xhr2.readyState == 4 && xhr2.status == 200) { $.db('rssfeed', /"(http:\/\/www\.instapaper\.com\/rss\/[^"]*)"/.exec( xhr2.responseText)[1]); } }; xhr2.open('GET', 'https://www.instapaper.com/u', true); xhr2.send(); } } xhr.open('POST', 'https://www.instapaper.com/user/login', true); xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); xhr.send(params); }; - ui.username.bind('change', authenticateCredentials); - ui.password.bind('change', authenticateCredentials); + ui.username.bind('change', verifyCredentials); + ui.password.bind('change', verifyCredentials); return { humanizeKeystrokes: function(e) { var key = "", special = ""; if(e.keyCode >= 65 && e.keyCode <= 90) { key = String.fromCharCode(e.keyCode); if (e.ctrlKey) { special += "Ctrl + "; } if (e.altKey) { special += "Alt + "; } if (e.shiftKey) { special += "Shift + "; } } return special + key; }, restore: function() { if (location.hash === '#setup') { $.flash('Enter your Instapaper credentials in order to save an URL.'); } ui.username.val(dbOrDefault('username')); - ui.password.val(dbOrDefault('password')); if (dbOrDefault('show_popup') === '1') { ui.show_popup.attr('checked', true); } if (dbOrDefault('auto_close') === '1') { ui.auto_close.attr('checked', true); } if (dbOrDefault('cx_read_later') === '1') { ui.cx_read_later.attr('checked', true); } if (dbOrDefault('cx_text_view') === '1') { ui.cx_text_view.attr('checked', true); } if (dbOrDefault('cx_unread') === '1') { ui.cx_unread.attr('checked', true); } if (dbOrDefault('cx_starred') === '1') { ui.cx_starred.attr('checked', true); } if (dbOrDefault('cx_archive') === '1') { ui.cx_archive.attr('checked', true); } ui.badge_style.val(dbOrDefault('badge_style')); ui.shortcut.val(this.humanizeKeystrokes(dbOrDefault('shortcut'))) .data('keys', dbOrDefault('shortcut')); ui.badge_style.change(function () { if(parseInt($(this).val()) == 3) { getRSSfeed(ui.username.val(), ui.password.val()); } }); }, save: function() { - $.db('username', ui.username.val()); - $.db('password', ui.password.val()); - $.db('show_popup', ui.show_popup.is(':checked') ? '1': '0'); - $.db('auto_close', ui.auto_close.is(':checked') ? '1': '0'); - $.db('cx_read_later', ui.cx_read_later.is(':checked') ? '1': '0'); - $.db('cx_text_view', ui.cx_text_view.is(':checked') ? '1': '0'); - $.db('cx_unread', ui.cx_unread.is(':checked') ? '1': '0'); - $.db('cx_starred', ui.cx_starred.is(':checked') ? '1': '0'); - $.db('cx_archive', ui.cx_archive.is(':checked') ? '1': '0'); - $.db('badge_style', ui.badge_style.val()); - $.db('shortcut', ui.shortcut.data('keys')); - - $.flash('Options saved successfully!'); + if(!$.db('oauth_token') || $.trim(ui.password.val()).length > 0) { + var accessToken = Instapaper.Auth.getAccessToken( + ui.username.val(), + ui.password.val() + ); + } else { + var accessToken = { + oauth_token: $.db('oauth_token'), + oauth_token_secret: $.db('oauth_token_secret'), + user_id: $.db('user_id'), + username: $.db('username'), + subscription_is_active: true + }; + } + if(accessToken) { + $.db('oauth_token', accessToken.oauth_token); + $.db('oauth_token_secret', accessToken.oauth_token_secret); + $.db('user_id', accessToken.user_id); + $.db('username', accessToken.username); + $.db('show_popup', ui.show_popup.is(':checked') ? '1': '0'); + $.db('auto_close', ui.auto_close.is(':checked') ? '1': '0'); + $.db('cx_read_later', ui.cx_read_later.is(':checked') ? '1': '0'); + $.db('cx_text_view', ui.cx_text_view.is(':checked') ? '1': '0'); + $.db('cx_unread', ui.cx_unread.is(':checked') ? '1': '0'); + $.db('cx_starred', ui.cx_starred.is(':checked') ? '1': '0'); + $.db('cx_archive', ui.cx_archive.is(':checked') ? '1': '0'); + $.db('badge_style', ui.badge_style.val()); + $.db('shortcut', ui.shortcut.data('keys')); + + if(accessToken.subscription_is_active) { + $.flash('Options saved successfully!'); + } else { + $.flash("You don't have a paid subscription at Instapaper. " + + "Some features requires to have a paid subscription. " + + '<a href="http://blog.instapaper.com/post/3208433429">Read more</a>'); + } + } else { + $.flash('There was an error authenticating with Instapaper! Please check your credentials.'); + } } }; }; $(function() { var o = new Options(); o.restore(); - $('.flash').click(function() { - $(this).fadeOut('slow'); - return false; - }); - $('.close').click(function() { window.close(); }); $('form.options').submit(function() { o.save(); return false; }); $('#shortcut').keydown(function(e) { $(this).val(o.humanizeKeystrokes(e)).data('keys', { ctrlKey: e.ctrlKey, altKey: e.altKey, shiftKey: e.shiftKey, keyCode: e.which }); return false; }); }); + diff --git a/manifest.json b/manifest.json index c9369fe..5dc1f24 100644 --- a/manifest.json +++ b/manifest.json @@ -1,35 +1,35 @@ { - "name": "Instachrome", - "version": "1.5.1", + "name": "Instachrome 2", + "version": "2.0", "description": "Save your URLs to Instapaper", "options_page": "options.html", "background_page": "background.html", "content_scripts": [{ "matches": ["http://*/*", "https://*/*"], "js": ["javascripts/keyboard.js"], "run_at": "document_start" }, { "matches": ["http://www.google.com/reader/*"], "js": ["javascripts/greader.js"], "run_at": "document_end" }], "browser_action": { "default_icon": "images/default.png", "default_title": "Save to Instapaper", "popup": "popup.html" }, "icons": { "16": "images/icon/16.png", "32": "images/icon/32.png", "48": "images/icon/48.png", "128": "images/icon/128.png" }, "permissions": [ "contextMenus", "tabs", "http://ajax.googleapis.com/ajax/libs/jquery/**/*", "http://www.instapaper.com/api/", "https://www.instapaper.com/api/", "http://www.google.com/reader/*" ] } diff --git a/options.html b/options.html index 1b37880..786032a 100644 --- a/options.html +++ b/options.html @@ -1,164 +1,167 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta charset="utf-8" /> <title>Instachrome Options</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> - <script type="text/javascript" src="javascripts/elastic.js"></script> + <script type="text/javascript" src="javascripts/lib/elastic.js"></script> + <script type="text/javascript" src="javascripts/lib/sha1.js"></script> + <script type="text/javascript" src="javascripts/lib/oauth.js"></script> + <script type="text/javascript" src="javascripts/lib/ajaxRequest.js"></script> <script type="text/javascript" src="javascripts/app.js"></script> + <script type="text/javascript" src="javascripts/instapaper.js"></script> + <script type="text/javascript" src="javascripts/instapaper.auth.js"></script> + <script type="text/javascript" src="javascripts/instapaper.api.js"></script> <script type="text/javascript" src="javascripts/options.js"></script> <link href="stylesheets/elastic.css" rel="stylesheet" type="text/css" /> <link href="stylesheets/options.css" rel="stylesheet" type="text/css" /> </head> <body> <a href="http://pledgie.com/campaigns/9023" class="ribbon left"></a> <a href="http://github.com/edgarjs/instachrome" class="ribbon right"></a> <div class="container wrapper"> <h1 class="title">Instachrome Options</h1> <div class="flash"></div> <form class="options" action="#" method="post"> <fieldset class="container set"> <legend>Instapaper credentials</legend> <div class="container pad"> <div class="unit on-2 columns same-height"> <div class="column label"> - <label for="username" class="vertical-center">Username:</label> + <label for="username">Email:</label> + <div class="description">(Username is now your email address)</div> </div> <div class="column"> <input type="text" class="text" spellcheck="false" name="username" id="username" /> </div> <div class="column label"> - <label for="password">Password:</label> - <div class="description">(If you have one)</div> + <label for="password" class="vertical-center">Password:</label> </div> <div class="column"> <input type="password" class="text" name="password" id="password" /> </div> <div class="column label span-2 auth"> Your username or password is incorrect. Please double check them. </div> - - <div class="column label span-2"> - <a href="http://www.instapaper.com/user/register" class="vertical-center description">Get a free account</a> - </div> </div> </div> </fieldset> <fieldset class="container set"> <legend>Extras</legend> <div class="container pad"> <div class="unit on-2 columns same-height"> <div class="column label"> <label for="show_popup" class="vertical-center">Show popup:</label> </div> <div class="column"> <input type="checkbox" name="show_popup" class="vertical-center" id="show_popup" value="1" /> </div> <div class="column label"> <label for="auto_close">Auto close:</label> <div class="description">(Close tab after saved)</div> </div> <div class="column"> <input type="checkbox" name="auto_close" class="vertical-center" id="auto_close" value="1" /> </div> <div class="column label"> <label for="badge_style" class="vertical-center">Badge style:</label> </div> <div class="column"> <select name="badge_style" id="badge_style"> <option value="0">Text</option> <option value="1">Tick/Circle/Cross Icons</option> <option value="2">Chromed icons</option> <option value="3">Text + unread count</option> </select> </div> <div class="column label"> <label for="shortcut" class="vertical-center">Keyboard shortcut:</label> <div class="description">(Beta - Not all shortcuts may work)</div> </div> <div class="column"> <input type="text" name="shortcut" id="shortcut" class="text" /> </div> </div> </div> </fieldset> <fieldset class="container set"> <legend>Context Menus</legend> <div class="container pad"> <div class="unit on-1 columns"> <div class="column label"> <div class="description">You'll need to restart the browser for context menus to take effect.</p> </div> </div> <div class="unit on-2 columns same-height"> <div class="column label"> - <label for="cx_read_later" class="vertical-center">Read Later</label> + <label for="cx_read_later">Read Later</label> + <div class="description">This item appears only when clicking on links</div> </div> <div class="column"> <input type="checkbox" name="cx_read_later" class="vertical-center" id="cx_read_later" value="1" /> </div> <div class="column label"> <label for="cx_text_view" class="vertical-center">Text view</label> </div> <div class="column"> <input type="checkbox" name="cx_text_view" class="vertical-center" id="cx_text_view" value="1" /> </div> <div class="column label"> <label for="cx_unread" class="vertical-center">Go to unread</label> </div> <div class="column"> <input type="checkbox" name="cx_unread" class="vertical-center" id="cx_unread" value="1" /> </div> <div class="column label"> <label for="cx_starred" class="vertical-center">Go to starred</label> </div> <div class="column"> <input type="checkbox" name="cx_starred" class="vertical-center" id="cx_starred" value="1" /> </div> <div class="column label"> <label for="cx_archive" class="vertical-center">Go to archive</label> </div> <div class="column"> <input type="checkbox" name="cx_archive" class="vertical-center" id="cx_archive" value="1" /> </div> </div> </div> </fieldset> <input type="submit" class="button" value="Save" /> or <a href="#" class="close">Close</a> </form> <div class="container footer"> <p> by <a href="http://edgarjs.mx">Edgar J. Suárez</a> | <a href="http://twitter.com/edgarjs">Twitter</a> | <a href="https://chrome.google.com/extensions/detail/fldildgghjoohccppflaohodcnmlacpb">Extension page</a> | <a href="http://instapaper.com">Instapaper</a> <br /> This page is powered by <a href="http://elasticss.com">Elastic CSS</a> | Icons by <a href="http://famfamfam.com">famfamfam.com</a> </p> </div> </div> </body> </html> diff --git a/stylesheets/options.css b/stylesheets/options.css index 309a7d3..c5ac5a2 100644 --- a/stylesheets/options.css +++ b/stylesheets/options.css @@ -1,100 +1,99 @@ a { color: #DC8145; } a.ribbon { top: 0; position: absolute; border: 0; display: block; width: 149px; height: 149px; } a.ribbon.right { right: 0; background: url("../images/forkme_ribbon.png") 0 0 no-repeat; } a.ribbon.left { left: 0; background: url("../images/donation_ribbon.png") 0 0 no-repeat; } .wrapper { width: 500px; margin: 20px auto; } .flash { background: #FFFFCC; border: 1px solid #cccc00; padding: 5px 0; color: #666; text-align: center; margin: 10px 0; display: none; - cursor: pointer; } .title { font-family: "Times New Roman"; font-size: 2em; } .set { border: 1px solid #C7E2EF; border-radius: 3px; background-color: #ededed; } .set > legend { margin-left: 12px; color: #52A8CF; text-shadow: 1px 1px 1px #ccc; cursor: default; } .set > .pad { padding: 6px; } .set .column.label { text-align: center; color: #888; } .set .column.label > .description { font-size: 0.8em; } .set .column > input.text { border: 1px solid #ccc; padding: 4px; margin: 3px 0; color: #52A8CF; border-radius: 3px; } .column.label.auth { line-height: 35px; display: none; font-size: 10px; } .column.label.auth.ok { color: green; } .column.label.auth.error { color: red; } .footer { font-size: 0.8em; color: #888; text-align: center; margin-top: 10em; } .footer a { color: #333; }
edgarjs/instachrome
1f1e0abf23147bfe15d409fe6b43efcb3c75820d
fetching rss url on badge style change
diff --git a/javascripts/options.js b/javascripts/options.js index a3e8d50..a5fedb7 100644 --- a/javascripts/options.js +++ b/javascripts/options.js @@ -1,188 +1,194 @@ (function($) { $.flash = function(msg) { $('.flash').text(msg).fadeIn('fast'); }; })(jQuery); var Options = function() { var values = { username: null, password: null, show_popup: '1', auto_close: false, badge_style: 0, shortcut: { keyCode: 83, altKey: true, ctrlKey: false, shiftKey: true }, cx_read_later: '1', cx_text_view: '0', cx_unread: '0', cx_starred: '0', cx_archive: '0' }; var ui = { username: $('input#username'), password: $('input#password'), show_popup: $('input#show_popup'), auto_close: $('input#auto_close'), badge_style: $('select#badge_style'), shortcut: $('input#shortcut'), cx_read_later: $('input#cx_read_later'), cx_text_view: $('input#cx_text_view'), cx_unread: $('input#cx_unread'), cx_starred: $('input#cx_starred'), cx_archive: $('input#cx_archive') }; var dbOrDefault = function(db_key) { return $.db(db_key) || values[db_key]; }; var authenticateCredentials = function() { var xhr = new XMLHttpRequest(); var username = encodeURIComponent(ui.username.val()); var password = encodeURIComponent(ui.password.val()); xhr.onreadystatechange = function(response) { if(response.srcElement && response.srcElement.readyState == 4) { $('.column.label.auth').show('fast').removeClass('ok error'); if(response.srcElement.status == 200) { $('.column.label.auth').addClass('ok').text('Your credentials are valid.'); getRSSfeed(username, password); } else { $('.column.label.auth').addClass('error').text('Your username or password is incorrect. Please double check them.'); } } } xhr.open("GET", 'https://www.instapaper.com/api/authenticate?username=' + username + '&password=' + password, true); xhr.send(); }; var getRSSfeed = function(user, pass) { var xhr = new XMLHttpRequest(); var params='username=' + user + '&password=' + pass; xhr.onreadystatechange = function() { if(xhr.readyState == 4 && xhr.status == 200) { var xhr2 = new XMLHttpRequest(); xhr2.onreadystatechange = function() { if(xhr2.readyState == 4 && xhr2.status == 200) { $.db('rssfeed', /"(http:\/\/www\.instapaper\.com\/rss\/[^"]*)"/.exec( xhr2.responseText)[1]); } }; xhr2.open('GET', 'https://www.instapaper.com/u', true); xhr2.send(); } } xhr.open('POST', 'https://www.instapaper.com/user/login', true); xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); xhr.send(params); }; ui.username.bind('change', authenticateCredentials); ui.password.bind('change', authenticateCredentials); return { humanizeKeystrokes: function(e) { var key = "", special = ""; if(e.keyCode >= 65 && e.keyCode <= 90) { key = String.fromCharCode(e.keyCode); if (e.ctrlKey) { special += "Ctrl + "; } if (e.altKey) { special += "Alt + "; } if (e.shiftKey) { special += "Shift + "; } } return special + key; }, restore: function() { if (location.hash === '#setup') { $.flash('Enter your Instapaper credentials in order to save an URL.'); } ui.username.val(dbOrDefault('username')); ui.password.val(dbOrDefault('password')); if (dbOrDefault('show_popup') === '1') { ui.show_popup.attr('checked', true); } if (dbOrDefault('auto_close') === '1') { ui.auto_close.attr('checked', true); } if (dbOrDefault('cx_read_later') === '1') { ui.cx_read_later.attr('checked', true); } if (dbOrDefault('cx_text_view') === '1') { ui.cx_text_view.attr('checked', true); } if (dbOrDefault('cx_unread') === '1') { ui.cx_unread.attr('checked', true); } if (dbOrDefault('cx_starred') === '1') { ui.cx_starred.attr('checked', true); } if (dbOrDefault('cx_archive') === '1') { ui.cx_archive.attr('checked', true); } ui.badge_style.val(dbOrDefault('badge_style')); ui.shortcut.val(this.humanizeKeystrokes(dbOrDefault('shortcut'))) .data('keys', dbOrDefault('shortcut')); + + ui.badge_style.change(function () { + if(parseInt($(this).val()) == 3) { + getRSSfeed(ui.username.val(), ui.password.val()); + } + }); }, save: function() { $.db('username', ui.username.val()); $.db('password', ui.password.val()); $.db('show_popup', ui.show_popup.is(':checked') ? '1': '0'); $.db('auto_close', ui.auto_close.is(':checked') ? '1': '0'); $.db('cx_read_later', ui.cx_read_later.is(':checked') ? '1': '0'); $.db('cx_text_view', ui.cx_text_view.is(':checked') ? '1': '0'); $.db('cx_unread', ui.cx_unread.is(':checked') ? '1': '0'); $.db('cx_starred', ui.cx_starred.is(':checked') ? '1': '0'); $.db('cx_archive', ui.cx_archive.is(':checked') ? '1': '0'); $.db('badge_style', ui.badge_style.val()); $.db('shortcut', ui.shortcut.data('keys')); $.flash('Options saved successfully!'); } }; }; $(function() { var o = new Options(); o.restore(); $('.flash').click(function() { $(this).fadeOut('slow'); return false; }); $('.close').click(function() { window.close(); }); $('form.options').submit(function() { o.save(); return false; }); $('#shortcut').keydown(function(e) { $(this).val(o.humanizeKeystrokes(e)).data('keys', { ctrlKey: e.ctrlKey, altKey: e.altKey, shiftKey: e.shiftKey, keyCode: e.which }); return false; }); }); diff --git a/manifest.json b/manifest.json index 64add34..c9369fe 100644 --- a/manifest.json +++ b/manifest.json @@ -1,35 +1,35 @@ { "name": "Instachrome", - "version": "1.5", + "version": "1.5.1", "description": "Save your URLs to Instapaper", "options_page": "options.html", "background_page": "background.html", "content_scripts": [{ "matches": ["http://*/*", "https://*/*"], "js": ["javascripts/keyboard.js"], "run_at": "document_start" }, { "matches": ["http://www.google.com/reader/*"], "js": ["javascripts/greader.js"], "run_at": "document_end" }], "browser_action": { "default_icon": "images/default.png", "default_title": "Save to Instapaper", "popup": "popup.html" }, "icons": { "16": "images/icon/16.png", "32": "images/icon/32.png", "48": "images/icon/48.png", "128": "images/icon/128.png" }, "permissions": [ "contextMenus", "tabs", "http://ajax.googleapis.com/ajax/libs/jquery/**/*", "http://www.instapaper.com/api/", "https://www.instapaper.com/api/", "http://www.google.com/reader/*" ] }
edgarjs/instachrome
8adff2c6e8e85b128b33b0159bcc1756cd469181
bump v1.5
diff --git a/javascripts/options.js b/javascripts/options.js index 9d6b5ee..a3e8d50 100644 --- a/javascripts/options.js +++ b/javascripts/options.js @@ -1,189 +1,188 @@ (function($) { $.flash = function(msg) { $('.flash').text(msg).fadeIn('fast'); }; })(jQuery); var Options = function() { var values = { username: null, password: null, show_popup: '1', auto_close: false, badge_style: 0, shortcut: { keyCode: 83, altKey: true, ctrlKey: false, shiftKey: true }, cx_read_later: '1', cx_text_view: '0', cx_unread: '0', cx_starred: '0', cx_archive: '0' }; var ui = { username: $('input#username'), password: $('input#password'), show_popup: $('input#show_popup'), auto_close: $('input#auto_close'), badge_style: $('select#badge_style'), shortcut: $('input#shortcut'), cx_read_later: $('input#cx_read_later'), cx_text_view: $('input#cx_text_view'), cx_unread: $('input#cx_unread'), cx_starred: $('input#cx_starred'), cx_archive: $('input#cx_archive') }; var dbOrDefault = function(db_key) { return $.db(db_key) || values[db_key]; }; var authenticateCredentials = function() { var xhr = new XMLHttpRequest(); var username = encodeURIComponent(ui.username.val()); var password = encodeURIComponent(ui.password.val()); xhr.onreadystatechange = function(response) { if(response.srcElement && response.srcElement.readyState == 4) { $('.column.label.auth').show('fast').removeClass('ok error'); if(response.srcElement.status == 200) { $('.column.label.auth').addClass('ok').text('Your credentials are valid.'); getRSSfeed(username, password); } else { $('.column.label.auth').addClass('error').text('Your username or password is incorrect. Please double check them.'); } } } xhr.open("GET", 'https://www.instapaper.com/api/authenticate?username=' + username + '&password=' + password, true); xhr.send(); }; var getRSSfeed = function(user, pass) { var xhr = new XMLHttpRequest(); var params='username=' + user + '&password=' + pass; xhr.onreadystatechange = function() { if(xhr.readyState == 4 && xhr.status == 200) { var xhr2 = new XMLHttpRequest(); xhr2.onreadystatechange = function() { if(xhr2.readyState == 4 && xhr2.status == 200) { $.db('rssfeed', /"(http:\/\/www\.instapaper\.com\/rss\/[^"]*)"/.exec( xhr2.responseText)[1]); - alert($.db('rssfeed')); } }; xhr2.open('GET', 'https://www.instapaper.com/u', true); xhr2.send(); } } xhr.open('POST', 'https://www.instapaper.com/user/login', true); xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); xhr.send(params); }; ui.username.bind('change', authenticateCredentials); ui.password.bind('change', authenticateCredentials); return { humanizeKeystrokes: function(e) { var key = "", special = ""; if(e.keyCode >= 65 && e.keyCode <= 90) { key = String.fromCharCode(e.keyCode); if (e.ctrlKey) { special += "Ctrl + "; } if (e.altKey) { special += "Alt + "; } if (e.shiftKey) { special += "Shift + "; } } return special + key; }, restore: function() { if (location.hash === '#setup') { $.flash('Enter your Instapaper credentials in order to save an URL.'); } ui.username.val(dbOrDefault('username')); ui.password.val(dbOrDefault('password')); if (dbOrDefault('show_popup') === '1') { ui.show_popup.attr('checked', true); } if (dbOrDefault('auto_close') === '1') { ui.auto_close.attr('checked', true); } if (dbOrDefault('cx_read_later') === '1') { ui.cx_read_later.attr('checked', true); } if (dbOrDefault('cx_text_view') === '1') { ui.cx_text_view.attr('checked', true); } if (dbOrDefault('cx_unread') === '1') { ui.cx_unread.attr('checked', true); } if (dbOrDefault('cx_starred') === '1') { ui.cx_starred.attr('checked', true); } if (dbOrDefault('cx_archive') === '1') { ui.cx_archive.attr('checked', true); } ui.badge_style.val(dbOrDefault('badge_style')); ui.shortcut.val(this.humanizeKeystrokes(dbOrDefault('shortcut'))) .data('keys', dbOrDefault('shortcut')); }, save: function() { $.db('username', ui.username.val()); $.db('password', ui.password.val()); $.db('show_popup', ui.show_popup.is(':checked') ? '1': '0'); $.db('auto_close', ui.auto_close.is(':checked') ? '1': '0'); $.db('cx_read_later', ui.cx_read_later.is(':checked') ? '1': '0'); $.db('cx_text_view', ui.cx_text_view.is(':checked') ? '1': '0'); $.db('cx_unread', ui.cx_unread.is(':checked') ? '1': '0'); $.db('cx_starred', ui.cx_starred.is(':checked') ? '1': '0'); $.db('cx_archive', ui.cx_archive.is(':checked') ? '1': '0'); $.db('badge_style', ui.badge_style.val()); $.db('shortcut', ui.shortcut.data('keys')); $.flash('Options saved successfully!'); } }; }; $(function() { var o = new Options(); o.restore(); $('.flash').click(function() { $(this).fadeOut('slow'); return false; }); $('.close').click(function() { window.close(); }); $('form.options').submit(function() { o.save(); return false; }); $('#shortcut').keydown(function(e) { $(this).val(o.humanizeKeystrokes(e)).data('keys', { ctrlKey: e.ctrlKey, altKey: e.altKey, shiftKey: e.shiftKey, keyCode: e.which }); return false; }); }); diff --git a/manifest.json b/manifest.json index 79c24d7..64add34 100644 --- a/manifest.json +++ b/manifest.json @@ -1,35 +1,35 @@ { "name": "Instachrome", - "version": "1.4.4", + "version": "1.5", "description": "Save your URLs to Instapaper", "options_page": "options.html", "background_page": "background.html", "content_scripts": [{ "matches": ["http://*/*", "https://*/*"], "js": ["javascripts/keyboard.js"], "run_at": "document_start" }, { "matches": ["http://www.google.com/reader/*"], "js": ["javascripts/greader.js"], "run_at": "document_end" }], "browser_action": { "default_icon": "images/default.png", "default_title": "Save to Instapaper", "popup": "popup.html" }, "icons": { "16": "images/icon/16.png", "32": "images/icon/32.png", "48": "images/icon/48.png", "128": "images/icon/128.png" }, "permissions": [ "contextMenus", "tabs", "http://ajax.googleapis.com/ajax/libs/jquery/**/*", "http://www.instapaper.com/api/", "https://www.instapaper.com/api/", "http://www.google.com/reader/*" ] }
edgarjs/instachrome
9366b3bd17aaee00b0a57171b1fd31f51e0bba6d
add non-idle cases, set number on all tabs
diff --git a/javascripts/background.js b/javascripts/background.js index aeaa67b..1b84f40 100644 --- a/javascripts/background.js +++ b/javascripts/background.js @@ -1,274 +1,276 @@ var last_tab_id, skip_auto_close; var badge_styles = { TEXT: 0, ICON: 1, CHROMED: 2, UNREAD: 3 }; var badge = { idle: function(tabId) { var tabImg = 'images/default.png'; if (parseInt($.db('badge_style')) === badge_styles.CHROMED) { tabImg = 'images/chromed_default.png'; } function setIcon(id) { chrome.browserAction.setIcon({ path: tabImg, tabId: id }); var feed = $.db('rssfeed'); if(feed && $.db('badge_style') == badge_styles.UNREAD) { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if(xhr.readyState == 4 && xhr.status == 200) { badgetext = xhr.responseText.match(/<item>/g).length; if (badgetext > 0) { chrome.browserAction.setBadgeText({ - text: '' + badgetext, - tabId: id + text: '' + badgetext }); } } }; xhr.open('GET', feed, true); xhr.send(); } else { chrome.browserAction.setBadgeText({ text: '', tabId: id }); } } if(!tabId) { chrome.tabs.getSelected(null, function(tab) { setIcon(tab.id); }); } else { setIcon(tabId); } }, saving: function () { switch (parseInt($.db('badge_style'))) { case badge_styles.TEXT: + case badge_styles.UNREAD: // TODO Customize color chrome.browserAction.setBadgeBackgroundColor({ color: [82, 168, 207, 255], tabId: last_tab_id }); chrome.browserAction.setBadgeText({ text: '...', tabId: last_tab_id }); break; case badge_styles.ICON: chrome.browserAction.setIcon({ path: 'images/saving.png', tabId: last_tab_id }); break; case badge_styles.CHROMED: chrome.browserAction.setIcon({ path: 'images/chromed_saving.png', tabId: last_tab_id }); break; } }, saved: function () { switch (parseInt($.db('badge_style'))) { case badge_styles.TEXT: + case badge_styles.UNREAD: chrome.browserAction.setBadgeBackgroundColor({ color: [53, 181, 49, 255], tabId: last_tab_id }); chrome.browserAction.setBadgeText({ text: 'ok', tabId: last_tab_id }); break; case badge_styles.ICON: chrome.browserAction.setIcon({ path: 'images/saved.png', tabId: last_tab_id }); break; case badge_styles.CHROMED: chrome.browserAction.setIcon({ path: 'images/chromed_saved.png', tabId: last_tab_id }); break; } }, error: function () { switch (parseInt($.db('badge_style'))) { case badge_styles.TEXT: + case badge_styles.UNREAD: chrome.browserAction.setBadgeBackgroundColor({ color: [255, 0, 0, 255], tabId: last_tab_id }); chrome.browserAction.setBadgeText({ text: 'err!', tabId: last_tab_id }); break; case badge_styles.ICON: chrome.browserAction.setIcon({ path: 'images/error.png', tabId: last_tab_id }); break; case badge_styles.CHROMED: chrome.browserAction.setIcon({ path: 'images/chromed_error.png', tabId: last_tab_id }); break; } } }; function onComplete(xhr) { try { if (xhr.srcElement.status == 201) { if ($.db('auto_close') === '1' && !skip_auto_close) { chrome.tabs.remove(last_tab_id); } else { badge.saved(); } } else { badge.error(); } } catch(e) {} } // TODO: gmail support for mails. function sendRequest(url, selection, title) { var username = $.db('username'); var password = $.db('password') || ''; if (!username) { badge.idle(); chrome.tabs.create({ url: chrome.extension.getURL('options.html#setup') }); return; } chrome.tabs.get(last_tab_id, function(tab) { if(/^https?:\/\/www\.google\.com\/reader/.test(url)) { chrome.tabs.sendRequest(tab.id, {}, function(response) { if(response.title && response.url) { sendRequest(response.url, response.selection, response.title); } else { badge.idle(tab.id); } }); } else { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = onComplete; title = encodeURIComponent(title || tab.title); var params = { url: url, username: username, password: password, selection: selection || url.match(/https?:\/\/([^\/]+)/)[1] }; title = title ? ("&title=" + title) : "&auto-title=1"; xhr.open("GET", 'https://www.instapaper.com/api/add?' + $.param(params) + title, true); xhr.send(); } }); } function readLater(tab, selection, source) { last_tab_id = tab.id; badge.saving(); skip_auto_close = (source === 'contextual'); sendRequest(tab.url, selection); } if($.db('cx_read_later') === '1') { chrome.contextMenus.create({ title: 'Read later (send to instapaper)', contexts: ['link'], onclick: function(data, tab) { readLater({id: tab.id, url: data.linkUrl}, null, 'contextual'); } }); } if($.db('cx_text_view') === '1') { chrome.contextMenus.create({ title: 'Text view', contexts: ['page', 'link'], onclick: function(data, tab) { chrome.tabs.update(tab.id, { url: "http://www.instapaper.com/text?u=" + encodeURIComponent(data.linkUrl || data.pageUrl) }); } }); } if($.db('cx_unread') === '1') { chrome.contextMenus.create({ title: 'Go to your unread items', contexts: ['all'], onclick: function(data, tab) { chrome.tabs.create({ url: "http://www.instapaper.com/u" }); } }); } if($.db('cx_starred') === '1') { chrome.contextMenus.create({ title: 'Go to your starred items', contexts: ['all'], onclick: function(data, tab) { chrome.tabs.create({ url: "http://www.instapaper.com/starred" }); } }); } if($.db('cx_archive') === '1') { chrome.contextMenus.create({ title: 'Go to your archived items', contexts: ['all'], onclick: function(data, tab) { chrome.tabs.create({ url: "http://www.instapaper.com/archive" }); } }); } chrome.tabs.onUpdated.addListener(function(tabId) { badge.idle(tabId); }); chrome.browserAction.onClicked.addListener(readLater); // from key shortcut chrome.extension.onRequest.addListener(function(request, sender, sendResponse) { if (sender.tab) { if (request.hasOwnProperty('keystroke')) { var shortcut = $.db('shortcut'); var ctrlKey = (shortcut.ctrlKey == request.keystroke.ctrlKey), altKey = (shortcut.altKey == request.keystroke.altKey), shiftKey = (shortcut.shiftKey == request.keystroke.shiftKey), keyCode = (shortcut.keyCode == request.keystroke.keyCode); sendResponse({ shortcutPressed: (ctrlKey && altKey && shiftKey & keyCode) }); } else if (request.hasOwnProperty('selection')) { readLater(sender.tab, request.selection); } } });
edgarjs/instachrome
ad500f5cec802218efaad15b892bcb16946323f3
Unread count option
diff --git a/javascripts/background.js b/javascripts/background.js index 8112eff..aeaa67b 100644 --- a/javascripts/background.js +++ b/javascripts/background.js @@ -1,273 +1,274 @@ var last_tab_id, skip_auto_close; var badge_styles = { TEXT: 0, ICON: 1, - CHROMED: 2 + CHROMED: 2, + UNREAD: 3 }; var badge = { idle: function(tabId) { var tabImg = 'images/default.png'; if (parseInt($.db('badge_style')) === badge_styles.CHROMED) { tabImg = 'images/chromed_default.png'; } function setIcon(id) { chrome.browserAction.setIcon({ path: tabImg, tabId: id }); var feed = $.db('rssfeed'); - if(feed) { + if(feed && $.db('badge_style') == badge_styles.UNREAD) { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if(xhr.readyState == 4 && xhr.status == 200) { badgetext = xhr.responseText.match(/<item>/g).length; if (badgetext > 0) { chrome.browserAction.setBadgeText({ text: '' + badgetext, tabId: id }); } } }; xhr.open('GET', feed, true); xhr.send(); } else { chrome.browserAction.setBadgeText({ text: '', tabId: id }); } } if(!tabId) { chrome.tabs.getSelected(null, function(tab) { setIcon(tab.id); }); } else { setIcon(tabId); } }, saving: function () { switch (parseInt($.db('badge_style'))) { case badge_styles.TEXT: // TODO Customize color chrome.browserAction.setBadgeBackgroundColor({ color: [82, 168, 207, 255], tabId: last_tab_id }); chrome.browserAction.setBadgeText({ text: '...', tabId: last_tab_id }); break; case badge_styles.ICON: chrome.browserAction.setIcon({ path: 'images/saving.png', tabId: last_tab_id }); break; case badge_styles.CHROMED: chrome.browserAction.setIcon({ path: 'images/chromed_saving.png', tabId: last_tab_id }); break; } }, saved: function () { switch (parseInt($.db('badge_style'))) { case badge_styles.TEXT: chrome.browserAction.setBadgeBackgroundColor({ color: [53, 181, 49, 255], tabId: last_tab_id }); chrome.browserAction.setBadgeText({ text: 'ok', tabId: last_tab_id }); break; case badge_styles.ICON: chrome.browserAction.setIcon({ path: 'images/saved.png', tabId: last_tab_id }); break; case badge_styles.CHROMED: chrome.browserAction.setIcon({ path: 'images/chromed_saved.png', tabId: last_tab_id }); break; } }, error: function () { switch (parseInt($.db('badge_style'))) { case badge_styles.TEXT: chrome.browserAction.setBadgeBackgroundColor({ color: [255, 0, 0, 255], tabId: last_tab_id }); chrome.browserAction.setBadgeText({ text: 'err!', tabId: last_tab_id }); break; case badge_styles.ICON: chrome.browserAction.setIcon({ path: 'images/error.png', tabId: last_tab_id }); break; case badge_styles.CHROMED: chrome.browserAction.setIcon({ path: 'images/chromed_error.png', tabId: last_tab_id }); break; } } }; function onComplete(xhr) { try { if (xhr.srcElement.status == 201) { if ($.db('auto_close') === '1' && !skip_auto_close) { chrome.tabs.remove(last_tab_id); } else { badge.saved(); } } else { badge.error(); } } catch(e) {} } // TODO: gmail support for mails. function sendRequest(url, selection, title) { var username = $.db('username'); var password = $.db('password') || ''; if (!username) { badge.idle(); chrome.tabs.create({ url: chrome.extension.getURL('options.html#setup') }); return; } chrome.tabs.get(last_tab_id, function(tab) { if(/^https?:\/\/www\.google\.com\/reader/.test(url)) { chrome.tabs.sendRequest(tab.id, {}, function(response) { if(response.title && response.url) { sendRequest(response.url, response.selection, response.title); } else { badge.idle(tab.id); } }); } else { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = onComplete; title = encodeURIComponent(title || tab.title); var params = { url: url, username: username, password: password, selection: selection || url.match(/https?:\/\/([^\/]+)/)[1] }; title = title ? ("&title=" + title) : "&auto-title=1"; xhr.open("GET", 'https://www.instapaper.com/api/add?' + $.param(params) + title, true); xhr.send(); } }); } function readLater(tab, selection, source) { last_tab_id = tab.id; badge.saving(); skip_auto_close = (source === 'contextual'); sendRequest(tab.url, selection); } if($.db('cx_read_later') === '1') { chrome.contextMenus.create({ title: 'Read later (send to instapaper)', contexts: ['link'], onclick: function(data, tab) { readLater({id: tab.id, url: data.linkUrl}, null, 'contextual'); } }); } if($.db('cx_text_view') === '1') { chrome.contextMenus.create({ title: 'Text view', contexts: ['page', 'link'], onclick: function(data, tab) { chrome.tabs.update(tab.id, { url: "http://www.instapaper.com/text?u=" + encodeURIComponent(data.linkUrl || data.pageUrl) }); } }); } if($.db('cx_unread') === '1') { chrome.contextMenus.create({ title: 'Go to your unread items', contexts: ['all'], onclick: function(data, tab) { chrome.tabs.create({ url: "http://www.instapaper.com/u" }); } }); } if($.db('cx_starred') === '1') { chrome.contextMenus.create({ title: 'Go to your starred items', contexts: ['all'], onclick: function(data, tab) { chrome.tabs.create({ url: "http://www.instapaper.com/starred" }); } }); } if($.db('cx_archive') === '1') { chrome.contextMenus.create({ title: 'Go to your archived items', contexts: ['all'], onclick: function(data, tab) { chrome.tabs.create({ url: "http://www.instapaper.com/archive" }); } }); } chrome.tabs.onUpdated.addListener(function(tabId) { badge.idle(tabId); }); chrome.browserAction.onClicked.addListener(readLater); // from key shortcut chrome.extension.onRequest.addListener(function(request, sender, sendResponse) { if (sender.tab) { if (request.hasOwnProperty('keystroke')) { var shortcut = $.db('shortcut'); var ctrlKey = (shortcut.ctrlKey == request.keystroke.ctrlKey), altKey = (shortcut.altKey == request.keystroke.altKey), shiftKey = (shortcut.shiftKey == request.keystroke.shiftKey), keyCode = (shortcut.keyCode == request.keystroke.keyCode); sendResponse({ shortcutPressed: (ctrlKey && altKey && shiftKey & keyCode) }); } else if (request.hasOwnProperty('selection')) { readLater(sender.tab, request.selection); } } }); diff --git a/options.html b/options.html index 2f88c8c..1b37880 100644 --- a/options.html +++ b/options.html @@ -1,163 +1,164 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta charset="utf-8" /> <title>Instachrome Options</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript" src="javascripts/elastic.js"></script> <script type="text/javascript" src="javascripts/app.js"></script> <script type="text/javascript" src="javascripts/options.js"></script> <link href="stylesheets/elastic.css" rel="stylesheet" type="text/css" /> <link href="stylesheets/options.css" rel="stylesheet" type="text/css" /> </head> <body> <a href="http://pledgie.com/campaigns/9023" class="ribbon left"></a> <a href="http://github.com/edgarjs/instachrome" class="ribbon right"></a> <div class="container wrapper"> <h1 class="title">Instachrome Options</h1> <div class="flash"></div> <form class="options" action="#" method="post"> <fieldset class="container set"> <legend>Instapaper credentials</legend> <div class="container pad"> <div class="unit on-2 columns same-height"> <div class="column label"> <label for="username" class="vertical-center">Username:</label> </div> <div class="column"> <input type="text" class="text" spellcheck="false" name="username" id="username" /> </div> <div class="column label"> <label for="password">Password:</label> <div class="description">(If you have one)</div> </div> <div class="column"> <input type="password" class="text" name="password" id="password" /> </div> <div class="column label span-2 auth"> Your username or password is incorrect. Please double check them. </div> <div class="column label span-2"> <a href="http://www.instapaper.com/user/register" class="vertical-center description">Get a free account</a> </div> </div> </div> </fieldset> <fieldset class="container set"> <legend>Extras</legend> <div class="container pad"> <div class="unit on-2 columns same-height"> <div class="column label"> <label for="show_popup" class="vertical-center">Show popup:</label> </div> <div class="column"> <input type="checkbox" name="show_popup" class="vertical-center" id="show_popup" value="1" /> </div> <div class="column label"> <label for="auto_close">Auto close:</label> <div class="description">(Close tab after saved)</div> </div> <div class="column"> <input type="checkbox" name="auto_close" class="vertical-center" id="auto_close" value="1" /> </div> <div class="column label"> <label for="badge_style" class="vertical-center">Badge style:</label> </div> <div class="column"> <select name="badge_style" id="badge_style"> <option value="0">Text</option> <option value="1">Tick/Circle/Cross Icons</option> <option value="2">Chromed icons</option> + <option value="3">Text + unread count</option> </select> </div> <div class="column label"> <label for="shortcut" class="vertical-center">Keyboard shortcut:</label> <div class="description">(Beta - Not all shortcuts may work)</div> </div> <div class="column"> <input type="text" name="shortcut" id="shortcut" class="text" /> </div> </div> </div> </fieldset> <fieldset class="container set"> <legend>Context Menus</legend> <div class="container pad"> <div class="unit on-1 columns"> <div class="column label"> <div class="description">You'll need to restart the browser for context menus to take effect.</p> </div> </div> <div class="unit on-2 columns same-height"> <div class="column label"> <label for="cx_read_later" class="vertical-center">Read Later</label> </div> <div class="column"> <input type="checkbox" name="cx_read_later" class="vertical-center" id="cx_read_later" value="1" /> </div> <div class="column label"> <label for="cx_text_view" class="vertical-center">Text view</label> </div> <div class="column"> <input type="checkbox" name="cx_text_view" class="vertical-center" id="cx_text_view" value="1" /> </div> <div class="column label"> <label for="cx_unread" class="vertical-center">Go to unread</label> </div> <div class="column"> <input type="checkbox" name="cx_unread" class="vertical-center" id="cx_unread" value="1" /> </div> <div class="column label"> <label for="cx_starred" class="vertical-center">Go to starred</label> </div> <div class="column"> <input type="checkbox" name="cx_starred" class="vertical-center" id="cx_starred" value="1" /> </div> <div class="column label"> <label for="cx_archive" class="vertical-center">Go to archive</label> </div> <div class="column"> <input type="checkbox" name="cx_archive" class="vertical-center" id="cx_archive" value="1" /> </div> </div> </div> </fieldset> <input type="submit" class="button" value="Save" /> or <a href="#" class="close">Close</a> </form> <div class="container footer"> <p> by <a href="http://edgarjs.mx">Edgar J. Suárez</a> | <a href="http://twitter.com/edgarjs">Twitter</a> | <a href="https://chrome.google.com/extensions/detail/fldildgghjoohccppflaohodcnmlacpb">Extension page</a> | <a href="http://instapaper.com">Instapaper</a> <br /> This page is powered by <a href="http://elasticss.com">Elastic CSS</a> | Icons by <a href="http://famfamfam.com">famfamfam.com</a> </p> </div> </div> </body> </html>
edgarjs/instachrome
3e22aa343bc7a3852ca90a122a443fabc9dd6616
first unread item # badge
diff --git a/javascripts/background.js b/javascripts/background.js index 0813d62..8112eff 100644 --- a/javascripts/background.js +++ b/javascripts/background.js @@ -1,254 +1,273 @@ var last_tab_id, skip_auto_close; var badge_styles = { TEXT: 0, ICON: 1, CHROMED: 2 }; var badge = { idle: function(tabId) { var tabImg = 'images/default.png'; if (parseInt($.db('badge_style')) === badge_styles.CHROMED) { tabImg = 'images/chromed_default.png'; } function setIcon(id) { chrome.browserAction.setIcon({ path: tabImg, tabId: id }); - chrome.browserAction.setBadgeText({ - text: '', - tabId: id - }); + var feed = $.db('rssfeed'); + if(feed) { + var xhr = new XMLHttpRequest(); + xhr.onreadystatechange = function() { + if(xhr.readyState == 4 && + xhr.status == 200) { + badgetext = xhr.responseText.match(/<item>/g).length; + if (badgetext > 0) { + chrome.browserAction.setBadgeText({ + text: '' + badgetext, + tabId: id + }); + } + } + }; + xhr.open('GET', feed, true); + xhr.send(); + } else { + chrome.browserAction.setBadgeText({ + text: '', + tabId: id + }); + } } if(!tabId) { chrome.tabs.getSelected(null, function(tab) { setIcon(tab.id); }); } else { setIcon(tabId); } }, saving: function () { switch (parseInt($.db('badge_style'))) { case badge_styles.TEXT: // TODO Customize color chrome.browserAction.setBadgeBackgroundColor({ color: [82, 168, 207, 255], tabId: last_tab_id }); chrome.browserAction.setBadgeText({ text: '...', tabId: last_tab_id }); break; case badge_styles.ICON: chrome.browserAction.setIcon({ path: 'images/saving.png', tabId: last_tab_id }); break; case badge_styles.CHROMED: chrome.browserAction.setIcon({ path: 'images/chromed_saving.png', tabId: last_tab_id }); break; } }, saved: function () { switch (parseInt($.db('badge_style'))) { case badge_styles.TEXT: chrome.browserAction.setBadgeBackgroundColor({ color: [53, 181, 49, 255], tabId: last_tab_id }); chrome.browserAction.setBadgeText({ text: 'ok', tabId: last_tab_id }); break; case badge_styles.ICON: chrome.browserAction.setIcon({ path: 'images/saved.png', tabId: last_tab_id }); break; case badge_styles.CHROMED: chrome.browserAction.setIcon({ path: 'images/chromed_saved.png', tabId: last_tab_id }); break; } }, error: function () { switch (parseInt($.db('badge_style'))) { case badge_styles.TEXT: chrome.browserAction.setBadgeBackgroundColor({ color: [255, 0, 0, 255], tabId: last_tab_id }); chrome.browserAction.setBadgeText({ text: 'err!', tabId: last_tab_id }); break; case badge_styles.ICON: chrome.browserAction.setIcon({ path: 'images/error.png', tabId: last_tab_id }); break; case badge_styles.CHROMED: chrome.browserAction.setIcon({ path: 'images/chromed_error.png', tabId: last_tab_id }); break; } } }; function onComplete(xhr) { try { if (xhr.srcElement.status == 201) { if ($.db('auto_close') === '1' && !skip_auto_close) { chrome.tabs.remove(last_tab_id); } else { badge.saved(); } } else { badge.error(); } } catch(e) {} } // TODO: gmail support for mails. function sendRequest(url, selection, title) { var username = $.db('username'); var password = $.db('password') || ''; if (!username) { badge.idle(); chrome.tabs.create({ url: chrome.extension.getURL('options.html#setup') }); return; } chrome.tabs.get(last_tab_id, function(tab) { if(/^https?:\/\/www\.google\.com\/reader/.test(url)) { chrome.tabs.sendRequest(tab.id, {}, function(response) { if(response.title && response.url) { sendRequest(response.url, response.selection, response.title); } else { badge.idle(tab.id); } }); } else { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = onComplete; title = encodeURIComponent(title || tab.title); var params = { url: url, username: username, password: password, selection: selection || url.match(/https?:\/\/([^\/]+)/)[1] }; title = title ? ("&title=" + title) : "&auto-title=1"; xhr.open("GET", 'https://www.instapaper.com/api/add?' + $.param(params) + title, true); xhr.send(); } }); } function readLater(tab, selection, source) { last_tab_id = tab.id; badge.saving(); skip_auto_close = (source === 'contextual'); sendRequest(tab.url, selection); } if($.db('cx_read_later') === '1') { chrome.contextMenus.create({ title: 'Read later (send to instapaper)', contexts: ['link'], onclick: function(data, tab) { readLater({id: tab.id, url: data.linkUrl}, null, 'contextual'); } }); } if($.db('cx_text_view') === '1') { chrome.contextMenus.create({ title: 'Text view', contexts: ['page', 'link'], onclick: function(data, tab) { chrome.tabs.update(tab.id, { url: "http://www.instapaper.com/text?u=" + encodeURIComponent(data.linkUrl || data.pageUrl) }); } }); } if($.db('cx_unread') === '1') { chrome.contextMenus.create({ title: 'Go to your unread items', contexts: ['all'], onclick: function(data, tab) { chrome.tabs.create({ url: "http://www.instapaper.com/u" }); } }); } if($.db('cx_starred') === '1') { chrome.contextMenus.create({ title: 'Go to your starred items', contexts: ['all'], onclick: function(data, tab) { chrome.tabs.create({ url: "http://www.instapaper.com/starred" }); } }); } if($.db('cx_archive') === '1') { chrome.contextMenus.create({ title: 'Go to your archived items', contexts: ['all'], onclick: function(data, tab) { chrome.tabs.create({ url: "http://www.instapaper.com/archive" }); } }); } chrome.tabs.onUpdated.addListener(function(tabId) { badge.idle(tabId); }); chrome.browserAction.onClicked.addListener(readLater); // from key shortcut chrome.extension.onRequest.addListener(function(request, sender, sendResponse) { if (sender.tab) { if (request.hasOwnProperty('keystroke')) { var shortcut = $.db('shortcut'); var ctrlKey = (shortcut.ctrlKey == request.keystroke.ctrlKey), altKey = (shortcut.altKey == request.keystroke.altKey), shiftKey = (shortcut.shiftKey == request.keystroke.shiftKey), keyCode = (shortcut.keyCode == request.keystroke.keyCode); sendResponse({ shortcutPressed: (ctrlKey && altKey && shiftKey & keyCode) }); } else if (request.hasOwnProperty('selection')) { readLater(sender.tab, request.selection); } } }); diff --git a/javascripts/options.js b/javascripts/options.js index 37935aa..9d6b5ee 100644 --- a/javascripts/options.js +++ b/javascripts/options.js @@ -1,163 +1,189 @@ (function($) { $.flash = function(msg) { $('.flash').text(msg).fadeIn('fast'); }; })(jQuery); var Options = function() { var values = { username: null, password: null, show_popup: '1', auto_close: false, badge_style: 0, shortcut: { keyCode: 83, altKey: true, ctrlKey: false, shiftKey: true }, cx_read_later: '1', cx_text_view: '0', cx_unread: '0', cx_starred: '0', cx_archive: '0' }; var ui = { username: $('input#username'), password: $('input#password'), show_popup: $('input#show_popup'), auto_close: $('input#auto_close'), badge_style: $('select#badge_style'), shortcut: $('input#shortcut'), cx_read_later: $('input#cx_read_later'), cx_text_view: $('input#cx_text_view'), cx_unread: $('input#cx_unread'), cx_starred: $('input#cx_starred'), cx_archive: $('input#cx_archive') }; var dbOrDefault = function(db_key) { return $.db(db_key) || values[db_key]; }; var authenticateCredentials = function() { var xhr = new XMLHttpRequest(); var username = encodeURIComponent(ui.username.val()); var password = encodeURIComponent(ui.password.val()); xhr.onreadystatechange = function(response) { if(response.srcElement && response.srcElement.readyState == 4) { $('.column.label.auth').show('fast').removeClass('ok error'); if(response.srcElement.status == 200) { $('.column.label.auth').addClass('ok').text('Your credentials are valid.'); + getRSSfeed(username, password); } else { $('.column.label.auth').addClass('error').text('Your username or password is incorrect. Please double check them.'); } } } xhr.open("GET", 'https://www.instapaper.com/api/authenticate?username=' + username + '&password=' + password, true); xhr.send(); }; + var getRSSfeed = function(user, pass) { + var xhr = new XMLHttpRequest(); + var params='username=' + user + '&password=' + pass; + xhr.onreadystatechange = function() { + if(xhr.readyState == 4 && + xhr.status == 200) { + var xhr2 = new XMLHttpRequest(); + xhr2.onreadystatechange = function() { + if(xhr2.readyState == 4 && + xhr2.status == 200) { + $.db('rssfeed', + /"(http:\/\/www\.instapaper\.com\/rss\/[^"]*)"/.exec( + xhr2.responseText)[1]); + alert($.db('rssfeed')); + } + }; + xhr2.open('GET', 'https://www.instapaper.com/u', true); + xhr2.send(); + } + } + xhr.open('POST', 'https://www.instapaper.com/user/login', true); + xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); + xhr.send(params); + }; + ui.username.bind('change', authenticateCredentials); ui.password.bind('change', authenticateCredentials); return { humanizeKeystrokes: function(e) { var key = "", special = ""; if(e.keyCode >= 65 && e.keyCode <= 90) { key = String.fromCharCode(e.keyCode); if (e.ctrlKey) { special += "Ctrl + "; } if (e.altKey) { special += "Alt + "; } if (e.shiftKey) { special += "Shift + "; } } return special + key; }, restore: function() { if (location.hash === '#setup') { $.flash('Enter your Instapaper credentials in order to save an URL.'); } ui.username.val(dbOrDefault('username')); ui.password.val(dbOrDefault('password')); if (dbOrDefault('show_popup') === '1') { ui.show_popup.attr('checked', true); } if (dbOrDefault('auto_close') === '1') { ui.auto_close.attr('checked', true); } if (dbOrDefault('cx_read_later') === '1') { ui.cx_read_later.attr('checked', true); } if (dbOrDefault('cx_text_view') === '1') { ui.cx_text_view.attr('checked', true); } if (dbOrDefault('cx_unread') === '1') { ui.cx_unread.attr('checked', true); } if (dbOrDefault('cx_starred') === '1') { ui.cx_starred.attr('checked', true); } if (dbOrDefault('cx_archive') === '1') { ui.cx_archive.attr('checked', true); } ui.badge_style.val(dbOrDefault('badge_style')); ui.shortcut.val(this.humanizeKeystrokes(dbOrDefault('shortcut'))) .data('keys', dbOrDefault('shortcut')); }, save: function() { $.db('username', ui.username.val()); $.db('password', ui.password.val()); $.db('show_popup', ui.show_popup.is(':checked') ? '1': '0'); $.db('auto_close', ui.auto_close.is(':checked') ? '1': '0'); $.db('cx_read_later', ui.cx_read_later.is(':checked') ? '1': '0'); $.db('cx_text_view', ui.cx_text_view.is(':checked') ? '1': '0'); $.db('cx_unread', ui.cx_unread.is(':checked') ? '1': '0'); $.db('cx_starred', ui.cx_starred.is(':checked') ? '1': '0'); $.db('cx_archive', ui.cx_archive.is(':checked') ? '1': '0'); $.db('badge_style', ui.badge_style.val()); $.db('shortcut', ui.shortcut.data('keys')); $.flash('Options saved successfully!'); } }; }; $(function() { var o = new Options(); o.restore(); $('.flash').click(function() { $(this).fadeOut('slow'); return false; }); $('.close').click(function() { window.close(); }); $('form.options').submit(function() { o.save(); return false; }); $('#shortcut').keydown(function(e) { $(this).val(o.humanizeKeystrokes(e)).data('keys', { ctrlKey: e.ctrlKey, altKey: e.altKey, shiftKey: e.shiftKey, keyCode: e.which }); return false; }); });
edgarjs/instachrome
8ff7e5dd0769476b675480206f8b71ba371217e6
Fix keyboard shortcut capturing tabs and special strokes
diff --git a/javascripts/options.js b/javascripts/options.js index 1997bf6..37935aa 100644 --- a/javascripts/options.js +++ b/javascripts/options.js @@ -1,160 +1,163 @@ (function($) { $.flash = function(msg) { $('.flash').text(msg).fadeIn('fast'); }; })(jQuery); var Options = function() { var values = { username: null, password: null, show_popup: '1', auto_close: false, badge_style: 0, shortcut: { keyCode: 83, altKey: true, ctrlKey: false, shiftKey: true }, cx_read_later: '1', cx_text_view: '0', cx_unread: '0', cx_starred: '0', cx_archive: '0' }; var ui = { username: $('input#username'), password: $('input#password'), show_popup: $('input#show_popup'), auto_close: $('input#auto_close'), badge_style: $('select#badge_style'), shortcut: $('input#shortcut'), cx_read_later: $('input#cx_read_later'), cx_text_view: $('input#cx_text_view'), cx_unread: $('input#cx_unread'), cx_starred: $('input#cx_starred'), cx_archive: $('input#cx_archive') }; var dbOrDefault = function(db_key) { return $.db(db_key) || values[db_key]; }; var authenticateCredentials = function() { var xhr = new XMLHttpRequest(); var username = encodeURIComponent(ui.username.val()); var password = encodeURIComponent(ui.password.val()); xhr.onreadystatechange = function(response) { if(response.srcElement && response.srcElement.readyState == 4) { $('.column.label.auth').show('fast').removeClass('ok error'); if(response.srcElement.status == 200) { $('.column.label.auth').addClass('ok').text('Your credentials are valid.'); } else { $('.column.label.auth').addClass('error').text('Your username or password is incorrect. Please double check them.'); } } } xhr.open("GET", 'https://www.instapaper.com/api/authenticate?username=' + username + '&password=' + password, true); xhr.send(); }; ui.username.bind('change', authenticateCredentials); ui.password.bind('change', authenticateCredentials); return { humanizeKeystrokes: function(e) { - var key = String.fromCharCode(e.keyCode); - var special = ""; - if (e.ctrlKey) { - special += "Ctrl + "; - } - if (e.altKey) { - special += "Alt + "; - } - if (e.shiftKey) { - special += "Shift + "; + var key = "", + special = ""; + if(e.keyCode >= 65 && e.keyCode <= 90) { + key = String.fromCharCode(e.keyCode); + if (e.ctrlKey) { + special += "Ctrl + "; + } + if (e.altKey) { + special += "Alt + "; + } + if (e.shiftKey) { + special += "Shift + "; + } } return special + key; }, restore: function() { if (location.hash === '#setup') { $.flash('Enter your Instapaper credentials in order to save an URL.'); } ui.username.val(dbOrDefault('username')); ui.password.val(dbOrDefault('password')); if (dbOrDefault('show_popup') === '1') { ui.show_popup.attr('checked', true); } if (dbOrDefault('auto_close') === '1') { ui.auto_close.attr('checked', true); } if (dbOrDefault('cx_read_later') === '1') { ui.cx_read_later.attr('checked', true); } if (dbOrDefault('cx_text_view') === '1') { ui.cx_text_view.attr('checked', true); } if (dbOrDefault('cx_unread') === '1') { ui.cx_unread.attr('checked', true); } if (dbOrDefault('cx_starred') === '1') { ui.cx_starred.attr('checked', true); } if (dbOrDefault('cx_archive') === '1') { ui.cx_archive.attr('checked', true); } ui.badge_style.val(dbOrDefault('badge_style')); ui.shortcut.val(this.humanizeKeystrokes(dbOrDefault('shortcut'))) .data('keys', dbOrDefault('shortcut')); }, save: function() { $.db('username', ui.username.val()); $.db('password', ui.password.val()); $.db('show_popup', ui.show_popup.is(':checked') ? '1': '0'); $.db('auto_close', ui.auto_close.is(':checked') ? '1': '0'); $.db('cx_read_later', ui.cx_read_later.is(':checked') ? '1': '0'); $.db('cx_text_view', ui.cx_text_view.is(':checked') ? '1': '0'); $.db('cx_unread', ui.cx_unread.is(':checked') ? '1': '0'); $.db('cx_starred', ui.cx_starred.is(':checked') ? '1': '0'); $.db('cx_archive', ui.cx_archive.is(':checked') ? '1': '0'); $.db('badge_style', ui.badge_style.val()); $.db('shortcut', ui.shortcut.data('keys')); $.flash('Options saved successfully!'); } }; }; $(function() { var o = new Options(); o.restore(); $('.flash').click(function() { $(this).fadeOut('slow'); return false; }); $('.close').click(function() { window.close(); }); $('form.options').submit(function() { o.save(); return false; }); $('#shortcut').keydown(function(e) { $(this).val(o.humanizeKeystrokes(e)).data('keys', { ctrlKey: e.ctrlKey, altKey: e.altKey, shiftKey: e.shiftKey, keyCode: e.which }); return false; }); }); diff --git a/manifest.json b/manifest.json index 8dc05f2..79c24d7 100644 --- a/manifest.json +++ b/manifest.json @@ -1,35 +1,35 @@ { "name": "Instachrome", - "version": "1.4.3", + "version": "1.4.4", "description": "Save your URLs to Instapaper", "options_page": "options.html", "background_page": "background.html", "content_scripts": [{ "matches": ["http://*/*", "https://*/*"], "js": ["javascripts/keyboard.js"], "run_at": "document_start" }, { "matches": ["http://www.google.com/reader/*"], "js": ["javascripts/greader.js"], "run_at": "document_end" }], "browser_action": { "default_icon": "images/default.png", "default_title": "Save to Instapaper", "popup": "popup.html" }, "icons": { "16": "images/icon/16.png", "32": "images/icon/32.png", "48": "images/icon/48.png", "128": "images/icon/128.png" }, "permissions": [ "contextMenus", "tabs", "http://ajax.googleapis.com/ajax/libs/jquery/**/*", "http://www.instapaper.com/api/", "https://www.instapaper.com/api/", "http://www.google.com/reader/*" ] }
edgarjs/instachrome
dc422631e7b77c73a37c11efbdad08385e9e9ee6
Skipping auto close when adding from contextual menu
diff --git a/javascripts/background.js b/javascripts/background.js index c0252fb..0813d62 100644 --- a/javascripts/background.js +++ b/javascripts/background.js @@ -1,252 +1,254 @@ -var last_tab_id; +var last_tab_id, + skip_auto_close; var badge_styles = { TEXT: 0, ICON: 1, CHROMED: 2 }; var badge = { idle: function(tabId) { var tabImg = 'images/default.png'; if (parseInt($.db('badge_style')) === badge_styles.CHROMED) { tabImg = 'images/chromed_default.png'; } function setIcon(id) { chrome.browserAction.setIcon({ path: tabImg, tabId: id }); chrome.browserAction.setBadgeText({ text: '', tabId: id }); } if(!tabId) { chrome.tabs.getSelected(null, function(tab) { setIcon(tab.id); }); } else { setIcon(tabId); } }, saving: function () { switch (parseInt($.db('badge_style'))) { case badge_styles.TEXT: // TODO Customize color chrome.browserAction.setBadgeBackgroundColor({ color: [82, 168, 207, 255], tabId: last_tab_id }); chrome.browserAction.setBadgeText({ text: '...', tabId: last_tab_id }); break; case badge_styles.ICON: chrome.browserAction.setIcon({ path: 'images/saving.png', tabId: last_tab_id }); break; case badge_styles.CHROMED: chrome.browserAction.setIcon({ path: 'images/chromed_saving.png', tabId: last_tab_id }); break; } }, saved: function () { switch (parseInt($.db('badge_style'))) { case badge_styles.TEXT: chrome.browserAction.setBadgeBackgroundColor({ color: [53, 181, 49, 255], tabId: last_tab_id }); chrome.browserAction.setBadgeText({ text: 'ok', tabId: last_tab_id }); break; case badge_styles.ICON: chrome.browserAction.setIcon({ path: 'images/saved.png', tabId: last_tab_id }); break; case badge_styles.CHROMED: chrome.browserAction.setIcon({ path: 'images/chromed_saved.png', tabId: last_tab_id }); break; } }, error: function () { switch (parseInt($.db('badge_style'))) { case badge_styles.TEXT: chrome.browserAction.setBadgeBackgroundColor({ color: [255, 0, 0, 255], tabId: last_tab_id }); chrome.browserAction.setBadgeText({ text: 'err!', tabId: last_tab_id }); break; case badge_styles.ICON: chrome.browserAction.setIcon({ path: 'images/error.png', tabId: last_tab_id }); break; case badge_styles.CHROMED: chrome.browserAction.setIcon({ path: 'images/chromed_error.png', tabId: last_tab_id }); break; } } }; function onComplete(xhr) { try { if (xhr.srcElement.status == 201) { - if ($.db('auto_close') === '1') { + if ($.db('auto_close') === '1' && !skip_auto_close) { chrome.tabs.remove(last_tab_id); } else { badge.saved(); } } else { badge.error(); } } catch(e) {} } // TODO: gmail support for mails. function sendRequest(url, selection, title) { var username = $.db('username'); var password = $.db('password') || ''; if (!username) { badge.idle(); chrome.tabs.create({ url: chrome.extension.getURL('options.html#setup') }); return; } chrome.tabs.get(last_tab_id, function(tab) { if(/^https?:\/\/www\.google\.com\/reader/.test(url)) { chrome.tabs.sendRequest(tab.id, {}, function(response) { if(response.title && response.url) { sendRequest(response.url, response.selection, response.title); } else { badge.idle(tab.id); } }); } else { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = onComplete; title = encodeURIComponent(title || tab.title); var params = { url: url, username: username, password: password, selection: selection || url.match(/https?:\/\/([^\/]+)/)[1] }; title = title ? ("&title=" + title) : "&auto-title=1"; xhr.open("GET", 'https://www.instapaper.com/api/add?' + $.param(params) + title, true); xhr.send(); } }); } -function readLater(tab, selection) { +function readLater(tab, selection, source) { last_tab_id = tab.id; badge.saving(); + skip_auto_close = (source === 'contextual'); sendRequest(tab.url, selection); } if($.db('cx_read_later') === '1') { chrome.contextMenus.create({ title: 'Read later (send to instapaper)', contexts: ['link'], onclick: function(data, tab) { - readLater({id: tab.id, url: data.linkUrl}); + readLater({id: tab.id, url: data.linkUrl}, null, 'contextual'); } }); } if($.db('cx_text_view') === '1') { chrome.contextMenus.create({ title: 'Text view', contexts: ['page', 'link'], onclick: function(data, tab) { chrome.tabs.update(tab.id, { url: "http://www.instapaper.com/text?u=" + encodeURIComponent(data.linkUrl || data.pageUrl) }); } }); } if($.db('cx_unread') === '1') { chrome.contextMenus.create({ title: 'Go to your unread items', contexts: ['all'], onclick: function(data, tab) { chrome.tabs.create({ url: "http://www.instapaper.com/u" }); } }); } if($.db('cx_starred') === '1') { chrome.contextMenus.create({ title: 'Go to your starred items', contexts: ['all'], onclick: function(data, tab) { chrome.tabs.create({ url: "http://www.instapaper.com/starred" }); } }); } if($.db('cx_archive') === '1') { chrome.contextMenus.create({ title: 'Go to your archived items', contexts: ['all'], onclick: function(data, tab) { chrome.tabs.create({ url: "http://www.instapaper.com/archive" }); } }); } chrome.tabs.onUpdated.addListener(function(tabId) { badge.idle(tabId); }); chrome.browserAction.onClicked.addListener(readLater); // from key shortcut chrome.extension.onRequest.addListener(function(request, sender, sendResponse) { if (sender.tab) { if (request.hasOwnProperty('keystroke')) { var shortcut = $.db('shortcut'); var ctrlKey = (shortcut.ctrlKey == request.keystroke.ctrlKey), altKey = (shortcut.altKey == request.keystroke.altKey), shiftKey = (shortcut.shiftKey == request.keystroke.shiftKey), keyCode = (shortcut.keyCode == request.keystroke.keyCode); sendResponse({ shortcutPressed: (ctrlKey && altKey && shiftKey & keyCode) }); } else if (request.hasOwnProperty('selection')) { readLater(sender.tab, request.selection); } } }); diff --git a/manifest.json b/manifest.json index 08c3e6d..8dc05f2 100644 --- a/manifest.json +++ b/manifest.json @@ -1,35 +1,35 @@ { "name": "Instachrome", - "version": "1.4.2.2", + "version": "1.4.3", "description": "Save your URLs to Instapaper", "options_page": "options.html", "background_page": "background.html", "content_scripts": [{ "matches": ["http://*/*", "https://*/*"], "js": ["javascripts/keyboard.js"], "run_at": "document_start" }, { "matches": ["http://www.google.com/reader/*"], "js": ["javascripts/greader.js"], "run_at": "document_end" }], "browser_action": { "default_icon": "images/default.png", "default_title": "Save to Instapaper", "popup": "popup.html" }, "icons": { "16": "images/icon/16.png", "32": "images/icon/32.png", "48": "images/icon/48.png", "128": "images/icon/128.png" }, "permissions": [ "contextMenus", "tabs", "http://ajax.googleapis.com/ajax/libs/jquery/**/*", "http://www.instapaper.com/api/", "https://www.instapaper.com/api/", "http://www.google.com/reader/*" ] }
edgarjs/instachrome
218a226f21905c141937722eacaeba73d47ddabe
bumping version 1.4.2.2
diff --git a/manifest.json b/manifest.json index 94cd359..08c3e6d 100644 --- a/manifest.json +++ b/manifest.json @@ -1,35 +1,35 @@ { "name": "Instachrome", - "version": "1.4.2.1", + "version": "1.4.2.2", "description": "Save your URLs to Instapaper", "options_page": "options.html", "background_page": "background.html", "content_scripts": [{ "matches": ["http://*/*", "https://*/*"], "js": ["javascripts/keyboard.js"], "run_at": "document_start" }, { "matches": ["http://www.google.com/reader/*"], "js": ["javascripts/greader.js"], "run_at": "document_end" }], "browser_action": { "default_icon": "images/default.png", "default_title": "Save to Instapaper", "popup": "popup.html" }, "icons": { "16": "images/icon/16.png", "32": "images/icon/32.png", "48": "images/icon/48.png", "128": "images/icon/128.png" }, "permissions": [ "contextMenus", "tabs", "http://ajax.googleapis.com/ajax/libs/jquery/**/*", "http://www.instapaper.com/api/", "https://www.instapaper.com/api/", "http://www.google.com/reader/*" ] }
edgarjs/instachrome
2186f43f2870dbfc0dac298f70da49ab91c9ff66
closing window inside the callback for get selected tab
diff --git a/javascripts/popup.js b/javascripts/popup.js index 38ec8c1..3204e3b 100644 --- a/javascripts/popup.js +++ b/javascripts/popup.js @@ -1,50 +1,55 @@ $(function() { var show_popup = $.db('show_popup') === "1"; if(!show_popup) { chrome.tabs.getSelected(null, function(tab) { chrome.extension.getBackgroundPage().readLater(tab); + window.close(); }); - window.close(); } else { $('ul.links li > a.add').click(function() { chrome.tabs.getSelected(null, function(tab) { chrome.extension.getBackgroundPage().readLater(tab); + window.close(); }); }); $('ul.links li > a.text').click(function() { chrome.tabs.getSelected(null, function(tab) { chrome.tabs.update(tab.id, { url: "http://www.instapaper.com/text?u=" + encodeURIComponent(tab.url) }); + window.close(); }); }); $('ul.links li > a.unread').click(function() { chrome.tabs.create({ url: "http://www.instapaper.com/u" }); + window.close(); }); $('ul.links li > a.starred').click(function() { chrome.tabs.create({ url: "http://www.instapaper.com/starred" }); + window.close(); }); $('ul.links li > a.archive').click(function() { chrome.tabs.create({ url: "http://www.instapaper.com/archive" }); + window.close(); }); $('ul.links li > a.options').click(function() { chrome.tabs.create({url: chrome.extension.getURL('options.html')}); + window.close(); }); $('ul.links li > a').click(function () { - window.close(); return false; }); } });
edgarjs/instachrome
e00a1fc24be316d27e39b21544445a79c5805627
adding more context menus and optionables
diff --git a/javascripts/background.js b/javascripts/background.js index 102ec26..c0252fb 100644 --- a/javascripts/background.js +++ b/javascripts/background.js @@ -1,202 +1,252 @@ var last_tab_id; var badge_styles = { TEXT: 0, ICON: 1, CHROMED: 2 }; var badge = { idle: function(tabId) { var tabImg = 'images/default.png'; if (parseInt($.db('badge_style')) === badge_styles.CHROMED) { tabImg = 'images/chromed_default.png'; } function setIcon(id) { chrome.browserAction.setIcon({ path: tabImg, tabId: id }); chrome.browserAction.setBadgeText({ text: '', tabId: id }); } if(!tabId) { chrome.tabs.getSelected(null, function(tab) { setIcon(tab.id); }); } else { setIcon(tabId); } }, saving: function () { switch (parseInt($.db('badge_style'))) { case badge_styles.TEXT: // TODO Customize color chrome.browserAction.setBadgeBackgroundColor({ color: [82, 168, 207, 255], tabId: last_tab_id }); chrome.browserAction.setBadgeText({ text: '...', tabId: last_tab_id }); break; case badge_styles.ICON: chrome.browserAction.setIcon({ path: 'images/saving.png', tabId: last_tab_id }); break; case badge_styles.CHROMED: chrome.browserAction.setIcon({ path: 'images/chromed_saving.png', tabId: last_tab_id }); break; } }, saved: function () { switch (parseInt($.db('badge_style'))) { case badge_styles.TEXT: chrome.browserAction.setBadgeBackgroundColor({ color: [53, 181, 49, 255], tabId: last_tab_id }); chrome.browserAction.setBadgeText({ text: 'ok', tabId: last_tab_id }); break; case badge_styles.ICON: chrome.browserAction.setIcon({ path: 'images/saved.png', tabId: last_tab_id }); break; case badge_styles.CHROMED: chrome.browserAction.setIcon({ path: 'images/chromed_saved.png', tabId: last_tab_id }); break; } }, error: function () { switch (parseInt($.db('badge_style'))) { case badge_styles.TEXT: chrome.browserAction.setBadgeBackgroundColor({ color: [255, 0, 0, 255], tabId: last_tab_id }); chrome.browserAction.setBadgeText({ text: 'err!', tabId: last_tab_id }); break; case badge_styles.ICON: chrome.browserAction.setIcon({ path: 'images/error.png', tabId: last_tab_id }); break; case badge_styles.CHROMED: chrome.browserAction.setIcon({ path: 'images/chromed_error.png', tabId: last_tab_id }); break; } } }; function onComplete(xhr) { try { if (xhr.srcElement.status == 201) { if ($.db('auto_close') === '1') { chrome.tabs.remove(last_tab_id); } else { badge.saved(); } } else { badge.error(); } } catch(e) {} } // TODO: gmail support for mails. function sendRequest(url, selection, title) { var username = $.db('username'); var password = $.db('password') || ''; if (!username) { badge.idle(); chrome.tabs.create({ url: chrome.extension.getURL('options.html#setup') }); return; } chrome.tabs.get(last_tab_id, function(tab) { if(/^https?:\/\/www\.google\.com\/reader/.test(url)) { chrome.tabs.sendRequest(tab.id, {}, function(response) { if(response.title && response.url) { sendRequest(response.url, response.selection, response.title); } else { badge.idle(tab.id); } }); } else { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = onComplete; title = encodeURIComponent(title || tab.title); var params = { url: url, username: username, password: password, selection: selection || url.match(/https?:\/\/([^\/]+)/)[1] }; title = title ? ("&title=" + title) : "&auto-title=1"; xhr.open("GET", 'https://www.instapaper.com/api/add?' + $.param(params) + title, true); xhr.send(); } }); } function readLater(tab, selection) { last_tab_id = tab.id; badge.saving(); sendRequest(tab.url, selection); } -chrome.contextMenus.create({ - title: 'Read later (send to instapaper)', - contexts: ['link'], - onclick: function(data, tab) { - readLater({id: tab.id, url: data.linkUrl}); - } -}); +if($.db('cx_read_later') === '1') { + chrome.contextMenus.create({ + title: 'Read later (send to instapaper)', + contexts: ['link'], + onclick: function(data, tab) { + readLater({id: tab.id, url: data.linkUrl}); + } + }); +} + +if($.db('cx_text_view') === '1') { + chrome.contextMenus.create({ + title: 'Text view', + contexts: ['page', 'link'], + onclick: function(data, tab) { + chrome.tabs.update(tab.id, { + url: "http://www.instapaper.com/text?u=" + encodeURIComponent(data.linkUrl || data.pageUrl) + }); + } + }); +} + +if($.db('cx_unread') === '1') { + chrome.contextMenus.create({ + title: 'Go to your unread items', + contexts: ['all'], + onclick: function(data, tab) { + chrome.tabs.create({ + url: "http://www.instapaper.com/u" + }); + } + }); +} + +if($.db('cx_starred') === '1') { + chrome.contextMenus.create({ + title: 'Go to your starred items', + contexts: ['all'], + onclick: function(data, tab) { + chrome.tabs.create({ + url: "http://www.instapaper.com/starred" + }); + } + }); +} + +if($.db('cx_archive') === '1') { + chrome.contextMenus.create({ + title: 'Go to your archived items', + contexts: ['all'], + onclick: function(data, tab) { + chrome.tabs.create({ + url: "http://www.instapaper.com/archive" + }); + } + }); +} chrome.tabs.onUpdated.addListener(function(tabId) { badge.idle(tabId); }); chrome.browserAction.onClicked.addListener(readLater); // from key shortcut chrome.extension.onRequest.addListener(function(request, sender, sendResponse) { if (sender.tab) { if (request.hasOwnProperty('keystroke')) { var shortcut = $.db('shortcut'); var ctrlKey = (shortcut.ctrlKey == request.keystroke.ctrlKey), altKey = (shortcut.altKey == request.keystroke.altKey), shiftKey = (shortcut.shiftKey == request.keystroke.shiftKey), keyCode = (shortcut.keyCode == request.keystroke.keyCode); sendResponse({ shortcutPressed: (ctrlKey && altKey && shiftKey & keyCode) }); } else if (request.hasOwnProperty('selection')) { readLater(sender.tab, request.selection); } } }); diff --git a/javascripts/options.js b/javascripts/options.js index 0762987..1997bf6 100644 --- a/javascripts/options.js +++ b/javascripts/options.js @@ -1,130 +1,160 @@ (function($) { $.flash = function(msg) { $('.flash').text(msg).fadeIn('fast'); }; })(jQuery); var Options = function() { var values = { username: null, password: null, show_popup: '1', auto_close: false, badge_style: 0, shortcut: { keyCode: 83, altKey: true, ctrlKey: false, shiftKey: true - } + }, + cx_read_later: '1', + cx_text_view: '0', + cx_unread: '0', + cx_starred: '0', + cx_archive: '0' }; var ui = { username: $('input#username'), password: $('input#password'), show_popup: $('input#show_popup'), auto_close: $('input#auto_close'), badge_style: $('select#badge_style'), - shortcut: $('input#shortcut') + shortcut: $('input#shortcut'), + cx_read_later: $('input#cx_read_later'), + cx_text_view: $('input#cx_text_view'), + cx_unread: $('input#cx_unread'), + cx_starred: $('input#cx_starred'), + cx_archive: $('input#cx_archive') }; var dbOrDefault = function(db_key) { return $.db(db_key) || values[db_key]; }; var authenticateCredentials = function() { var xhr = new XMLHttpRequest(); var username = encodeURIComponent(ui.username.val()); var password = encodeURIComponent(ui.password.val()); xhr.onreadystatechange = function(response) { if(response.srcElement && response.srcElement.readyState == 4) { $('.column.label.auth').show('fast').removeClass('ok error'); if(response.srcElement.status == 200) { $('.column.label.auth').addClass('ok').text('Your credentials are valid.'); } else { $('.column.label.auth').addClass('error').text('Your username or password is incorrect. Please double check them.'); } } } xhr.open("GET", 'https://www.instapaper.com/api/authenticate?username=' + username + '&password=' + password, true); xhr.send(); }; ui.username.bind('change', authenticateCredentials); ui.password.bind('change', authenticateCredentials); return { humanizeKeystrokes: function(e) { var key = String.fromCharCode(e.keyCode); var special = ""; if (e.ctrlKey) { special += "Ctrl + "; } if (e.altKey) { special += "Alt + "; } if (e.shiftKey) { special += "Shift + "; } return special + key; }, restore: function() { if (location.hash === '#setup') { $.flash('Enter your Instapaper credentials in order to save an URL.'); } ui.username.val(dbOrDefault('username')); ui.password.val(dbOrDefault('password')); if (dbOrDefault('show_popup') === '1') { ui.show_popup.attr('checked', true); } if (dbOrDefault('auto_close') === '1') { ui.auto_close.attr('checked', true); } + if (dbOrDefault('cx_read_later') === '1') { + ui.cx_read_later.attr('checked', true); + } + if (dbOrDefault('cx_text_view') === '1') { + ui.cx_text_view.attr('checked', true); + } + if (dbOrDefault('cx_unread') === '1') { + ui.cx_unread.attr('checked', true); + } + if (dbOrDefault('cx_starred') === '1') { + ui.cx_starred.attr('checked', true); + } + if (dbOrDefault('cx_archive') === '1') { + ui.cx_archive.attr('checked', true); + } ui.badge_style.val(dbOrDefault('badge_style')); ui.shortcut.val(this.humanizeKeystrokes(dbOrDefault('shortcut'))) .data('keys', dbOrDefault('shortcut')); }, save: function() { $.db('username', ui.username.val()); $.db('password', ui.password.val()); $.db('show_popup', ui.show_popup.is(':checked') ? '1': '0'); $.db('auto_close', ui.auto_close.is(':checked') ? '1': '0'); + $.db('cx_read_later', ui.cx_read_later.is(':checked') ? '1': '0'); + $.db('cx_text_view', ui.cx_text_view.is(':checked') ? '1': '0'); + $.db('cx_unread', ui.cx_unread.is(':checked') ? '1': '0'); + $.db('cx_starred', ui.cx_starred.is(':checked') ? '1': '0'); + $.db('cx_archive', ui.cx_archive.is(':checked') ? '1': '0'); $.db('badge_style', ui.badge_style.val()); $.db('shortcut', ui.shortcut.data('keys')); $.flash('Options saved successfully!'); } }; }; $(function() { var o = new Options(); o.restore(); $('.flash').click(function() { $(this).fadeOut('slow'); return false; }); $('.close').click(function() { window.close(); }); $('form.options').submit(function() { o.save(); return false; }); $('#shortcut').keydown(function(e) { $(this).val(o.humanizeKeystrokes(e)).data('keys', { ctrlKey: e.ctrlKey, altKey: e.altKey, shiftKey: e.shiftKey, keyCode: e.which }); return false; }); }); diff --git a/manifest.json b/manifest.json index 20d2501..94cd359 100644 --- a/manifest.json +++ b/manifest.json @@ -1,35 +1,35 @@ { "name": "Instachrome", - "version": "1.4.2", + "version": "1.4.2.1", "description": "Save your URLs to Instapaper", "options_page": "options.html", "background_page": "background.html", "content_scripts": [{ "matches": ["http://*/*", "https://*/*"], "js": ["javascripts/keyboard.js"], "run_at": "document_start" }, { "matches": ["http://www.google.com/reader/*"], "js": ["javascripts/greader.js"], "run_at": "document_end" }], "browser_action": { "default_icon": "images/default.png", "default_title": "Save to Instapaper", "popup": "popup.html" }, "icons": { "16": "images/icon/16.png", "32": "images/icon/32.png", "48": "images/icon/48.png", "128": "images/icon/128.png" }, "permissions": [ "contextMenus", "tabs", "http://ajax.googleapis.com/ajax/libs/jquery/**/*", "http://www.instapaper.com/api/", "https://www.instapaper.com/api/", "http://www.google.com/reader/*" ] } diff --git a/options.html b/options.html index cf5ce33..2f88c8c 100644 --- a/options.html +++ b/options.html @@ -1,115 +1,163 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta charset="utf-8" /> <title>Instachrome Options</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript" src="javascripts/elastic.js"></script> <script type="text/javascript" src="javascripts/app.js"></script> <script type="text/javascript" src="javascripts/options.js"></script> <link href="stylesheets/elastic.css" rel="stylesheet" type="text/css" /> <link href="stylesheets/options.css" rel="stylesheet" type="text/css" /> </head> <body> <a href="http://pledgie.com/campaigns/9023" class="ribbon left"></a> <a href="http://github.com/edgarjs/instachrome" class="ribbon right"></a> <div class="container wrapper"> <h1 class="title">Instachrome Options</h1> <div class="flash"></div> <form class="options" action="#" method="post"> <fieldset class="container set"> <legend>Instapaper credentials</legend> <div class="container pad"> <div class="unit on-2 columns same-height"> <div class="column label"> <label for="username" class="vertical-center">Username:</label> </div> <div class="column"> <input type="text" class="text" spellcheck="false" name="username" id="username" /> </div> <div class="column label"> <label for="password">Password:</label> <div class="description">(If you have one)</div> </div> <div class="column"> <input type="password" class="text" name="password" id="password" /> </div> <div class="column label span-2 auth"> Your username or password is incorrect. Please double check them. </div> <div class="column label span-2"> <a href="http://www.instapaper.com/user/register" class="vertical-center description">Get a free account</a> </div> </div> </div> </fieldset> <fieldset class="container set"> <legend>Extras</legend> <div class="container pad"> <div class="unit on-2 columns same-height"> <div class="column label"> <label for="show_popup" class="vertical-center">Show popup:</label> </div> <div class="column"> <input type="checkbox" name="show_popup" class="vertical-center" id="show_popup" value="1" /> </div> <div class="column label"> <label for="auto_close">Auto close:</label> <div class="description">(Close tab after saved)</div> </div> <div class="column"> <input type="checkbox" name="auto_close" class="vertical-center" id="auto_close" value="1" /> </div> <div class="column label"> <label for="badge_style" class="vertical-center">Badge style:</label> </div> <div class="column"> <select name="badge_style" id="badge_style"> <option value="0">Text</option> <option value="1">Tick/Circle/Cross Icons</option> <option value="2">Chromed icons</option> </select> </div> <div class="column label"> <label for="shortcut" class="vertical-center">Keyboard shortcut:</label> <div class="description">(Beta - Not all shortcuts may work)</div> </div> <div class="column"> <input type="text" name="shortcut" id="shortcut" class="text" /> </div> </div> </div> </fieldset> + <fieldset class="container set"> + <legend>Context Menus</legend> + <div class="container pad"> + <div class="unit on-1 columns"> + <div class="column label"> + <div class="description">You'll need to restart the browser for context menus to take effect.</p> + </div> + </div> + <div class="unit on-2 columns same-height"> + + <div class="column label"> + <label for="cx_read_later" class="vertical-center">Read Later</label> + </div> + <div class="column"> + <input type="checkbox" name="cx_read_later" class="vertical-center" id="cx_read_later" value="1" /> + </div> + + <div class="column label"> + <label for="cx_text_view" class="vertical-center">Text view</label> + </div> + <div class="column"> + <input type="checkbox" name="cx_text_view" class="vertical-center" id="cx_text_view" value="1" /> + </div> + + <div class="column label"> + <label for="cx_unread" class="vertical-center">Go to unread</label> + </div> + <div class="column"> + <input type="checkbox" name="cx_unread" class="vertical-center" id="cx_unread" value="1" /> + </div> + + <div class="column label"> + <label for="cx_starred" class="vertical-center">Go to starred</label> + </div> + <div class="column"> + <input type="checkbox" name="cx_starred" class="vertical-center" id="cx_starred" value="1" /> + </div> + + <div class="column label"> + <label for="cx_archive" class="vertical-center">Go to archive</label> + </div> + <div class="column"> + <input type="checkbox" name="cx_archive" class="vertical-center" id="cx_archive" value="1" /> + </div> + </div> + </div> + </fieldset> + <input type="submit" class="button" value="Save" /> or <a href="#" class="close">Close</a> </form> <div class="container footer"> <p> by <a href="http://edgarjs.mx">Edgar J. Suárez</a> | <a href="http://twitter.com/edgarjs">Twitter</a> | <a href="https://chrome.google.com/extensions/detail/fldildgghjoohccppflaohodcnmlacpb">Extension page</a> | <a href="http://instapaper.com">Instapaper</a> <br /> This page is powered by <a href="http://elasticss.com">Elastic CSS</a> | Icons by <a href="http://famfamfam.com">famfamfam.com</a> </p> </div> </div> </body> </html>
edgarjs/instachrome
53e882ddc0ba8e5070558726763fe0ee8b3251fb
adding context menu
diff --git a/images/icon/16.png b/images/icon/16.png new file mode 100644 index 0000000..86625db Binary files /dev/null and b/images/icon/16.png differ diff --git a/javascripts/background.js b/javascripts/background.js index 4b59dd6..102ec26 100644 --- a/javascripts/background.js +++ b/javascripts/background.js @@ -1,194 +1,202 @@ var last_tab_id; var badge_styles = { TEXT: 0, ICON: 1, CHROMED: 2 }; var badge = { idle: function(tabId) { var tabImg = 'images/default.png'; if (parseInt($.db('badge_style')) === badge_styles.CHROMED) { tabImg = 'images/chromed_default.png'; } function setIcon(id) { chrome.browserAction.setIcon({ path: tabImg, tabId: id }); chrome.browserAction.setBadgeText({ text: '', tabId: id }); } if(!tabId) { chrome.tabs.getSelected(null, function(tab) { setIcon(tab.id); }); } else { setIcon(tabId); } }, saving: function () { switch (parseInt($.db('badge_style'))) { case badge_styles.TEXT: // TODO Customize color chrome.browserAction.setBadgeBackgroundColor({ color: [82, 168, 207, 255], tabId: last_tab_id }); chrome.browserAction.setBadgeText({ text: '...', tabId: last_tab_id }); break; case badge_styles.ICON: chrome.browserAction.setIcon({ path: 'images/saving.png', tabId: last_tab_id }); break; case badge_styles.CHROMED: chrome.browserAction.setIcon({ path: 'images/chromed_saving.png', tabId: last_tab_id }); break; } }, saved: function () { switch (parseInt($.db('badge_style'))) { case badge_styles.TEXT: chrome.browserAction.setBadgeBackgroundColor({ color: [53, 181, 49, 255], tabId: last_tab_id }); chrome.browserAction.setBadgeText({ text: 'ok', tabId: last_tab_id }); break; case badge_styles.ICON: chrome.browserAction.setIcon({ path: 'images/saved.png', tabId: last_tab_id }); break; case badge_styles.CHROMED: chrome.browserAction.setIcon({ path: 'images/chromed_saved.png', tabId: last_tab_id }); break; } }, error: function () { switch (parseInt($.db('badge_style'))) { case badge_styles.TEXT: chrome.browserAction.setBadgeBackgroundColor({ color: [255, 0, 0, 255], tabId: last_tab_id }); chrome.browserAction.setBadgeText({ text: 'err!', tabId: last_tab_id }); break; case badge_styles.ICON: chrome.browserAction.setIcon({ path: 'images/error.png', tabId: last_tab_id }); break; case badge_styles.CHROMED: chrome.browserAction.setIcon({ path: 'images/chromed_error.png', tabId: last_tab_id }); break; } } }; function onComplete(xhr) { try { if (xhr.srcElement.status == 201) { if ($.db('auto_close') === '1') { chrome.tabs.remove(last_tab_id); } else { badge.saved(); } } else { badge.error(); } } catch(e) {} } // TODO: gmail support for mails. function sendRequest(url, selection, title) { var username = $.db('username'); var password = $.db('password') || ''; if (!username) { badge.idle(); chrome.tabs.create({ url: chrome.extension.getURL('options.html#setup') }); return; } chrome.tabs.get(last_tab_id, function(tab) { if(/^https?:\/\/www\.google\.com\/reader/.test(url)) { chrome.tabs.sendRequest(tab.id, {}, function(response) { if(response.title && response.url) { sendRequest(response.url, response.selection, response.title); } else { badge.idle(tab.id); } }); } else { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = onComplete; title = encodeURIComponent(title || tab.title); var params = { url: url, username: username, password: password, selection: selection || url.match(/https?:\/\/([^\/]+)/)[1] }; title = title ? ("&title=" + title) : "&auto-title=1"; xhr.open("GET", 'https://www.instapaper.com/api/add?' + $.param(params) + title, true); xhr.send(); } }); } function readLater(tab, selection) { last_tab_id = tab.id; badge.saving(); sendRequest(tab.url, selection); } +chrome.contextMenus.create({ + title: 'Read later (send to instapaper)', + contexts: ['link'], + onclick: function(data, tab) { + readLater({id: tab.id, url: data.linkUrl}); + } +}); + chrome.tabs.onUpdated.addListener(function(tabId) { badge.idle(tabId); }); chrome.browserAction.onClicked.addListener(readLater); // from key shortcut chrome.extension.onRequest.addListener(function(request, sender, sendResponse) { if (sender.tab) { if (request.hasOwnProperty('keystroke')) { var shortcut = $.db('shortcut'); var ctrlKey = (shortcut.ctrlKey == request.keystroke.ctrlKey), altKey = (shortcut.altKey == request.keystroke.altKey), shiftKey = (shortcut.shiftKey == request.keystroke.shiftKey), keyCode = (shortcut.keyCode == request.keystroke.keyCode); sendResponse({ shortcutPressed: (ctrlKey && altKey && shiftKey & keyCode) }); } else if (request.hasOwnProperty('selection')) { readLater(sender.tab, request.selection); } } }); diff --git a/manifest.json b/manifest.json index f81f951..20d2501 100644 --- a/manifest.json +++ b/manifest.json @@ -1,33 +1,35 @@ { "name": "Instachrome", - "version": "1.4.1.1", + "version": "1.4.2", "description": "Save your URLs to Instapaper", "options_page": "options.html", "background_page": "background.html", "content_scripts": [{ "matches": ["http://*/*", "https://*/*"], "js": ["javascripts/keyboard.js"], "run_at": "document_start" }, { "matches": ["http://www.google.com/reader/*"], "js": ["javascripts/greader.js"], "run_at": "document_end" }], "browser_action": { "default_icon": "images/default.png", "default_title": "Save to Instapaper", "popup": "popup.html" }, "icons": { + "16": "images/icon/16.png", "32": "images/icon/32.png", "48": "images/icon/48.png", "128": "images/icon/128.png" }, "permissions": [ + "contextMenus", "tabs", "http://ajax.googleapis.com/ajax/libs/jquery/**/*", "http://www.instapaper.com/api/", "https://www.instapaper.com/api/", "http://www.google.com/reader/*" ] }
edgarjs/instachrome
b44b08126e0b5b4592389d2c71956f32db0da9ba
Fixing small bump to err icon
diff --git a/javascripts/background.js b/javascripts/background.js index b32e99f..4b59dd6 100644 --- a/javascripts/background.js +++ b/javascripts/background.js @@ -1,196 +1,194 @@ var last_tab_id; var badge_styles = { TEXT: 0, ICON: 1, CHROMED: 2 }; var badge = { idle: function(tabId) { var tabImg = 'images/default.png'; if (parseInt($.db('badge_style')) === badge_styles.CHROMED) { tabImg = 'images/chromed_default.png'; } function setIcon(id) { chrome.browserAction.setIcon({ path: tabImg, tabId: id }); chrome.browserAction.setBadgeText({ text: '', tabId: id }); } if(!tabId) { chrome.tabs.getSelected(null, function(tab) { setIcon(tab.id); }); } else { setIcon(tabId); } }, saving: function () { switch (parseInt($.db('badge_style'))) { case badge_styles.TEXT: // TODO Customize color chrome.browserAction.setBadgeBackgroundColor({ color: [82, 168, 207, 255], tabId: last_tab_id }); chrome.browserAction.setBadgeText({ text: '...', tabId: last_tab_id }); break; case badge_styles.ICON: chrome.browserAction.setIcon({ path: 'images/saving.png', tabId: last_tab_id }); break; case badge_styles.CHROMED: chrome.browserAction.setIcon({ path: 'images/chromed_saving.png', tabId: last_tab_id }); break; } }, saved: function () { switch (parseInt($.db('badge_style'))) { case badge_styles.TEXT: chrome.browserAction.setBadgeBackgroundColor({ color: [53, 181, 49, 255], tabId: last_tab_id }); chrome.browserAction.setBadgeText({ text: 'ok', tabId: last_tab_id }); break; case badge_styles.ICON: chrome.browserAction.setIcon({ path: 'images/saved.png', tabId: last_tab_id }); break; case badge_styles.CHROMED: chrome.browserAction.setIcon({ path: 'images/chromed_saved.png', tabId: last_tab_id }); break; } }, error: function () { switch (parseInt($.db('badge_style'))) { case badge_styles.TEXT: chrome.browserAction.setBadgeBackgroundColor({ color: [255, 0, 0, 255], tabId: last_tab_id }); chrome.browserAction.setBadgeText({ text: 'err!', tabId: last_tab_id }); break; case badge_styles.ICON: chrome.browserAction.setIcon({ path: 'images/error.png', tabId: last_tab_id }); break; case badge_styles.CHROMED: chrome.browserAction.setIcon({ path: 'images/chromed_error.png', tabId: last_tab_id }); break; } } }; function onComplete(xhr) { try { if (xhr.srcElement.status == 201) { if ($.db('auto_close') === '1') { chrome.tabs.remove(last_tab_id); } else { badge.saved(); } } else { badge.error(); } - } catch(e) { - badge.error(); - } + } catch(e) {} } // TODO: gmail support for mails. function sendRequest(url, selection, title) { var username = $.db('username'); var password = $.db('password') || ''; if (!username) { badge.idle(); chrome.tabs.create({ url: chrome.extension.getURL('options.html#setup') }); return; } chrome.tabs.get(last_tab_id, function(tab) { if(/^https?:\/\/www\.google\.com\/reader/.test(url)) { chrome.tabs.sendRequest(tab.id, {}, function(response) { if(response.title && response.url) { sendRequest(response.url, response.selection, response.title); } else { badge.idle(tab.id); } }); } else { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = onComplete; title = encodeURIComponent(title || tab.title); var params = { url: url, username: username, password: password, selection: selection || url.match(/https?:\/\/([^\/]+)/)[1] }; title = title ? ("&title=" + title) : "&auto-title=1"; xhr.open("GET", 'https://www.instapaper.com/api/add?' + $.param(params) + title, true); xhr.send(); } }); } function readLater(tab, selection) { last_tab_id = tab.id; badge.saving(); sendRequest(tab.url, selection); } chrome.tabs.onUpdated.addListener(function(tabId) { badge.idle(tabId); }); chrome.browserAction.onClicked.addListener(readLater); // from key shortcut chrome.extension.onRequest.addListener(function(request, sender, sendResponse) { if (sender.tab) { if (request.hasOwnProperty('keystroke')) { var shortcut = $.db('shortcut'); var ctrlKey = (shortcut.ctrlKey == request.keystroke.ctrlKey), altKey = (shortcut.altKey == request.keystroke.altKey), shiftKey = (shortcut.shiftKey == request.keystroke.shiftKey), keyCode = (shortcut.keyCode == request.keystroke.keyCode); sendResponse({ shortcutPressed: (ctrlKey && altKey && shiftKey & keyCode) }); } else if (request.hasOwnProperty('selection')) { readLater(sender.tab, request.selection); } } }); diff --git a/manifest.json b/manifest.json index 9acf651..f81f951 100644 --- a/manifest.json +++ b/manifest.json @@ -1,33 +1,33 @@ { "name": "Instachrome", - "version": "1.4.1", + "version": "1.4.1.1", "description": "Save your URLs to Instapaper", "options_page": "options.html", "background_page": "background.html", "content_scripts": [{ "matches": ["http://*/*", "https://*/*"], "js": ["javascripts/keyboard.js"], "run_at": "document_start" }, { "matches": ["http://www.google.com/reader/*"], "js": ["javascripts/greader.js"], "run_at": "document_end" }], "browser_action": { "default_icon": "images/default.png", "default_title": "Save to Instapaper", "popup": "popup.html" }, "icons": { "32": "images/icon/32.png", "48": "images/icon/48.png", "128": "images/icon/128.png" }, "permissions": [ "tabs", "http://ajax.googleapis.com/ajax/libs/jquery/**/*", "http://www.instapaper.com/api/", "https://www.instapaper.com/api/", "http://www.google.com/reader/*" ] }
edgarjs/instachrome
03ac2f7a041ba570a1855bbdc775d7c5fa755afc
fixing chromed icons
diff --git a/images/chromed_default.png b/images/chromed_default.png index 9dd1ad6..49632dd 100644 Binary files a/images/chromed_default.png and b/images/chromed_default.png differ diff --git a/images/chromed_error.png b/images/chromed_error.png index 1d80e5e..f4959c6 100644 Binary files a/images/chromed_error.png and b/images/chromed_error.png differ diff --git a/images/chromed_saved.png b/images/chromed_saved.png index 2930730..5f5a535 100644 Binary files a/images/chromed_saved.png and b/images/chromed_saved.png differ diff --git a/images/chromed_saving.png b/images/chromed_saving.png index a40b5c0..94aee3b 100644 Binary files a/images/chromed_saving.png and b/images/chromed_saving.png differ diff --git a/javascripts/background.js b/javascripts/background.js index cec1d31..b32e99f 100644 --- a/javascripts/background.js +++ b/javascripts/background.js @@ -1,183 +1,196 @@ var last_tab_id; var badge_styles = { TEXT: 0, ICON: 1, CHROMED: 2 }; var badge = { - idle: function() { + idle: function(tabId) { var tabImg = 'images/default.png'; if (parseInt($.db('badge_style')) === badge_styles.CHROMED) { tabImg = 'images/chromed_default.png'; } - chrome.browserAction.setIcon({ - path: tabImg, - tabId: last_tab_id - }); - chrome.browserAction.setBadgeText({ - text: '', - tabId: last_tab_id - }); + function setIcon(id) { + chrome.browserAction.setIcon({ + path: tabImg, + tabId: id + }); + chrome.browserAction.setBadgeText({ + text: '', + tabId: id + }); + } + if(!tabId) { + chrome.tabs.getSelected(null, function(tab) { + setIcon(tab.id); + }); + } else { + setIcon(tabId); + } }, saving: function () { switch (parseInt($.db('badge_style'))) { case badge_styles.TEXT: // TODO Customize color chrome.browserAction.setBadgeBackgroundColor({ color: [82, 168, 207, 255], tabId: last_tab_id }); chrome.browserAction.setBadgeText({ text: '...', tabId: last_tab_id }); break; case badge_styles.ICON: chrome.browserAction.setIcon({ path: 'images/saving.png', tabId: last_tab_id }); break; case badge_styles.CHROMED: chrome.browserAction.setIcon({ path: 'images/chromed_saving.png', tabId: last_tab_id }); break; } }, saved: function () { switch (parseInt($.db('badge_style'))) { case badge_styles.TEXT: chrome.browserAction.setBadgeBackgroundColor({ color: [53, 181, 49, 255], tabId: last_tab_id }); chrome.browserAction.setBadgeText({ text: 'ok', tabId: last_tab_id }); break; case badge_styles.ICON: chrome.browserAction.setIcon({ path: 'images/saved.png', tabId: last_tab_id }); break; case badge_styles.CHROMED: chrome.browserAction.setIcon({ path: 'images/chromed_saved.png', tabId: last_tab_id }); break; } }, error: function () { switch (parseInt($.db('badge_style'))) { case badge_styles.TEXT: chrome.browserAction.setBadgeBackgroundColor({ color: [255, 0, 0, 255], tabId: last_tab_id }); chrome.browserAction.setBadgeText({ text: 'err!', tabId: last_tab_id }); break; case badge_styles.ICON: chrome.browserAction.setIcon({ path: 'images/error.png', tabId: last_tab_id }); break; case badge_styles.CHROMED: chrome.browserAction.setIcon({ path: 'images/chromed_error.png', tabId: last_tab_id }); break; } } }; function onComplete(xhr) { - if (xhr.srcElement.status == 201) { - if ($.db('auto_close') === '1') { - chrome.tabs.remove(last_tab_id); + try { + if (xhr.srcElement.status == 201) { + if ($.db('auto_close') === '1') { + chrome.tabs.remove(last_tab_id); + } else { + badge.saved(); + } } else { - badge.saved(); + badge.error(); } - } else { + } catch(e) { badge.error(); } } // TODO: gmail support for mails. function sendRequest(url, selection, title) { var username = $.db('username'); var password = $.db('password') || ''; if (!username) { badge.idle(); chrome.tabs.create({ url: chrome.extension.getURL('options.html#setup') }); return; } chrome.tabs.get(last_tab_id, function(tab) { if(/^https?:\/\/www\.google\.com\/reader/.test(url)) { chrome.tabs.sendRequest(tab.id, {}, function(response) { if(response.title && response.url) { sendRequest(response.url, response.selection, response.title); } else { - badge.idle(); + badge.idle(tab.id); } }); } else { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = onComplete; title = encodeURIComponent(title || tab.title); var params = { url: url, username: username, password: password, selection: selection || url.match(/https?:\/\/([^\/]+)/)[1] }; title = title ? ("&title=" + title) : "&auto-title=1"; xhr.open("GET", 'https://www.instapaper.com/api/add?' + $.param(params) + title, true); xhr.send(); } }); } function readLater(tab, selection) { last_tab_id = tab.id; badge.saving(); sendRequest(tab.url, selection); } chrome.tabs.onUpdated.addListener(function(tabId) { - badge.idle(); + badge.idle(tabId); }); chrome.browserAction.onClicked.addListener(readLater); // from key shortcut chrome.extension.onRequest.addListener(function(request, sender, sendResponse) { if (sender.tab) { if (request.hasOwnProperty('keystroke')) { var shortcut = $.db('shortcut'); var ctrlKey = (shortcut.ctrlKey == request.keystroke.ctrlKey), altKey = (shortcut.altKey == request.keystroke.altKey), shiftKey = (shortcut.shiftKey == request.keystroke.shiftKey), keyCode = (shortcut.keyCode == request.keystroke.keyCode); sendResponse({ shortcutPressed: (ctrlKey && altKey && shiftKey & keyCode) }); } else if (request.hasOwnProperty('selection')) { readLater(sender.tab, request.selection); } } }); diff --git a/manifest.json b/manifest.json index c497cdd..9acf651 100644 --- a/manifest.json +++ b/manifest.json @@ -1,33 +1,33 @@ { "name": "Instachrome", - "version": "1.4.0", + "version": "1.4.1", "description": "Save your URLs to Instapaper", "options_page": "options.html", "background_page": "background.html", "content_scripts": [{ "matches": ["http://*/*", "https://*/*"], "js": ["javascripts/keyboard.js"], "run_at": "document_start" }, { "matches": ["http://www.google.com/reader/*"], "js": ["javascripts/greader.js"], "run_at": "document_end" }], "browser_action": { "default_icon": "images/default.png", "default_title": "Save to Instapaper", "popup": "popup.html" }, "icons": { "32": "images/icon/32.png", "48": "images/icon/48.png", "128": "images/icon/128.png" }, "permissions": [ "tabs", "http://ajax.googleapis.com/ajax/libs/jquery/**/*", "http://www.instapaper.com/api/", "https://www.instapaper.com/api/", "http://www.google.com/reader/*" ] }
edgarjs/instachrome
3933439a109f6472cd181bd0def73dcb0ef57af2
Support for GReader
diff --git a/background.html b/background.html index eea0918..037b88d 100644 --- a/background.html +++ b/background.html @@ -1,13 +1,13 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta charset="utf-8" /> <title>Instachrome Popup</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript" src="javascripts/app.js"></script> <script type="text/javascript" src="javascripts/background.js"></script> </head> <body> </body> -</html> \ No newline at end of file +</html> diff --git a/javascripts/background.js b/javascripts/background.js index dce3c76..cec1d31 100644 --- a/javascripts/background.js +++ b/javascripts/background.js @@ -1,179 +1,183 @@ var last_tab_id; var badge_styles = { TEXT: 0, ICON: 1, CHROMED: 2 }; -var description_styles = { - DEFAULT: 0, - SITEURL: 1 -}; -function onComplete(xhr) { - if (xhr.srcElement.status == 201) { - if ($.db('auto_close') === '1') { - chrome.tabs.remove(last_tab_id); - } else { - switch (parseInt($.db('badge_style'))) { - case badge_styles.TEXT: - chrome.browserAction.setBadgeBackgroundColor({ - color: - [53, 181, 49, 255], - tabId: last_tab_id - }); - chrome.browserAction.setBadgeText({ - text: 'ok', - tabId: last_tab_id - }); - break; - case badge_styles.ICON: - chrome.browserAction.setIcon({ - path: - 'images/saved.png', - tabId: last_tab_id - }); - break; - case badge_styles.CHROMED: - chrome.browserAction.setIcon({ - path: - 'images/chromed_saved.png', - tabId: last_tab_id - }); - break; - } +var badge = { + idle: function() { + var tabImg = 'images/default.png'; + if (parseInt($.db('badge_style')) === badge_styles.CHROMED) { + tabImg = 'images/chromed_default.png'; } - } else { + chrome.browserAction.setIcon({ + path: tabImg, + tabId: last_tab_id + }); + chrome.browserAction.setBadgeText({ + text: '', + tabId: last_tab_id + }); + }, + saving: function () { switch (parseInt($.db('badge_style'))) { case badge_styles.TEXT: + // TODO Customize color chrome.browserAction.setBadgeBackgroundColor({ - color: - [255, 0, 0, 255], + color: [82, 168, 207, 255], + tabId: last_tab_id + }); + chrome.browserAction.setBadgeText({ + text: '...', + tabId: last_tab_id + }); + break; + case badge_styles.ICON: + chrome.browserAction.setIcon({ + path: 'images/saving.png', + tabId: last_tab_id + }); + break; + case badge_styles.CHROMED: + chrome.browserAction.setIcon({ + path: 'images/chromed_saving.png', + tabId: last_tab_id + }); + break; + } + }, + saved: function () { + switch (parseInt($.db('badge_style'))) { + case badge_styles.TEXT: + chrome.browserAction.setBadgeBackgroundColor({ + color: [53, 181, 49, 255], + tabId: last_tab_id + }); + chrome.browserAction.setBadgeText({ + text: 'ok', + tabId: last_tab_id + }); + break; + case badge_styles.ICON: + chrome.browserAction.setIcon({ + path: 'images/saved.png', + tabId: last_tab_id + }); + break; + case badge_styles.CHROMED: + chrome.browserAction.setIcon({ + path: 'images/chromed_saved.png', + tabId: last_tab_id + }); + break; + } + }, + error: function () { + switch (parseInt($.db('badge_style'))) { + case badge_styles.TEXT: + chrome.browserAction.setBadgeBackgroundColor({ + color: [255, 0, 0, 255], tabId: last_tab_id }); chrome.browserAction.setBadgeText({ text: 'err!', tabId: last_tab_id }); break; case badge_styles.ICON: chrome.browserAction.setIcon({ - path: - 'images/error.png', + path: 'images/error.png', tabId: last_tab_id }); break; case badge_styles.CHROMED: chrome.browserAction.setIcon({ - path: - 'images/chromed_error.png', + path: 'images/chromed_error.png', tabId: last_tab_id }); break; } } +}; + +function onComplete(xhr) { + if (xhr.srcElement.status == 201) { + if ($.db('auto_close') === '1') { + chrome.tabs.remove(last_tab_id); + } else { + badge.saved(); + } + } else { + badge.error(); + } } // TODO: gmail support for mails. -// TODO: get gReader single articles -function sendRequest(url, selection) { - var xhr = new XMLHttpRequest(); +function sendRequest(url, selection, title) { var username = $.db('username'); var password = $.db('password') || ''; if (!username) { - var tabImg = 'images/default.png'; - if (parseInt($.db('badge_style')) === badge_styles.CHROMED) { - tabImg = 'images/chromed_default.png'; - } - chrome.browserAction.setIcon({ - path: tabImg, - tabId: last_tab_id - }); + badge.idle(); chrome.tabs.create({ url: chrome.extension.getURL('options.html#setup') }); return; } - xhr.onreadystatechange = onComplete; + chrome.tabs.get(last_tab_id, function(tab) { - var theDescript = "Saved from Instachrome"; - if (parseInt($.db('description_style')) === description_styles.SITEURL) { - theDescript = tab.url.match(/https?:\/\/([^\/]+)/)[1]; + if(/^https?:\/\/www\.google\.com\/reader/.test(url)) { + chrome.tabs.sendRequest(tab.id, {}, function(response) { + if(response.title && response.url) { + sendRequest(response.url, response.selection, response.title); + } else { + badge.idle(); + } + }); + } else { + var xhr = new XMLHttpRequest(); + xhr.onreadystatechange = onComplete; + title = encodeURIComponent(title || tab.title); + var params = { + url: url, + username: username, + password: password, + selection: selection || url.match(/https?:\/\/([^\/]+)/)[1] + }; + title = title ? ("&title=" + title) : "&auto-title=1"; + xhr.open("GET", 'https://www.instapaper.com/api/add?' + $.param(params) + title, true); + xhr.send(); } - - var title = encodeURIComponent(tab.title); - var params = { - url: url, - username: username, - password: password, - selection: selection || theDescript - }; - var title = title ? ("&title=" + title) : "&auto-title=1"; - xhr.open("GET", 'https://www.instapaper.com/api/add?' + $.param(params) + title, true); - xhr.send(); }); } function readLater(tab, selection) { last_tab_id = tab.id; - switch (parseInt($.db('badge_style'))) { - case badge_styles.TEXT: - // TODO Customize color - chrome.browserAction.setBadgeBackgroundColor({ - color: - [82, 168, 207, 255], - tabId: last_tab_id - }); - chrome.browserAction.setBadgeText({ - text: '...', - tabId: last_tab_id - }); - break; - case badge_styles.ICON: - chrome.browserAction.setIcon({ - path: - 'images/saving.png', - tabId: last_tab_id - }); - break; - case badge_styles.CHROMED: - chrome.browserAction.setIcon({ - path: - 'images/chromed_saving.png', - tabId: last_tab_id - }); - break; - } + badge.saving(); sendRequest(tab.url, selection); } chrome.tabs.onUpdated.addListener(function(tabId) { - var tabImg = 'images/default.png'; - if (parseInt($.db('badge_style')) === badge_styles.CHROMED) { - tabImg = 'images/chromed_default.png'; - } - chrome.browserAction.setIcon({ - path: tabImg, - tabId: tabId - }); + badge.idle(); }); chrome.browserAction.onClicked.addListener(readLater); // from key shortcut chrome.extension.onRequest.addListener(function(request, sender, sendResponse) { if (sender.tab) { if (request.hasOwnProperty('keystroke')) { var shortcut = $.db('shortcut'); var ctrlKey = (shortcut.ctrlKey == request.keystroke.ctrlKey), altKey = (shortcut.altKey == request.keystroke.altKey), shiftKey = (shortcut.shiftKey == request.keystroke.shiftKey), keyCode = (shortcut.keyCode == request.keystroke.keyCode); sendResponse({ shortcutPressed: (ctrlKey && altKey && shiftKey & keyCode) }); } else if (request.hasOwnProperty('selection')) { readLater(sender.tab, request.selection); } } }); diff --git a/javascripts/greader.js b/javascripts/greader.js new file mode 100644 index 0000000..a8eef1e --- /dev/null +++ b/javascripts/greader.js @@ -0,0 +1,16 @@ +chrome.extension.onRequest.addListener(function(req, sender, sendResponse) { + var entry = document.getElementById('current-entry'); + if(entry) { + var entryTitle = entry.getElementsByClassName('entry-container')[0] + .getElementsByClassName('entry-title')[0]; + var entryUrl = entryTitle.getElementsByClassName('entry-title-link')[0]; + sendResponse({ + title: entryTitle.innerText, + url: entryUrl.href, + selection: getWindowSelection() + }); + } else { + sendResponse({saved: false}); + alert("You don't have any entry expanded. Once you have an entry expanded try saving it for later."); + } +}); diff --git a/javascripts/keyboard.js b/javascripts/keyboard.js index b2e6cdf..9029ea4 100644 --- a/javascripts/keyboard.js +++ b/javascripts/keyboard.js @@ -1,19 +1,24 @@ // keyboard shortcut +function getWindowSelection() { + var selection = ''; + if (window && window.getSelection) { + selection = window.getSelection().toString(); + } else if (document && document.getSelection) { + selection = document.getSelection().toString(); + } + return selection; +} + window.addEventListener('keydown', function(e) { chrome.extension.sendRequest({keystroke: { keyCode: e.keyCode, altKey: e.altKey, ctrlKey: e.ctrlKey, shiftKey: e.shiftKey }}, function(response) { if(response.shortcutPressed) { - var selection = ''; - if (window && window.getSelection) { - selection = window.getSelection().toString(); - } else if (document && document.getSelection) { - selection = document.getSelection().toString(); - } - chrome.extension.sendRequest({selection: selection}, function(r) {}); + chrome.extension.sendRequest({selection: getWindowSelection()}, function(r) {}); } }); }, false); + diff --git a/javascripts/options.js b/javascripts/options.js index a3cca30..0762987 100644 --- a/javascripts/options.js +++ b/javascripts/options.js @@ -1,134 +1,130 @@ (function($) { $.flash = function(msg) { $('.flash').text(msg).fadeIn('fast'); }; })(jQuery); var Options = function() { var values = { username: null, password: null, show_popup: '1', auto_close: false, badge_style: 0, shortcut: { keyCode: 83, altKey: true, ctrlKey: false, shiftKey: true - }, - description_style: 1 + } }; var ui = { username: $('input#username'), password: $('input#password'), show_popup: $('input#show_popup'), auto_close: $('input#auto_close'), badge_style: $('select#badge_style'), - shortcut: $('input#shortcut'), - description_style: $('select#description_style') + shortcut: $('input#shortcut') }; var dbOrDefault = function(db_key) { return $.db(db_key) || values[db_key]; }; var authenticateCredentials = function() { var xhr = new XMLHttpRequest(); var username = encodeURIComponent(ui.username.val()); var password = encodeURIComponent(ui.password.val()); xhr.onreadystatechange = function(response) { if(response.srcElement && response.srcElement.readyState == 4) { $('.column.label.auth').show('fast').removeClass('ok error'); if(response.srcElement.status == 200) { $('.column.label.auth').addClass('ok').text('Your credentials are valid.'); } else { $('.column.label.auth').addClass('error').text('Your username or password is incorrect. Please double check them.'); } } } xhr.open("GET", 'https://www.instapaper.com/api/authenticate?username=' + username + '&password=' + password, true); xhr.send(); }; ui.username.bind('change', authenticateCredentials); ui.password.bind('change', authenticateCredentials); return { humanizeKeystrokes: function(e) { var key = String.fromCharCode(e.keyCode); var special = ""; if (e.ctrlKey) { special += "Ctrl + "; } if (e.altKey) { special += "Alt + "; } if (e.shiftKey) { special += "Shift + "; } return special + key; }, restore: function() { if (location.hash === '#setup') { $.flash('Enter your Instapaper credentials in order to save an URL.'); } ui.username.val(dbOrDefault('username')); ui.password.val(dbOrDefault('password')); if (dbOrDefault('show_popup') === '1') { ui.show_popup.attr('checked', true); } if (dbOrDefault('auto_close') === '1') { ui.auto_close.attr('checked', true); } ui.badge_style.val(dbOrDefault('badge_style')); ui.shortcut.val(this.humanizeKeystrokes(dbOrDefault('shortcut'))) .data('keys', dbOrDefault('shortcut')); - ui.description_style.val(dbOrDefault('description_style')); }, save: function() { $.db('username', ui.username.val()); $.db('password', ui.password.val()); $.db('show_popup', ui.show_popup.is(':checked') ? '1': '0'); $.db('auto_close', ui.auto_close.is(':checked') ? '1': '0'); $.db('badge_style', ui.badge_style.val()); $.db('shortcut', ui.shortcut.data('keys')); - $.db('description_style', ui.description_style.val()); $.flash('Options saved successfully!'); } }; }; $(function() { var o = new Options(); o.restore(); $('.flash').click(function() { $(this).fadeOut('slow'); return false; }); $('.close').click(function() { window.close(); }); $('form.options').submit(function() { o.save(); return false; }); $('#shortcut').keydown(function(e) { $(this).val(o.humanizeKeystrokes(e)).data('keys', { ctrlKey: e.ctrlKey, altKey: e.altKey, shiftKey: e.shiftKey, keyCode: e.which }); return false; }); }); diff --git a/javascripts/popup.js b/javascripts/popup.js index 21ec368..38ec8c1 100644 --- a/javascripts/popup.js +++ b/javascripts/popup.js @@ -1,57 +1,50 @@ $(function() { var show_popup = $.db('show_popup') === "1"; if(!show_popup) { chrome.tabs.getSelected(null, function(tab) { chrome.extension.getBackgroundPage().readLater(tab); }); window.close(); } else { $('ul.links li > a.add').click(function() { chrome.tabs.getSelected(null, function(tab) { chrome.extension.getBackgroundPage().readLater(tab); }); - window.close(); - return false; }); $('ul.links li > a.text').click(function() { chrome.tabs.getSelected(null, function(tab) { chrome.tabs.update(tab.id, { url: "http://www.instapaper.com/text?u=" + encodeURIComponent(tab.url) }); }); - window.close(); - return false; }); $('ul.links li > a.unread').click(function() { chrome.tabs.create({ url: "http://www.instapaper.com/u" }); - window.close(); - return false; }); $('ul.links li > a.starred').click(function() { chrome.tabs.create({ url: "http://www.instapaper.com/starred" }); - window.close(); - return false; }); $('ul.links li > a.archive').click(function() { chrome.tabs.create({ url: "http://www.instapaper.com/archive" }); - window.close(); - return false; }); $('ul.links li > a.options').click(function() { chrome.tabs.create({url: chrome.extension.getURL('options.html')}); + }); + + $('ul.links li > a').click(function () { window.close(); return false; }); } }); diff --git a/manifest.json b/manifest.json index 6716899..c497cdd 100644 --- a/manifest.json +++ b/manifest.json @@ -1,28 +1,33 @@ { "name": "Instachrome", - "version": "1.3.2", + "version": "1.4.0", "description": "Save your URLs to Instapaper", "options_page": "options.html", "background_page": "background.html", "content_scripts": [{ "matches": ["http://*/*", "https://*/*"], "js": ["javascripts/keyboard.js"], "run_at": "document_start" + }, { + "matches": ["http://www.google.com/reader/*"], + "js": ["javascripts/greader.js"], + "run_at": "document_end" }], "browser_action": { "default_icon": "images/default.png", "default_title": "Save to Instapaper", "popup": "popup.html" }, "icons": { "32": "images/icon/32.png", "48": "images/icon/48.png", "128": "images/icon/128.png" }, "permissions": [ "tabs", "http://ajax.googleapis.com/ajax/libs/jquery/**/*", "http://www.instapaper.com/api/", - "https://www.instapaper.com/api/" + "https://www.instapaper.com/api/", + "http://www.google.com/reader/*" ] } diff --git a/options.html b/options.html index ae04a68..cf5ce33 100644 --- a/options.html +++ b/options.html @@ -1,124 +1,115 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta charset="utf-8" /> <title>Instachrome Options</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript" src="javascripts/elastic.js"></script> <script type="text/javascript" src="javascripts/app.js"></script> <script type="text/javascript" src="javascripts/options.js"></script> <link href="stylesheets/elastic.css" rel="stylesheet" type="text/css" /> <link href="stylesheets/options.css" rel="stylesheet" type="text/css" /> </head> <body> <a href="http://pledgie.com/campaigns/9023" class="ribbon left"></a> <a href="http://github.com/edgarjs/instachrome" class="ribbon right"></a> <div class="container wrapper"> <h1 class="title">Instachrome Options</h1> <div class="flash"></div> <form class="options" action="#" method="post"> <fieldset class="container set"> <legend>Instapaper credentials</legend> <div class="container pad"> <div class="unit on-2 columns same-height"> <div class="column label"> <label for="username" class="vertical-center">Username:</label> </div> <div class="column"> <input type="text" class="text" spellcheck="false" name="username" id="username" /> </div> <div class="column label"> <label for="password">Password:</label> <div class="description">(If you have one)</div> </div> <div class="column"> <input type="password" class="text" name="password" id="password" /> </div> <div class="column label span-2 auth"> Your username or password is incorrect. Please double check them. </div> <div class="column label span-2"> <a href="http://www.instapaper.com/user/register" class="vertical-center description">Get a free account</a> </div> </div> </div> </fieldset> <fieldset class="container set"> <legend>Extras</legend> <div class="container pad"> <div class="unit on-2 columns same-height"> <div class="column label"> <label for="show_popup" class="vertical-center">Show popup:</label> </div> <div class="column"> <input type="checkbox" name="show_popup" class="vertical-center" id="show_popup" value="1" /> </div> <div class="column label"> <label for="auto_close">Auto close:</label> <div class="description">(Close tab after saved)</div> </div> <div class="column"> <input type="checkbox" name="auto_close" class="vertical-center" id="auto_close" value="1" /> </div> <div class="column label"> <label for="badge_style" class="vertical-center">Badge style:</label> </div> <div class="column"> <select name="badge_style" id="badge_style"> <option value="0">Text</option> <option value="1">Tick/Circle/Cross Icons</option> <option value="2">Chromed icons</option> </select> </div> <div class="column label"> <label for="shortcut" class="vertical-center">Keyboard shortcut:</label> <div class="description">(Beta - Not all shortcuts may work)</div> </div> <div class="column"> <input type="text" name="shortcut" id="shortcut" class="text" /> </div> - <div class="column label"> - <label for="description_style" class="vertical-center">Article Description:</label> - </div> - <div class="column"> - <select name="description_style" id="description_style"> - <option value="1">Use Article URL</option> - <option value="0">"Saved from Instachrome Extension"</option> - </select> - </div> </div> </div> </fieldset> <input type="submit" class="button" value="Save" /> or <a href="#" class="close">Close</a> </form> <div class="container footer"> <p> by <a href="http://edgarjs.mx">Edgar J. Suárez</a> | <a href="http://twitter.com/edgarjs">Twitter</a> | <a href="https://chrome.google.com/extensions/detail/fldildgghjoohccppflaohodcnmlacpb">Extension page</a> | <a href="http://instapaper.com">Instapaper</a> <br /> This page is powered by <a href="http://elasticss.com">Elastic CSS</a> | Icons by <a href="http://famfamfam.com">famfamfam.com</a> </p> </div> </div> </body> </html>
edgarjs/instachrome
1a868661d6ab7f43fb8d7e4af10ec9df963311ae
Adding authentication when changing credentials
diff --git a/javascripts/background.js b/javascripts/background.js index 04f87ef..dce3c76 100644 --- a/javascripts/background.js +++ b/javascripts/background.js @@ -1,180 +1,179 @@ var last_tab_id; var badge_styles = { TEXT: 0, ICON: 1, CHROMED: 2 }; var description_styles = { DEFAULT: 0, SITEURL: 1 }; function onComplete(xhr) { if (xhr.srcElement.status == 201) { if ($.db('auto_close') === '1') { chrome.tabs.remove(last_tab_id); } else { switch (parseInt($.db('badge_style'))) { case badge_styles.TEXT: chrome.browserAction.setBadgeBackgroundColor({ color: [53, 181, 49, 255], tabId: last_tab_id }); chrome.browserAction.setBadgeText({ text: 'ok', tabId: last_tab_id }); break; case badge_styles.ICON: chrome.browserAction.setIcon({ path: 'images/saved.png', tabId: last_tab_id }); break; case badge_styles.CHROMED: chrome.browserAction.setIcon({ path: 'images/chromed_saved.png', tabId: last_tab_id }); break; } } } else { switch (parseInt($.db('badge_style'))) { case badge_styles.TEXT: chrome.browserAction.setBadgeBackgroundColor({ color: [255, 0, 0, 255], tabId: last_tab_id }); chrome.browserAction.setBadgeText({ text: 'err!', tabId: last_tab_id }); break; case badge_styles.ICON: chrome.browserAction.setIcon({ path: 'images/error.png', tabId: last_tab_id }); break; case badge_styles.CHROMED: chrome.browserAction.setIcon({ path: 'images/chromed_error.png', tabId: last_tab_id }); break; } } } // TODO: gmail support for mails. // TODO: get gReader single articles function sendRequest(url, selection) { var xhr = new XMLHttpRequest(); var username = $.db('username'); var password = $.db('password') || ''; if (!username) { var tabImg = 'images/default.png'; if (parseInt($.db('badge_style')) === badge_styles.CHROMED) { tabImg = 'images/chromed_default.png'; } chrome.browserAction.setIcon({ path: tabImg, tabId: last_tab_id }); chrome.tabs.create({ - url: chrome.extension.getURL('options.html') + url: chrome.extension.getURL('options.html#setup') }); return; } xhr.onreadystatechange = onComplete; chrome.tabs.get(last_tab_id, function(tab) { var theDescript = "Saved from Instachrome"; if (parseInt($.db('description_style')) === description_styles.SITEURL) { - theDescript = tab.url.match(/https?:\/\/([^\/]+)/)[1] + theDescript = tab.url.match(/https?:\/\/([^\/]+)/)[1]; } var title = encodeURIComponent(tab.title); var params = { url: url, username: username, password: password, selection: selection || theDescript }; var title = title ? ("&title=" + title) : "&auto-title=1"; - xhr.open("GET", 'https://www.instapaper.com/api/add?' + - $.param(params) + title, true); + xhr.open("GET", 'https://www.instapaper.com/api/add?' + $.param(params) + title, true); xhr.send(); }); } function readLater(tab, selection) { last_tab_id = tab.id; switch (parseInt($.db('badge_style'))) { case badge_styles.TEXT: // TODO Customize color chrome.browserAction.setBadgeBackgroundColor({ color: [82, 168, 207, 255], tabId: last_tab_id }); chrome.browserAction.setBadgeText({ text: '...', tabId: last_tab_id }); break; case badge_styles.ICON: chrome.browserAction.setIcon({ path: 'images/saving.png', tabId: last_tab_id }); break; case badge_styles.CHROMED: chrome.browserAction.setIcon({ path: 'images/chromed_saving.png', tabId: last_tab_id }); break; } sendRequest(tab.url, selection); } chrome.tabs.onUpdated.addListener(function(tabId) { var tabImg = 'images/default.png'; if (parseInt($.db('badge_style')) === badge_styles.CHROMED) { tabImg = 'images/chromed_default.png'; } chrome.browserAction.setIcon({ path: tabImg, tabId: tabId }); }); chrome.browserAction.onClicked.addListener(readLater); // from key shortcut chrome.extension.onRequest.addListener(function(request, sender, sendResponse) { if (sender.tab) { if (request.hasOwnProperty('keystroke')) { var shortcut = $.db('shortcut'); var ctrlKey = (shortcut.ctrlKey == request.keystroke.ctrlKey), altKey = (shortcut.altKey == request.keystroke.altKey), shiftKey = (shortcut.shiftKey == request.keystroke.shiftKey), keyCode = (shortcut.keyCode == request.keystroke.keyCode); sendResponse({ shortcutPressed: (ctrlKey && altKey && shiftKey & keyCode) }); } else if (request.hasOwnProperty('selection')) { readLater(sender.tab, request.selection); } } }); diff --git a/javascripts/options.js b/javascripts/options.js index 27fa4c4..a3cca30 100644 --- a/javascripts/options.js +++ b/javascripts/options.js @@ -1,113 +1,134 @@ (function($) { $.flash = function(msg) { $('.flash').text(msg).fadeIn('fast'); }; })(jQuery); var Options = function() { var values = { username: null, password: null, show_popup: '1', auto_close: false, badge_style: 0, shortcut: { keyCode: 83, altKey: true, ctrlKey: false, shiftKey: true }, - description_style: 0 + description_style: 1 }; var ui = { username: $('input#username'), password: $('input#password'), show_popup: $('input#show_popup'), auto_close: $('input#auto_close'), badge_style: $('select#badge_style'), shortcut: $('input#shortcut'), description_style: $('select#description_style') }; var dbOrDefault = function(db_key) { return $.db(db_key) || values[db_key]; }; + var authenticateCredentials = function() { + var xhr = new XMLHttpRequest(); + var username = encodeURIComponent(ui.username.val()); + var password = encodeURIComponent(ui.password.val()); + xhr.onreadystatechange = function(response) { + if(response.srcElement && response.srcElement.readyState == 4) { + $('.column.label.auth').show('fast').removeClass('ok error'); + if(response.srcElement.status == 200) { + $('.column.label.auth').addClass('ok').text('Your credentials are valid.'); + } else { + $('.column.label.auth').addClass('error').text('Your username or password is incorrect. Please double check them.'); + } + } + } + xhr.open("GET", 'https://www.instapaper.com/api/authenticate?username=' + username + '&password=' + password, true); + xhr.send(); + }; + + ui.username.bind('change', authenticateCredentials); + ui.password.bind('change', authenticateCredentials); + return { humanizeKeystrokes: function(e) { var key = String.fromCharCode(e.keyCode); var special = ""; if (e.ctrlKey) { special += "Ctrl + "; } if (e.altKey) { special += "Alt + "; } if (e.shiftKey) { special += "Shift + "; } return special + key; }, restore: function() { if (location.hash === '#setup') { $.flash('Enter your Instapaper credentials in order to save an URL.'); } ui.username.val(dbOrDefault('username')); ui.password.val(dbOrDefault('password')); if (dbOrDefault('show_popup') === '1') { ui.show_popup.attr('checked', true); } if (dbOrDefault('auto_close') === '1') { ui.auto_close.attr('checked', true); } ui.badge_style.val(dbOrDefault('badge_style')); ui.shortcut.val(this.humanizeKeystrokes(dbOrDefault('shortcut'))) .data('keys', dbOrDefault('shortcut')); ui.description_style.val(dbOrDefault('description_style')); }, save: function() { $.db('username', ui.username.val()); $.db('password', ui.password.val()); $.db('show_popup', ui.show_popup.is(':checked') ? '1': '0'); $.db('auto_close', ui.auto_close.is(':checked') ? '1': '0'); $.db('badge_style', ui.badge_style.val()); $.db('shortcut', ui.shortcut.data('keys')); $.db('description_style', ui.description_style.val()); $.flash('Options saved successfully!'); } }; }; $(function() { var o = new Options(); o.restore(); $('.flash').click(function() { $(this).fadeOut('slow'); return false; }); $('.close').click(function() { window.close(); }); $('form.options').submit(function() { o.save(); return false; }); $('#shortcut').keydown(function(e) { $(this).val(o.humanizeKeystrokes(e)).data('keys', { ctrlKey: e.ctrlKey, altKey: e.altKey, shiftKey: e.shiftKey, keyCode: e.which }); return false; }); }); diff --git a/manifest.json b/manifest.json index 957e7cc..6716899 100644 --- a/manifest.json +++ b/manifest.json @@ -1,28 +1,28 @@ { "name": "Instachrome", - "version": "1.3.1.1", + "version": "1.3.2", "description": "Save your URLs to Instapaper", "options_page": "options.html", "background_page": "background.html", "content_scripts": [{ "matches": ["http://*/*", "https://*/*"], "js": ["javascripts/keyboard.js"], "run_at": "document_start" }], "browser_action": { "default_icon": "images/default.png", "default_title": "Save to Instapaper", "popup": "popup.html" }, "icons": { "32": "images/icon/32.png", "48": "images/icon/48.png", "128": "images/icon/128.png" }, "permissions": [ "tabs", "http://ajax.googleapis.com/ajax/libs/jquery/**/*", "http://www.instapaper.com/api/", "https://www.instapaper.com/api/" ] } diff --git a/options.html b/options.html index fdd0413..ae04a68 100644 --- a/options.html +++ b/options.html @@ -1,120 +1,124 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" - "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> +"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> - <head> - <meta charset="utf-8" /> - <title>Instachrome Options</title> - <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> - <script type="text/javascript" src="javascripts/elastic.js"></script> - <script type="text/javascript" src="javascripts/app.js"></script> - <script type="text/javascript" src="javascripts/options.js"></script> - <link href="stylesheets/elastic.css" rel="stylesheet" type="text/css" /> - <link href="stylesheets/options.css" rel="stylesheet" type="text/css" /> - </head> -<body> - <a href="http://pledgie.com/campaigns/9023" class="ribbon left"></a> - <a href="http://github.com/edgarjs/instachrome" class="ribbon right"></a> - <div class="container wrapper"> - <h1 class="title">Instachrome Options</h1> - - <div class="flash"></div> + <head> + <meta charset="utf-8" /> + <title>Instachrome Options</title> + <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> + <script type="text/javascript" src="javascripts/elastic.js"></script> + <script type="text/javascript" src="javascripts/app.js"></script> + <script type="text/javascript" src="javascripts/options.js"></script> + <link href="stylesheets/elastic.css" rel="stylesheet" type="text/css" /> + <link href="stylesheets/options.css" rel="stylesheet" type="text/css" /> + </head> + <body> + <a href="http://pledgie.com/campaigns/9023" class="ribbon left"></a> + <a href="http://github.com/edgarjs/instachrome" class="ribbon right"></a> + <div class="container wrapper"> + <h1 class="title">Instachrome Options</h1> - <form class="options" action="#" method="post"> - <fieldset class="container set"> - <legend>Instapaper credentials</legend> - <div class="container pad"> - <div class="unit on-2 columns same-height"> - <div class="column label"> - <label for="username" class="vertical-center">Username:</label> - </div> - <div class="column"> - <input type="text" class="text" spellcheck="false" name="username" id="username" /> - </div> + <div class="flash"></div> - <div class="column label"> - <label for="password">Password:</label> - <div class="description">(If you have one)</div> - </div> - <div class="column"> - <input type="password" class="text" name="password" id="password" /> - </div> - - <div class="column label span-2"> - <a href="http://www.instapaper.com/user/register" class="vertical-center description">Get a free account</a> - </div> - </div> - </div> - </fieldset> + <form class="options" action="#" method="post"> + <fieldset class="container set"> + <legend>Instapaper credentials</legend> + <div class="container pad"> + <div class="unit on-2 columns same-height"> + <div class="column label"> + <label for="username" class="vertical-center">Username:</label> + </div> + <div class="column"> + <input type="text" class="text" spellcheck="false" name="username" id="username" /> + </div> - <fieldset class="container set"> - <legend>Extras</legend> - <div class="container pad"> - <div class="unit on-2 columns same-height"> - <div class="column label"> - <label for="show_popup" class="vertical-center">Show popup:</label> - </div> - <div class="column"> - <input type="checkbox" name="show_popup" class="vertical-center" id="show_popup" value="1" /> - </div> - - <div class="column label"> - <label for="auto_close">Auto close:</label> - <div class="description">(Close tab after saved)</div> - </div> - <div class="column"> - <input type="checkbox" name="auto_close" class="vertical-center" id="auto_close" value="1" /> - </div> + <div class="column label"> + <label for="password">Password:</label> + <div class="description">(If you have one)</div> + </div> + <div class="column"> + <input type="password" class="text" name="password" id="password" /> + </div> - <div class="column label"> - <label for="badge_style" class="vertical-center">Badge style:</label> - </div> - <div class="column"> - <select name="badge_style" id="badge_style"> - <option value="0">Text</option> - <option value="1">Tick/Circle/Cross Icons</option> - <option value="2">Chromed icons</option> - </select> - </div> - - <div class="column label"> - <label for="shortcut" class="vertical-center">Keyboard shortcut:</label> - <div class="description">(Beta - Not all shortcuts may work)</div> - </div> - <div class="column"> - <input type="text" name="shortcut" id="shortcut" class="text" /> - </div> - - <div class="column label"> - <label for="description_style" class="vertical-center">Article Description:</label> + <div class="column label span-2 auth"> + Your username or password is incorrect. Please double check them. + </div> + + <div class="column label span-2"> + <a href="http://www.instapaper.com/user/register" class="vertical-center description">Get a free account</a> + </div> + </div> + </div> + </fieldset> + + <fieldset class="container set"> + <legend>Extras</legend> + <div class="container pad"> + <div class="unit on-2 columns same-height"> + <div class="column label"> + <label for="show_popup" class="vertical-center">Show popup:</label> + </div> + <div class="column"> + <input type="checkbox" name="show_popup" class="vertical-center" id="show_popup" value="1" /> + </div> + + <div class="column label"> + <label for="auto_close">Auto close:</label> + <div class="description">(Close tab after saved)</div> + </div> + <div class="column"> + <input type="checkbox" name="auto_close" class="vertical-center" id="auto_close" value="1" /> + </div> + + <div class="column label"> + <label for="badge_style" class="vertical-center">Badge style:</label> + </div> + <div class="column"> + <select name="badge_style" id="badge_style"> + <option value="0">Text</option> + <option value="1">Tick/Circle/Cross Icons</option> + <option value="2">Chromed icons</option> + </select> + </div> + + <div class="column label"> + <label for="shortcut" class="vertical-center">Keyboard shortcut:</label> + <div class="description">(Beta - Not all shortcuts may work)</div> + </div> + <div class="column"> + <input type="text" name="shortcut" id="shortcut" class="text" /> + </div> + + <div class="column label"> + <label for="description_style" class="vertical-center">Article Description:</label> + </div> + <div class="column"> + <select name="description_style" id="description_style"> + <option value="1">Use Article URL</option> + <option value="0">"Saved from Instachrome Extension"</option> + </select> + </div> + </div> + </div> + </fieldset> + + <input type="submit" class="button" value="Save" /> or + <a href="#" class="close">Close</a> + </form> + + <div class="container footer"> + <p> + by <a href="http://edgarjs.mx">Edgar J. Suárez</a> + | + <a href="http://twitter.com/edgarjs">Twitter</a> + | + <a href="https://chrome.google.com/extensions/detail/fldildgghjoohccppflaohodcnmlacpb">Extension page</a> + | + <a href="http://instapaper.com">Instapaper</a> + <br /> + This page is powered by <a href="http://elasticss.com">Elastic CSS</a> + | Icons by <a href="http://famfamfam.com">famfamfam.com</a> + </p> </div> - <div class="column"> - <select name="description_style" id="description_style"> - <option value="0">"Saved from Instachrome Extension"</option> - <option value="1">Use Article URL</option> - </select> - </div> - </div> </div> - </fieldset> - - <input type="submit" class="button" value="Save" /> or - <a href="#" class="close">Close</a> - </form> - - <div class="container footer"> - <p> - by <a href="http://edgarjs.mx">Edgar J. Suárez</a> - | - <a href="http://twitter.com/edgarjs">Twitter</a> - | - <a href="https://chrome.google.com/extensions/detail/fldildgghjoohccppflaohodcnmlacpb">Extension page</a> - | - <a href="http://instapaper.com">Instapaper</a> - <br /> - This page is powered by <a href="http://elasticss.com">Elastic CSS</a> - | Icons by <a href="http://famfamfam.com">famfamfam.com</a> - </p> - </div> - </div> -</body> + </body> </html> diff --git a/stylesheets/options.css b/stylesheets/options.css index 2dee754..309a7d3 100644 --- a/stylesheets/options.css +++ b/stylesheets/options.css @@ -1,86 +1,100 @@ a { color: #DC8145; } a.ribbon { top: 0; position: absolute; border: 0; display: block; width: 149px; height: 149px; } a.ribbon.right { right: 0; background: url("../images/forkme_ribbon.png") 0 0 no-repeat; } a.ribbon.left { left: 0; background: url("../images/donation_ribbon.png") 0 0 no-repeat; } .wrapper { width: 500px; margin: 20px auto; } .flash { background: #FFFFCC; border: 1px solid #cccc00; padding: 5px 0; color: #666; text-align: center; margin: 10px 0; display: none; cursor: pointer; } .title { font-family: "Times New Roman"; font-size: 2em; } .set { border: 1px solid #C7E2EF; border-radius: 3px; background-color: #ededed; } .set > legend { margin-left: 12px; color: #52A8CF; text-shadow: 1px 1px 1px #ccc; cursor: default; } .set > .pad { padding: 6px; } .set .column.label { text-align: center; color: #888; } .set .column.label > .description { font-size: 0.8em; } .set .column > input.text { border: 1px solid #ccc; padding: 4px; margin: 3px 0; color: #52A8CF; border-radius: 3px; } +.column.label.auth { + line-height: 35px; + display: none; + font-size: 10px; +} + +.column.label.auth.ok { + color: green; +} + +.column.label.auth.error { + color: red; +} + .footer { font-size: 0.8em; color: #888; text-align: center; margin-top: 10em; } .footer a { color: #333; -} \ No newline at end of file +}
edgarjs/instachrome
de29631d86db252d1b990f9441bcbae9c01f40cc
Changed manifest version
diff --git a/manifest.json b/manifest.json index a2ee473..a98f7bd 100644 --- a/manifest.json +++ b/manifest.json @@ -1,28 +1,28 @@ { "name": "Instachrome", - "version": "1.3.0", + "version": "1.3.1", "description": "Save your URLs to Instapaper", "options_page": "options.html", "background_page": "background.html", "content_scripts": [{ "matches": ["http://*/*", "https://*/*"], "js": ["javascripts/keyboard.js"], "run_at": "document_start" }], "browser_action": { "default_icon": "images/default.png", "default_title": "Save to Instapaper", "popup": "popup.html" }, "icons": { "32": "images/icon/32.png", "48": "images/icon/48.png", "128": "images/icon/128.png" }, "permissions": [ "tabs", "http://ajax.googleapis.com/ajax/libs/jquery/**/*", "http://www.instapaper.com/api/", "https://www.instapaper.com/api/" ] -} \ No newline at end of file +}
edgarjs/instachrome
99c138c0b1678c3a32a75f7e38c832c3091c3299
Added ability to save base URL as article description
diff --git a/javascripts/background.js b/javascripts/background.js index cfa4bee..04f87ef 100644 --- a/javascripts/background.js +++ b/javascripts/background.js @@ -1,117 +1,180 @@ var last_tab_id; var badge_styles = { TEXT: 0, ICON: 1, CHROMED: 2 }; +var description_styles = { + DEFAULT: 0, + SITEURL: 1 +}; function onComplete(xhr) { - if(xhr.srcElement.status == 201) { - if($.db('auto_close') === '1') { + if (xhr.srcElement.status == 201) { + if ($.db('auto_close') === '1') { chrome.tabs.remove(last_tab_id); } else { - switch(parseInt($.db('badge_style'))) { - case badge_styles.TEXT: - chrome.browserAction.setBadgeBackgroundColor({color: [53, 181, 49, 255], tabId: last_tab_id}); - chrome.browserAction.setBadgeText({text: 'ok', tabId: last_tab_id}); - break; - case badge_styles.ICON: - chrome.browserAction.setIcon({path: 'images/saved.png', tabId: last_tab_id}); - break; - case badge_styles.CHROMED: - chrome.browserAction.setIcon({path: 'images/chromed_saved.png', tabId: last_tab_id}); - break; - } - } - } else { - switch(parseInt($.db('badge_style'))) { + switch (parseInt($.db('badge_style'))) { case badge_styles.TEXT: - chrome.browserAction.setBadgeBackgroundColor({color: [255, 0, 0, 255], tabId: last_tab_id}); - chrome.browserAction.setBadgeText({text: 'err!', tabId: last_tab_id}); + chrome.browserAction.setBadgeBackgroundColor({ + color: + [53, 181, 49, 255], + tabId: last_tab_id + }); + chrome.browserAction.setBadgeText({ + text: 'ok', + tabId: last_tab_id + }); break; case badge_styles.ICON: - chrome.browserAction.setIcon({path: 'images/error.png', tabId: last_tab_id}); + chrome.browserAction.setIcon({ + path: + 'images/saved.png', + tabId: last_tab_id + }); break; case badge_styles.CHROMED: - chrome.browserAction.setIcon({path: 'images/chromed_error.png', tabId: last_tab_id}); + chrome.browserAction.setIcon({ + path: + 'images/chromed_saved.png', + tabId: last_tab_id + }); break; + } + } + } else { + switch (parseInt($.db('badge_style'))) { + case badge_styles.TEXT: + chrome.browserAction.setBadgeBackgroundColor({ + color: + [255, 0, 0, 255], + tabId: last_tab_id + }); + chrome.browserAction.setBadgeText({ + text: 'err!', + tabId: last_tab_id + }); + break; + case badge_styles.ICON: + chrome.browserAction.setIcon({ + path: + 'images/error.png', + tabId: last_tab_id + }); + break; + case badge_styles.CHROMED: + chrome.browserAction.setIcon({ + path: + 'images/chromed_error.png', + tabId: last_tab_id + }); + break; } } } // TODO: gmail support for mails. // TODO: get gReader single articles function sendRequest(url, selection) { var xhr = new XMLHttpRequest(); var username = $.db('username'); var password = $.db('password') || ''; - if(!username) { + if (!username) { var tabImg = 'images/default.png'; - if(parseInt($.db('badge_style')) === badge_styles.CHROMED) { + if (parseInt($.db('badge_style')) === badge_styles.CHROMED) { tabImg = 'images/chromed_default.png'; } - chrome.browserAction.setIcon({path: tabImg, tabId: last_tab_id}); - chrome.tabs.create({url: chrome.extension.getURL('options.html')}); + chrome.browserAction.setIcon({ + path: tabImg, + tabId: last_tab_id + }); + chrome.tabs.create({ + url: chrome.extension.getURL('options.html') + }); return; } - + xhr.onreadystatechange = onComplete; chrome.tabs.get(last_tab_id, function(tab) { + + var theDescript = "Saved from Instachrome"; + if (parseInt($.db('description_style')) === description_styles.SITEURL) { + theDescript = tab.url.match(/https?:\/\/([^\/]+)/)[1] + } + var title = encodeURIComponent(tab.title); var params = { url: url, username: username, password: password, - selection: selection || "Saved from instachrome extension" + selection: selection || theDescript }; var title = title ? ("&title=" + title) : "&auto-title=1"; xhr.open("GET", 'https://www.instapaper.com/api/add?' + - $.param(params) + title, true); + $.param(params) + title, true); xhr.send(); }); } function readLater(tab, selection) { last_tab_id = tab.id; - switch(parseInt($.db('badge_style'))) { - case badge_styles.TEXT: - // TODO Customize color - chrome.browserAction.setBadgeBackgroundColor({color: [82, 168, 207, 255], tabId: last_tab_id}); - chrome.browserAction.setBadgeText({text: '...', tabId: last_tab_id}); - break; - case badge_styles.ICON: - chrome.browserAction.setIcon({path: 'images/saving.png', tabId: last_tab_id}); - break; - case badge_styles.CHROMED: - chrome.browserAction.setIcon({path: 'images/chromed_saving.png', tabId: last_tab_id}); - break; + switch (parseInt($.db('badge_style'))) { + case badge_styles.TEXT: + // TODO Customize color + chrome.browserAction.setBadgeBackgroundColor({ + color: + [82, 168, 207, 255], + tabId: last_tab_id + }); + chrome.browserAction.setBadgeText({ + text: '...', + tabId: last_tab_id + }); + break; + case badge_styles.ICON: + chrome.browserAction.setIcon({ + path: + 'images/saving.png', + tabId: last_tab_id + }); + break; + case badge_styles.CHROMED: + chrome.browserAction.setIcon({ + path: + 'images/chromed_saving.png', + tabId: last_tab_id + }); + break; } sendRequest(tab.url, selection); } chrome.tabs.onUpdated.addListener(function(tabId) { var tabImg = 'images/default.png'; - if(parseInt($.db('badge_style')) === badge_styles.CHROMED) { + if (parseInt($.db('badge_style')) === badge_styles.CHROMED) { tabImg = 'images/chromed_default.png'; } - chrome.browserAction.setIcon({path: tabImg, tabId: tabId}); + chrome.browserAction.setIcon({ + path: tabImg, + tabId: tabId + }); }); chrome.browserAction.onClicked.addListener(readLater); // from key shortcut chrome.extension.onRequest.addListener(function(request, sender, sendResponse) { - if(sender.tab) { - if(request.hasOwnProperty('keystroke')) { + if (sender.tab) { + if (request.hasOwnProperty('keystroke')) { var shortcut = $.db('shortcut'); var ctrlKey = (shortcut.ctrlKey == request.keystroke.ctrlKey), - altKey = (shortcut.altKey == request.keystroke.altKey), - shiftKey = (shortcut.shiftKey == request.keystroke.shiftKey), - keyCode = (shortcut.keyCode == request.keystroke.keyCode); + altKey = (shortcut.altKey == request.keystroke.altKey), + shiftKey = (shortcut.shiftKey == request.keystroke.shiftKey), + keyCode = (shortcut.keyCode == request.keystroke.keyCode); sendResponse({ shortcutPressed: (ctrlKey && altKey && shiftKey & keyCode) }); - } else if(request.hasOwnProperty('selection')) { + } else if (request.hasOwnProperty('selection')) { readLater(sender.tab, request.selection); } } - }); +}); diff --git a/javascripts/options.js b/javascripts/options.js index c56c361..27fa4c4 100644 --- a/javascripts/options.js +++ b/javascripts/options.js @@ -1,109 +1,113 @@ (function($) { $.flash = function(msg) { $('.flash').text(msg).fadeIn('fast'); }; })(jQuery); var Options = function() { var values = { username: null, password: null, show_popup: '1', auto_close: false, badge_style: 0, shortcut: { keyCode: 83, altKey: true, ctrlKey: false, shiftKey: true - } + }, + description_style: 0 }; - + var ui = { username: $('input#username'), password: $('input#password'), show_popup: $('input#show_popup'), auto_close: $('input#auto_close'), badge_style: $('select#badge_style'), - shortcut: $('input#shortcut') + shortcut: $('input#shortcut'), + description_style: $('select#description_style') }; - + var dbOrDefault = function(db_key) { return $.db(db_key) || values[db_key]; }; - + return { humanizeKeystrokes: function(e) { var key = String.fromCharCode(e.keyCode); var special = ""; - if(e.ctrlKey) { + if (e.ctrlKey) { special += "Ctrl + "; } - if(e.altKey) { + if (e.altKey) { special += "Alt + "; } - if(e.shiftKey) { + if (e.shiftKey) { special += "Shift + "; } return special + key; }, - + restore: function() { - if(location.hash === '#setup') { + if (location.hash === '#setup') { $.flash('Enter your Instapaper credentials in order to save an URL.'); } ui.username.val(dbOrDefault('username')); ui.password.val(dbOrDefault('password')); - if(dbOrDefault('show_popup') === '1') { + if (dbOrDefault('show_popup') === '1') { ui.show_popup.attr('checked', true); } - if(dbOrDefault('auto_close') === '1') { + if (dbOrDefault('auto_close') === '1') { ui.auto_close.attr('checked', true); } ui.badge_style.val(dbOrDefault('badge_style')); ui.shortcut.val(this.humanizeKeystrokes(dbOrDefault('shortcut'))) - .data('keys', dbOrDefault('shortcut')); + .data('keys', dbOrDefault('shortcut')); + ui.description_style.val(dbOrDefault('description_style')); }, save: function() { $.db('username', ui.username.val()); $.db('password', ui.password.val()); - $.db('show_popup', ui.show_popup.is(':checked') ? '1' : '0'); - $.db('auto_close', ui.auto_close.is(':checked') ? '1' : '0'); + $.db('show_popup', ui.show_popup.is(':checked') ? '1': '0'); + $.db('auto_close', ui.auto_close.is(':checked') ? '1': '0'); $.db('badge_style', ui.badge_style.val()); $.db('shortcut', ui.shortcut.data('keys')); - + $.db('description_style', ui.description_style.val()); + $.flash('Options saved successfully!'); } }; }; $(function() { var o = new Options(); o.restore(); - + $('.flash').click(function() { $(this).fadeOut('slow'); return false; }); - + $('.close').click(function() { window.close(); }); - + $('form.options').submit(function() { o.save(); return false; }); - + $('#shortcut').keydown(function(e) { $(this).val(o.humanizeKeystrokes(e)).data('keys', { ctrlKey: e.ctrlKey, altKey: e.altKey, shiftKey: e.shiftKey, keyCode: e.which }); return false; }); }); diff --git a/options.html b/options.html index 6d51c9c..1d197cb 100644 --- a/options.html +++ b/options.html @@ -1,110 +1,120 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta charset="utf-8" /> <title>Instachrome Options</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript" src="javascripts/elastic.js"></script> <script type="text/javascript" src="javascripts/app.js"></script> <script type="text/javascript" src="javascripts/options.js"></script> <link href="stylesheets/elastic.css" rel="stylesheet" type="text/css" /> <link href="stylesheets/options.css" rel="stylesheet" type="text/css" /> </head> <body> <a href="http://pledgie.com/campaigns/9023" class="ribbon left"></a> <a href="http://github.com/edgarjs/instachrome" class="ribbon right"></a> <div class="container wrapper"> <h1 class="title">Instachrome Options</h1> <div class="flash"></div> <form class="options" action="#" method="post"> <fieldset class="container set"> <legend>Instapaper credentials</legend> <div class="container pad"> <div class="unit on-2 columns same-height"> <div class="column label"> <label for="username" class="vertical-center">Username:</label> </div> <div class="column"> <input type="text" class="text" spellcheck="false" name="username" id="username" /> </div> <div class="column label"> <label for="password">Password:</label> <div class="description">(If you have one)</div> </div> <div class="column"> <input type="password" class="text" name="password" id="password" /> </div> <div class="column label span-2"> <a href="http://www.instapaper.com/user/register" class="vertical-center description">Get a free account</a> </div> </div> </div> </fieldset> <fieldset class="container set"> <legend>Extras</legend> <div class="container pad"> <div class="unit on-2 columns same-height"> <div class="column label"> <label for="show_popup" class="vertical-center">Show popup:</label> </div> <div class="column"> <input type="checkbox" name="show_popup" class="vertical-center" id="show_popup" value="1" /> </div> <div class="column label"> <label for="auto_close">Auto close:</label> <div class="description">(Close tab after saved)</div> </div> <div class="column"> <input type="checkbox" name="auto_close" class="vertical-center" id="auto_close" value="1" /> </div> <div class="column label"> <label for="badge_style" class="vertical-center">Badge style:</label> </div> <div class="column"> <select name="badge_style" id="badge_style"> <option value="0">Text</option> <option value="1">Tick/Circle/Cross Icons</option> <option value="2">Chromed icons</option> </select> </div> <div class="column label"> - <label for="badge_style" class="vertical-center">Keyboard shortcut:</label> + <label for="shortcut" class="vertical-center">Keyboard shortcut:</label> <div class="description">(Beta - Not all shortcuts may work)</div> </div> <div class="column"> <input type="text" name="shortcut" id="shortcut" class="text" /> </div> + + <div class="column label"> + <label for="description_style" class="vertical-center">Article Description:</label> + </div> + <div class="column"> + <select name="description_style" id="description_style"> + <option value="0">"Saved from Instachrome Extension"</option> + <option value="1">Use Article URL</option> + </select> + </div> </div> </div> </fieldset> <input type="submit" class="button" value="Save" /> or <a href="#" class="close">Close</a> </form> <div class="container footer"> <p> by <a href="http://e.dgar.org">Edgar J. Suárez</a> | <a href="http://twitter.com/edgarjs">Twitter</a> | <a href="https://chrome.google.com/extensions/detail/fldildgghjoohccppflaohodcnmlacpb">Extension page</a> | <a href="http://instapaper.com">Instapaper</a> <br /> This page is powered by <a href="http://elasticss.com">Elastic CSS</a> | Icons by <a href="http://famfamfam.com">famfamfam.com</a> </p> </div> </div> </body> </html> \ No newline at end of file
edgarjs/instachrome
229c90c2861a13fc5b07735d94bd543624045a5a
Custom keyboard shortcut
diff --git a/javascripts/app.js b/javascripts/app.js index 49382f7..6426492 100644 --- a/javascripts/app.js +++ b/javascripts/app.js @@ -1,10 +1,17 @@ (function($) { $.db = function(attr, val) { + var isJSON = function(str) { + return (typeof str === 'string' && /^\{.*\}$/.test(str)); + }; if(typeof val === 'undefined') { - return localStorage[attr]; + return isJSON(localStorage[attr]) ? JSON.parse(localStorage[attr]) : localStorage[attr]; } else { - localStorage[attr] = val; + if(val.constructor === Object) { + localStorage[attr] = JSON.stringify(val); + } else { + localStorage[attr] = val; + } return val; } }; })(jQuery); diff --git a/javascripts/background.js b/javascripts/background.js index 44ffd70..cfa4bee 100644 --- a/javascripts/background.js +++ b/javascripts/background.js @@ -1,105 +1,117 @@ var last_tab_id; var badge_styles = { TEXT: 0, ICON: 1, CHROMED: 2 }; function onComplete(xhr) { if(xhr.srcElement.status == 201) { if($.db('auto_close') === '1') { chrome.tabs.remove(last_tab_id); } else { switch(parseInt($.db('badge_style'))) { case badge_styles.TEXT: chrome.browserAction.setBadgeBackgroundColor({color: [53, 181, 49, 255], tabId: last_tab_id}); chrome.browserAction.setBadgeText({text: 'ok', tabId: last_tab_id}); break; case badge_styles.ICON: chrome.browserAction.setIcon({path: 'images/saved.png', tabId: last_tab_id}); break; case badge_styles.CHROMED: chrome.browserAction.setIcon({path: 'images/chromed_saved.png', tabId: last_tab_id}); break; } } } else { switch(parseInt($.db('badge_style'))) { case badge_styles.TEXT: chrome.browserAction.setBadgeBackgroundColor({color: [255, 0, 0, 255], tabId: last_tab_id}); chrome.browserAction.setBadgeText({text: 'err!', tabId: last_tab_id}); break; case badge_styles.ICON: chrome.browserAction.setIcon({path: 'images/error.png', tabId: last_tab_id}); break; case badge_styles.CHROMED: chrome.browserAction.setIcon({path: 'images/chromed_error.png', tabId: last_tab_id}); break; } } } // TODO: gmail support for mails. +// TODO: get gReader single articles function sendRequest(url, selection) { var xhr = new XMLHttpRequest(); var username = $.db('username'); var password = $.db('password') || ''; if(!username) { var tabImg = 'images/default.png'; if(parseInt($.db('badge_style')) === badge_styles.CHROMED) { tabImg = 'images/chromed_default.png'; } chrome.browserAction.setIcon({path: tabImg, tabId: last_tab_id}); chrome.tabs.create({url: chrome.extension.getURL('options.html')}); return; } xhr.onreadystatechange = onComplete; chrome.tabs.get(last_tab_id, function(tab) { var title = encodeURIComponent(tab.title); var params = { url: url, username: username, password: password, selection: selection || "Saved from instachrome extension" }; var title = title ? ("&title=" + title) : "&auto-title=1"; xhr.open("GET", 'https://www.instapaper.com/api/add?' + $.param(params) + title, true); xhr.send(); }); } function readLater(tab, selection) { last_tab_id = tab.id; switch(parseInt($.db('badge_style'))) { case badge_styles.TEXT: // TODO Customize color chrome.browserAction.setBadgeBackgroundColor({color: [82, 168, 207, 255], tabId: last_tab_id}); chrome.browserAction.setBadgeText({text: '...', tabId: last_tab_id}); break; case badge_styles.ICON: chrome.browserAction.setIcon({path: 'images/saving.png', tabId: last_tab_id}); break; case badge_styles.CHROMED: chrome.browserAction.setIcon({path: 'images/chromed_saving.png', tabId: last_tab_id}); break; } sendRequest(tab.url, selection); } chrome.tabs.onUpdated.addListener(function(tabId) { var tabImg = 'images/default.png'; if(parseInt($.db('badge_style')) === badge_styles.CHROMED) { tabImg = 'images/chromed_default.png'; } chrome.browserAction.setIcon({path: tabImg, tabId: tabId}); }); chrome.browserAction.onClicked.addListener(readLater); // from key shortcut chrome.extension.onRequest.addListener(function(request, sender, sendResponse) { if(sender.tab) { - readLater(sender.tab, request.selection); + if(request.hasOwnProperty('keystroke')) { + var shortcut = $.db('shortcut'); + var ctrlKey = (shortcut.ctrlKey == request.keystroke.ctrlKey), + altKey = (shortcut.altKey == request.keystroke.altKey), + shiftKey = (shortcut.shiftKey == request.keystroke.shiftKey), + keyCode = (shortcut.keyCode == request.keystroke.keyCode); + sendResponse({ + shortcutPressed: (ctrlKey && altKey && shiftKey & keyCode) + }); + } else if(request.hasOwnProperty('selection')) { + readLater(sender.tab, request.selection); + } } }); diff --git a/javascripts/keyboard.js b/javascripts/keyboard.js index 4fa885b..b2e6cdf 100644 --- a/javascripts/keyboard.js +++ b/javascripts/keyboard.js @@ -1,14 +1,19 @@ // keyboard shortcut window.addEventListener('keydown', function(e) { - // TODO: Make it configurable - // Shift + Alt + S - if(e.which === 83 && e.altKey) { - var selection = ''; - if (window && window.getSelection) { - selection = window.getSelection().toString(); - } else if (document && document.getSelection) { - selection = document.getSelection().toString(); - } - chrome.extension.sendRequest({selection: selection}, function(response) {}); - } + chrome.extension.sendRequest({keystroke: { + keyCode: e.keyCode, + altKey: e.altKey, + ctrlKey: e.ctrlKey, + shiftKey: e.shiftKey + }}, function(response) { + if(response.shortcutPressed) { + var selection = ''; + if (window && window.getSelection) { + selection = window.getSelection().toString(); + } else if (document && document.getSelection) { + selection = document.getSelection().toString(); + } + chrome.extension.sendRequest({selection: selection}, function(r) {}); + } + }); }, false); diff --git a/javascripts/options.js b/javascripts/options.js index c63a39b..c56c361 100644 --- a/javascripts/options.js +++ b/javascripts/options.js @@ -1,71 +1,109 @@ (function($) { $.flash = function(msg) { $('.flash').text(msg).fadeIn('fast'); }; })(jQuery); var Options = function() { var values = { username: null, password: null, - show_popup: false, + show_popup: '1', auto_close: false, - badge_style: 0 + badge_style: 0, + shortcut: { + keyCode: 83, + altKey: true, + ctrlKey: false, + shiftKey: true + } }; var ui = { username: $('input#username'), password: $('input#password'), show_popup: $('input#show_popup'), auto_close: $('input#auto_close'), - badge_style: $('select#badge_style') + badge_style: $('select#badge_style'), + shortcut: $('input#shortcut') }; + var dbOrDefault = function(db_key) { + return $.db(db_key) || values[db_key]; + }; return { + humanizeKeystrokes: function(e) { + var key = String.fromCharCode(e.keyCode); + var special = ""; + if(e.ctrlKey) { + special += "Ctrl + "; + } + if(e.altKey) { + special += "Alt + "; + } + if(e.shiftKey) { + special += "Shift + "; + } + return special + key; + }, + restore: function() { if(location.hash === '#setup') { $.flash('Enter your Instapaper credentials in order to save an URL.'); } - ui.username.val($.db('username')); - ui.password.val($.db('password')); - if($.db('show_popup') === '1') { + ui.username.val(dbOrDefault('username')); + ui.password.val(dbOrDefault('password')); + if(dbOrDefault('show_popup') === '1') { ui.show_popup.attr('checked', true); } - if($.db('auto_close') === '1') { + if(dbOrDefault('auto_close') === '1') { ui.auto_close.attr('checked', true); } - ui.badge_style.val($.db('badge_style')); + ui.badge_style.val(dbOrDefault('badge_style')); + ui.shortcut.val(this.humanizeKeystrokes(dbOrDefault('shortcut'))) + .data('keys', dbOrDefault('shortcut')); }, save: function() { $.db('username', ui.username.val()); $.db('password', ui.password.val()); $.db('show_popup', ui.show_popup.is(':checked') ? '1' : '0'); $.db('auto_close', ui.auto_close.is(':checked') ? '1' : '0'); $.db('badge_style', ui.badge_style.val()); + $.db('shortcut', ui.shortcut.data('keys')); $.flash('Options saved successfully!'); } }; }; $(function() { var o = new Options(); o.restore(); $('.flash').click(function() { $(this).fadeOut('slow'); return false; }); $('.close').click(function() { window.close(); }); $('form.options').submit(function() { o.save(); return false; }); + + $('#shortcut').keydown(function(e) { + $(this).val(o.humanizeKeystrokes(e)).data('keys', { + ctrlKey: e.ctrlKey, + altKey: e.altKey, + shiftKey: e.shiftKey, + keyCode: e.which + }); + return false; + }); }); diff --git a/manifest.json b/manifest.json index 924831c..a2ee473 100644 --- a/manifest.json +++ b/manifest.json @@ -1,28 +1,28 @@ { "name": "Instachrome", - "version": "1.2.2", + "version": "1.3.0", "description": "Save your URLs to Instapaper", "options_page": "options.html", "background_page": "background.html", "content_scripts": [{ "matches": ["http://*/*", "https://*/*"], "js": ["javascripts/keyboard.js"], "run_at": "document_start" }], "browser_action": { "default_icon": "images/default.png", "default_title": "Save to Instapaper", "popup": "popup.html" }, "icons": { "32": "images/icon/32.png", "48": "images/icon/48.png", "128": "images/icon/128.png" }, "permissions": [ "tabs", "http://ajax.googleapis.com/ajax/libs/jquery/**/*", "http://www.instapaper.com/api/", "https://www.instapaper.com/api/" ] } \ No newline at end of file diff --git a/options.html b/options.html index c042772..6d51c9c 100644 --- a/options.html +++ b/options.html @@ -1,102 +1,110 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta charset="utf-8" /> <title>Instachrome Options</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript" src="javascripts/elastic.js"></script> <script type="text/javascript" src="javascripts/app.js"></script> <script type="text/javascript" src="javascripts/options.js"></script> <link href="stylesheets/elastic.css" rel="stylesheet" type="text/css" /> <link href="stylesheets/options.css" rel="stylesheet" type="text/css" /> </head> <body> <a href="http://pledgie.com/campaigns/9023" class="ribbon left"></a> <a href="http://github.com/edgarjs/instachrome" class="ribbon right"></a> <div class="container wrapper"> <h1 class="title">Instachrome Options</h1> <div class="flash"></div> <form class="options" action="#" method="post"> <fieldset class="container set"> <legend>Instapaper credentials</legend> <div class="container pad"> <div class="unit on-2 columns same-height"> <div class="column label"> <label for="username" class="vertical-center">Username:</label> </div> <div class="column"> <input type="text" class="text" spellcheck="false" name="username" id="username" /> </div> <div class="column label"> <label for="password">Password:</label> <div class="description">(If you have one)</div> </div> <div class="column"> <input type="password" class="text" name="password" id="password" /> </div> <div class="column label span-2"> <a href="http://www.instapaper.com/user/register" class="vertical-center description">Get a free account</a> </div> </div> </div> </fieldset> <fieldset class="container set"> <legend>Extras</legend> <div class="container pad"> <div class="unit on-2 columns same-height"> <div class="column label"> <label for="show_popup" class="vertical-center">Show popup:</label> </div> <div class="column"> <input type="checkbox" name="show_popup" class="vertical-center" id="show_popup" value="1" /> </div> <div class="column label"> <label for="auto_close">Auto close:</label> <div class="description">(Close tab after saved)</div> </div> <div class="column"> <input type="checkbox" name="auto_close" class="vertical-center" id="auto_close" value="1" /> </div> <div class="column label"> <label for="badge_style" class="vertical-center">Badge style:</label> </div> <div class="column"> <select name="badge_style" id="badge_style"> <option value="0">Text</option> <option value="1">Tick/Circle/Cross Icons</option> <option value="2">Chromed icons</option> </select> </div> + + <div class="column label"> + <label for="badge_style" class="vertical-center">Keyboard shortcut:</label> + <div class="description">(Beta - Not all shortcuts may work)</div> + </div> + <div class="column"> + <input type="text" name="shortcut" id="shortcut" class="text" /> + </div> </div> </div> </fieldset> <input type="submit" class="button" value="Save" /> or <a href="#" class="close">Close</a> </form> <div class="container footer"> <p> by <a href="http://e.dgar.org">Edgar J. Suárez</a> | <a href="http://twitter.com/edgarjs">Twitter</a> | <a href="https://chrome.google.com/extensions/detail/fldildgghjoohccppflaohodcnmlacpb">Extension page</a> | <a href="http://instapaper.com">Instapaper</a> <br /> This page is powered by <a href="http://elasticss.com">Elastic CSS</a> | Icons by <a href="http://famfamfam.com">famfamfam.com</a> </p> </div> </div> </body> </html> \ No newline at end of file
edgarjs/instachrome
8bb522ada162899ee13a6ed55b21db7a9f71c256
pushing version 1.2.2
diff --git a/manifest.json b/manifest.json index 1fd321a..924831c 100644 --- a/manifest.json +++ b/manifest.json @@ -1,28 +1,28 @@ { "name": "Instachrome", - "version": "1.2.1", + "version": "1.2.2", "description": "Save your URLs to Instapaper", "options_page": "options.html", "background_page": "background.html", "content_scripts": [{ "matches": ["http://*/*", "https://*/*"], "js": ["javascripts/keyboard.js"], "run_at": "document_start" }], "browser_action": { "default_icon": "images/default.png", "default_title": "Save to Instapaper", "popup": "popup.html" }, "icons": { "32": "images/icon/32.png", "48": "images/icon/48.png", "128": "images/icon/128.png" }, "permissions": [ "tabs", "http://ajax.googleapis.com/ajax/libs/jquery/**/*", "http://www.instapaper.com/api/", "https://www.instapaper.com/api/" ] } \ No newline at end of file
edgarjs/instachrome
f4cc186c23dd1d6f1630dbf1044f5ef06d293306
Fixes issue #1
diff --git a/javascripts/background.js b/javascripts/background.js index d077df8..44ffd70 100644 --- a/javascripts/background.js +++ b/javascripts/background.js @@ -1,94 +1,105 @@ var last_tab_id; var badge_styles = { TEXT: 0, ICON: 1, CHROMED: 2 }; function onComplete(xhr) { if(xhr.srcElement.status == 201) { if($.db('auto_close') === '1') { chrome.tabs.remove(last_tab_id); } else { switch(parseInt($.db('badge_style'))) { case badge_styles.TEXT: chrome.browserAction.setBadgeBackgroundColor({color: [53, 181, 49, 255], tabId: last_tab_id}); chrome.browserAction.setBadgeText({text: 'ok', tabId: last_tab_id}); break; case badge_styles.ICON: chrome.browserAction.setIcon({path: 'images/saved.png', tabId: last_tab_id}); break; case badge_styles.CHROMED: chrome.browserAction.setIcon({path: 'images/chromed_saved.png', tabId: last_tab_id}); break; } } } else { switch(parseInt($.db('badge_style'))) { case badge_styles.TEXT: chrome.browserAction.setBadgeBackgroundColor({color: [255, 0, 0, 255], tabId: last_tab_id}); chrome.browserAction.setBadgeText({text: 'err!', tabId: last_tab_id}); break; case badge_styles.ICON: chrome.browserAction.setIcon({path: 'images/error.png', tabId: last_tab_id}); break; case badge_styles.CHROMED: chrome.browserAction.setIcon({path: 'images/chromed_error.png', tabId: last_tab_id}); break; } } } // TODO: gmail support for mails. function sendRequest(url, selection) { var xhr = new XMLHttpRequest(); var username = $.db('username'); var password = $.db('password') || ''; if(!username) { - chrome.browserAction.setIcon({path: 'images/default.png', tabId: last_tab_id}); + var tabImg = 'images/default.png'; + if(parseInt($.db('badge_style')) === badge_styles.CHROMED) { + tabImg = 'images/chromed_default.png'; + } + chrome.browserAction.setIcon({path: tabImg, tabId: last_tab_id}); chrome.tabs.create({url: chrome.extension.getURL('options.html')}); return; } xhr.onreadystatechange = onComplete; chrome.tabs.get(last_tab_id, function(tab) { var title = encodeURIComponent(tab.title); var params = { url: url, username: username, password: password, selection: selection || "Saved from instachrome extension" }; var title = title ? ("&title=" + title) : "&auto-title=1"; xhr.open("GET", 'https://www.instapaper.com/api/add?' + $.param(params) + title, true); xhr.send(); }); } function readLater(tab, selection) { last_tab_id = tab.id; switch(parseInt($.db('badge_style'))) { case badge_styles.TEXT: // TODO Customize color chrome.browserAction.setBadgeBackgroundColor({color: [82, 168, 207, 255], tabId: last_tab_id}); chrome.browserAction.setBadgeText({text: '...', tabId: last_tab_id}); break; case badge_styles.ICON: chrome.browserAction.setIcon({path: 'images/saving.png', tabId: last_tab_id}); break; case badge_styles.CHROMED: chrome.browserAction.setIcon({path: 'images/chromed_saving.png', tabId: last_tab_id}); break; } sendRequest(tab.url, selection); } +chrome.tabs.onUpdated.addListener(function(tabId) { + var tabImg = 'images/default.png'; + if(parseInt($.db('badge_style')) === badge_styles.CHROMED) { + tabImg = 'images/chromed_default.png'; + } + chrome.browserAction.setIcon({path: tabImg, tabId: tabId}); +}); chrome.browserAction.onClicked.addListener(readLater); // from key shortcut chrome.extension.onRequest.addListener(function(request, sender, sendResponse) { if(sender.tab) { readLater(sender.tab, request.selection); } });
edgarjs/instachrome
2b9fed2770789c187323273aacc4f25f30cad296
updating version in manifest
diff --git a/manifest.json b/manifest.json index 3ff10a5..1fd321a 100644 --- a/manifest.json +++ b/manifest.json @@ -1,28 +1,28 @@ { "name": "Instachrome", - "version": "1.2.0", + "version": "1.2.1", "description": "Save your URLs to Instapaper", "options_page": "options.html", "background_page": "background.html", "content_scripts": [{ "matches": ["http://*/*", "https://*/*"], "js": ["javascripts/keyboard.js"], "run_at": "document_start" }], "browser_action": { "default_icon": "images/default.png", "default_title": "Save to Instapaper", "popup": "popup.html" }, "icons": { "32": "images/icon/32.png", "48": "images/icon/48.png", "128": "images/icon/128.png" }, "permissions": [ "tabs", "http://ajax.googleapis.com/ajax/libs/jquery/**/*", "http://www.instapaper.com/api/", "https://www.instapaper.com/api/" ] } \ No newline at end of file
edgarjs/instachrome
35bb37c0e844fa92e1f532a2e33536e78c1de777
Adding chromed icons
diff --git a/images/chromed_default.png b/images/chromed_default.png new file mode 100644 index 0000000..9dd1ad6 Binary files /dev/null and b/images/chromed_default.png differ diff --git a/images/chromed_error.png b/images/chromed_error.png new file mode 100644 index 0000000..1d80e5e Binary files /dev/null and b/images/chromed_error.png differ diff --git a/images/chromed_saved.png b/images/chromed_saved.png new file mode 100644 index 0000000..2930730 Binary files /dev/null and b/images/chromed_saved.png differ diff --git a/images/chromed_saving.png b/images/chromed_saving.png new file mode 100644 index 0000000..a40b5c0 Binary files /dev/null and b/images/chromed_saving.png differ diff --git a/javascripts/background.js b/javascripts/background.js index 9a58720..d077df8 100644 --- a/javascripts/background.js +++ b/javascripts/background.js @@ -1,84 +1,94 @@ var last_tab_id; var badge_styles = { TEXT: 0, - ICON: 1 + ICON: 1, + CHROMED: 2 }; function onComplete(xhr) { if(xhr.srcElement.status == 201) { if($.db('auto_close') === '1') { chrome.tabs.remove(last_tab_id); } else { switch(parseInt($.db('badge_style'))) { case badge_styles.TEXT: chrome.browserAction.setBadgeBackgroundColor({color: [53, 181, 49, 255], tabId: last_tab_id}); chrome.browserAction.setBadgeText({text: 'ok', tabId: last_tab_id}); break; case badge_styles.ICON: chrome.browserAction.setIcon({path: 'images/saved.png', tabId: last_tab_id}); break; + case badge_styles.CHROMED: + chrome.browserAction.setIcon({path: 'images/chromed_saved.png', tabId: last_tab_id}); + break; } } } else { switch(parseInt($.db('badge_style'))) { case badge_styles.TEXT: chrome.browserAction.setBadgeBackgroundColor({color: [255, 0, 0, 255], tabId: last_tab_id}); chrome.browserAction.setBadgeText({text: 'err!', tabId: last_tab_id}); break; case badge_styles.ICON: chrome.browserAction.setIcon({path: 'images/error.png', tabId: last_tab_id}); break; + case badge_styles.CHROMED: + chrome.browserAction.setIcon({path: 'images/chromed_error.png', tabId: last_tab_id}); + break; } } } // TODO: gmail support for mails. function sendRequest(url, selection) { var xhr = new XMLHttpRequest(); var username = $.db('username'); var password = $.db('password') || ''; if(!username) { chrome.browserAction.setIcon({path: 'images/default.png', tabId: last_tab_id}); chrome.tabs.create({url: chrome.extension.getURL('options.html')}); return; } xhr.onreadystatechange = onComplete; chrome.tabs.get(last_tab_id, function(tab) { var title = encodeURIComponent(tab.title); var params = { url: url, username: username, password: password, selection: selection || "Saved from instachrome extension" }; var title = title ? ("&title=" + title) : "&auto-title=1"; xhr.open("GET", 'https://www.instapaper.com/api/add?' + $.param(params) + title, true); xhr.send(); }); } function readLater(tab, selection) { last_tab_id = tab.id; switch(parseInt($.db('badge_style'))) { case badge_styles.TEXT: // TODO Customize color chrome.browserAction.setBadgeBackgroundColor({color: [82, 168, 207, 255], tabId: last_tab_id}); chrome.browserAction.setBadgeText({text: '...', tabId: last_tab_id}); break; case badge_styles.ICON: chrome.browserAction.setIcon({path: 'images/saving.png', tabId: last_tab_id}); break; + case badge_styles.CHROMED: + chrome.browserAction.setIcon({path: 'images/chromed_saving.png', tabId: last_tab_id}); + break; } sendRequest(tab.url, selection); } chrome.browserAction.onClicked.addListener(readLater); // from key shortcut chrome.extension.onRequest.addListener(function(request, sender, sendResponse) { if(sender.tab) { readLater(sender.tab, request.selection); } }); diff --git a/options.html b/options.html index 5392939..c042772 100644 --- a/options.html +++ b/options.html @@ -1,101 +1,102 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta charset="utf-8" /> <title>Instachrome Options</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript" src="javascripts/elastic.js"></script> <script type="text/javascript" src="javascripts/app.js"></script> <script type="text/javascript" src="javascripts/options.js"></script> <link href="stylesheets/elastic.css" rel="stylesheet" type="text/css" /> <link href="stylesheets/options.css" rel="stylesheet" type="text/css" /> </head> <body> <a href="http://pledgie.com/campaigns/9023" class="ribbon left"></a> <a href="http://github.com/edgarjs/instachrome" class="ribbon right"></a> <div class="container wrapper"> <h1 class="title">Instachrome Options</h1> <div class="flash"></div> <form class="options" action="#" method="post"> <fieldset class="container set"> <legend>Instapaper credentials</legend> <div class="container pad"> <div class="unit on-2 columns same-height"> <div class="column label"> <label for="username" class="vertical-center">Username:</label> </div> <div class="column"> <input type="text" class="text" spellcheck="false" name="username" id="username" /> </div> <div class="column label"> <label for="password">Password:</label> <div class="description">(If you have one)</div> </div> <div class="column"> <input type="password" class="text" name="password" id="password" /> </div> <div class="column label span-2"> <a href="http://www.instapaper.com/user/register" class="vertical-center description">Get a free account</a> </div> </div> </div> </fieldset> <fieldset class="container set"> <legend>Extras</legend> <div class="container pad"> <div class="unit on-2 columns same-height"> <div class="column label"> <label for="show_popup" class="vertical-center">Show popup:</label> </div> <div class="column"> <input type="checkbox" name="show_popup" class="vertical-center" id="show_popup" value="1" /> </div> <div class="column label"> <label for="auto_close">Auto close:</label> <div class="description">(Close tab after saved)</div> </div> <div class="column"> <input type="checkbox" name="auto_close" class="vertical-center" id="auto_close" value="1" /> </div> <div class="column label"> <label for="badge_style" class="vertical-center">Badge style:</label> </div> <div class="column"> <select name="badge_style" id="badge_style"> <option value="0">Text</option> - <option value="1">Icon</option> + <option value="1">Tick/Circle/Cross Icons</option> + <option value="2">Chromed icons</option> </select> </div> </div> </div> </fieldset> <input type="submit" class="button" value="Save" /> or <a href="#" class="close">Close</a> </form> <div class="container footer"> <p> by <a href="http://e.dgar.org">Edgar J. Suárez</a> | <a href="http://twitter.com/edgarjs">Twitter</a> | <a href="https://chrome.google.com/extensions/detail/fldildgghjoohccppflaohodcnmlacpb">Extension page</a> | <a href="http://instapaper.com">Instapaper</a> <br /> This page is powered by <a href="http://elasticss.com">Elastic CSS</a> | Icons by <a href="http://famfamfam.com">famfamfam.com</a> </p> </div> </div> </body> </html> \ No newline at end of file
edgarjs/instachrome
dbc4a79e9c6372657abb2387807144c78d8d33df
v 1.2.0 Extra options working
diff --git a/images/add.png b/images/add.png new file mode 100644 index 0000000..6332fef Binary files /dev/null and b/images/add.png differ diff --git a/images/archive.png b/images/archive.png new file mode 100644 index 0000000..99d532e Binary files /dev/null and b/images/archive.png differ diff --git a/images/error.png b/images/error.png new file mode 100644 index 0000000..039151f Binary files /dev/null and b/images/error.png differ diff --git a/images/options.png b/images/options.png new file mode 100644 index 0000000..67de2c6 Binary files /dev/null and b/images/options.png differ diff --git a/images/saved.png b/images/saved.png new file mode 100644 index 0000000..caed2b3 Binary files /dev/null and b/images/saved.png differ diff --git a/images/saving.png b/images/saving.png new file mode 100644 index 0000000..db49ed0 Binary files /dev/null and b/images/saving.png differ diff --git a/images/starred.png b/images/starred.png new file mode 100644 index 0000000..b88c857 Binary files /dev/null and b/images/starred.png differ diff --git a/images/text_view.png b/images/text_view.png new file mode 100644 index 0000000..813f712 Binary files /dev/null and b/images/text_view.png differ diff --git a/images/unread.png b/images/unread.png new file mode 100644 index 0000000..564a1a9 Binary files /dev/null and b/images/unread.png differ diff --git a/javascripts/background.js b/javascripts/background.js index 2b7b52d..9a58720 100644 --- a/javascripts/background.js +++ b/javascripts/background.js @@ -1,63 +1,84 @@ var last_tab_id; var badge_styles = { TEXT: 0, ICON: 1 }; function onComplete(xhr) { - // TODO: validate badge style if(xhr.srcElement.status == 201) { if($.db('auto_close') === '1') { chrome.tabs.remove(last_tab_id); } else { - chrome.browserAction.setBadgeText({text: 'done', tabId: last_tab_id}); + switch(parseInt($.db('badge_style'))) { + case badge_styles.TEXT: + chrome.browserAction.setBadgeBackgroundColor({color: [53, 181, 49, 255], tabId: last_tab_id}); + chrome.browserAction.setBadgeText({text: 'ok', tabId: last_tab_id}); + break; + case badge_styles.ICON: + chrome.browserAction.setIcon({path: 'images/saved.png', tabId: last_tab_id}); + break; + } } } else { - chrome.browserAction.setBadgeText({text: 'error', tabId: last_tab_id}); + switch(parseInt($.db('badge_style'))) { + case badge_styles.TEXT: + chrome.browserAction.setBadgeBackgroundColor({color: [255, 0, 0, 255], tabId: last_tab_id}); + chrome.browserAction.setBadgeText({text: 'err!', tabId: last_tab_id}); + break; + case badge_styles.ICON: + chrome.browserAction.setIcon({path: 'images/error.png', tabId: last_tab_id}); + break; + } } } -function sendRequest(url) { +// TODO: gmail support for mails. +function sendRequest(url, selection) { var xhr = new XMLHttpRequest(); var username = $.db('username'); var password = $.db('password') || ''; if(!username) { chrome.browserAction.setIcon({path: 'images/default.png', tabId: last_tab_id}); chrome.tabs.create({url: chrome.extension.getURL('options.html')}); return; } - - username = encodeURIComponent(username); - password = encodeURIComponent(password); - url = encodeURIComponent(url); xhr.onreadystatechange = onComplete; - // TODO: set selection to the page selected text, or excerpt - var params = "?url=" + url + "&username=" + username + "&password=" + password + "&auto-title=1"; - - xhr.open("GET", 'https://www.instapaper.com/api/add' + params, true); - xhr.send(); + chrome.tabs.get(last_tab_id, function(tab) { + var title = encodeURIComponent(tab.title); + var params = { + url: url, + username: username, + password: password, + selection: selection || "Saved from instachrome extension" + }; + var title = title ? ("&title=" + title) : "&auto-title=1"; + xhr.open("GET", 'https://www.instapaper.com/api/add?' + + $.param(params) + title, true); + xhr.send(); + }); } -function readLater(tab) { +function readLater(tab, selection) { last_tab_id = tab.id; switch(parseInt($.db('badge_style'))) { case badge_styles.TEXT: - chrome.browserAction.setBadgeText({text: 'saving', tabId: last_tab_id}); + // TODO Customize color + chrome.browserAction.setBadgeBackgroundColor({color: [82, 168, 207, 255], tabId: last_tab_id}); + chrome.browserAction.setBadgeText({text: '...', tabId: last_tab_id}); break; case badge_styles.ICON: - // TODO: use icon - chrome.browserAction.setBadgeText({text: 'saving', tabId: last_tab_id}); + chrome.browserAction.setIcon({path: 'images/saving.png', tabId: last_tab_id}); break; } - sendRequest(tab.url); + sendRequest(tab.url, selection); } chrome.browserAction.onClicked.addListener(readLater); // from key shortcut chrome.extension.onRequest.addListener(function(request, sender, sendResponse) { if(sender.tab) { - readLater(sender.tab); + readLater(sender.tab, request.selection); } }); diff --git a/javascripts/keyboard.js b/javascripts/keyboard.js index a85a6e4..4fa885b 100644 --- a/javascripts/keyboard.js +++ b/javascripts/keyboard.js @@ -1,8 +1,14 @@ // keyboard shortcut window.addEventListener('keydown', function(e) { // TODO: Make it configurable // Shift + Alt + S if(e.which === 83 && e.altKey) { - chrome.extension.sendRequest({source: "shortcut"}, function(response) {}); + var selection = ''; + if (window && window.getSelection) { + selection = window.getSelection().toString(); + } else if (document && document.getSelection) { + selection = document.getSelection().toString(); + } + chrome.extension.sendRequest({selection: selection}, function(response) {}); } }, false); diff --git a/javascripts/options.js b/javascripts/options.js index 11e6ba6..c63a39b 100644 --- a/javascripts/options.js +++ b/javascripts/options.js @@ -1,76 +1,71 @@ (function($) { $.flash = function(msg) { $('.flash').text(msg).fadeIn('fast'); }; })(jQuery); var Options = function() { - var BADGE_STYLES = [ - 'Red Text', - 'Tick Icon' - ]; - var values = { username: null, password: null, show_popup: false, auto_close: false, badge_style: 0 }; var ui = { username: $('input#username'), password: $('input#password'), show_popup: $('input#show_popup'), auto_close: $('input#auto_close'), badge_style: $('select#badge_style') }; return { restore: function() { if(location.hash === '#setup') { $.flash('Enter your Instapaper credentials in order to save an URL.'); } ui.username.val($.db('username')); ui.password.val($.db('password')); if($.db('show_popup') === '1') { ui.show_popup.attr('checked', true); } if($.db('auto_close') === '1') { ui.auto_close.attr('checked', true); } ui.badge_style.val($.db('badge_style')); }, save: function() { $.db('username', ui.username.val()); $.db('password', ui.password.val()); $.db('show_popup', ui.show_popup.is(':checked') ? '1' : '0'); $.db('auto_close', ui.auto_close.is(':checked') ? '1' : '0'); $.db('badge_style', ui.badge_style.val()); $.flash('Options saved successfully!'); } }; }; $(function() { var o = new Options(); o.restore(); $('.flash').click(function() { $(this).fadeOut('slow'); return false; }); $('.close').click(function() { window.close(); }); $('form.options').submit(function() { o.save(); return false; }); }); diff --git a/javascripts/popup.js b/javascripts/popup.js index 141d70c..21ec368 100644 --- a/javascripts/popup.js +++ b/javascripts/popup.js @@ -1,11 +1,57 @@ $(function() { var show_popup = $.db('show_popup') === "1"; if(!show_popup) { chrome.tabs.getSelected(null, function(tab) { chrome.extension.getBackgroundPage().readLater(tab); }); window.close(); } else { - //show + $('ul.links li > a.add').click(function() { + chrome.tabs.getSelected(null, function(tab) { + chrome.extension.getBackgroundPage().readLater(tab); + }); + window.close(); + return false; + }); + + $('ul.links li > a.text').click(function() { + chrome.tabs.getSelected(null, function(tab) { + chrome.tabs.update(tab.id, { + url: "http://www.instapaper.com/text?u=" + encodeURIComponent(tab.url) + }); + }); + window.close(); + return false; + }); + + $('ul.links li > a.unread').click(function() { + chrome.tabs.create({ + url: "http://www.instapaper.com/u" + }); + window.close(); + return false; + }); + + $('ul.links li > a.starred').click(function() { + chrome.tabs.create({ + url: "http://www.instapaper.com/starred" + }); + window.close(); + return false; + }); + + $('ul.links li > a.archive').click(function() { + chrome.tabs.create({ + url: "http://www.instapaper.com/archive" + }); + window.close(); + return false; + }); + + $('ul.links li > a.options').click(function() { + chrome.tabs.create({url: chrome.extension.getURL('options.html')}); + window.close(); + return false; + }); } }); diff --git a/manifest.json b/manifest.json index bf1c282..3ff10a5 100644 --- a/manifest.json +++ b/manifest.json @@ -1,28 +1,28 @@ { "name": "Instachrome", - "version": "1.1.1", + "version": "1.2.0", "description": "Save your URLs to Instapaper", "options_page": "options.html", "background_page": "background.html", "content_scripts": [{ "matches": ["http://*/*", "https://*/*"], "js": ["javascripts/keyboard.js"], "run_at": "document_start" }], "browser_action": { "default_icon": "images/default.png", "default_title": "Save to Instapaper", "popup": "popup.html" }, "icons": { "32": "images/icon/32.png", "48": "images/icon/48.png", "128": "images/icon/128.png" }, "permissions": [ "tabs", "http://ajax.googleapis.com/ajax/libs/jquery/**/*", "http://www.instapaper.com/api/", "https://www.instapaper.com/api/" ] } \ No newline at end of file diff --git a/options.html b/options.html index 51998d2..5392939 100644 --- a/options.html +++ b/options.html @@ -1,100 +1,101 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta charset="utf-8" /> <title>Instachrome Options</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript" src="javascripts/elastic.js"></script> <script type="text/javascript" src="javascripts/app.js"></script> <script type="text/javascript" src="javascripts/options.js"></script> <link href="stylesheets/elastic.css" rel="stylesheet" type="text/css" /> <link href="stylesheets/options.css" rel="stylesheet" type="text/css" /> </head> <body> <a href="http://pledgie.com/campaigns/9023" class="ribbon left"></a> <a href="http://github.com/edgarjs/instachrome" class="ribbon right"></a> <div class="container wrapper"> <h1 class="title">Instachrome Options</h1> <div class="flash"></div> <form class="options" action="#" method="post"> <fieldset class="container set"> <legend>Instapaper credentials</legend> <div class="container pad"> <div class="unit on-2 columns same-height"> <div class="column label"> <label for="username" class="vertical-center">Username:</label> </div> <div class="column"> <input type="text" class="text" spellcheck="false" name="username" id="username" /> </div> <div class="column label"> <label for="password">Password:</label> <div class="description">(If you have one)</div> </div> <div class="column"> <input type="password" class="text" name="password" id="password" /> </div> <div class="column label span-2"> <a href="http://www.instapaper.com/user/register" class="vertical-center description">Get a free account</a> </div> </div> </div> </fieldset> <fieldset class="container set"> <legend>Extras</legend> <div class="container pad"> <div class="unit on-2 columns same-height"> <div class="column label"> <label for="show_popup" class="vertical-center">Show popup:</label> </div> <div class="column"> <input type="checkbox" name="show_popup" class="vertical-center" id="show_popup" value="1" /> </div> <div class="column label"> <label for="auto_close">Auto close:</label> <div class="description">(Close tab after saved)</div> </div> <div class="column"> <input type="checkbox" name="auto_close" class="vertical-center" id="auto_close" value="1" /> </div> <div class="column label"> <label for="badge_style" class="vertical-center">Badge style:</label> </div> <div class="column"> <select name="badge_style" id="badge_style"> - <option value="0">Red Text</option> - <option value="1">Tick icon</option> + <option value="0">Text</option> + <option value="1">Icon</option> </select> </div> </div> </div> </fieldset> <input type="submit" class="button" value="Save" /> or <a href="#" class="close">Close</a> </form> <div class="container footer"> <p> by <a href="http://e.dgar.org">Edgar J. Suárez</a> | <a href="http://twitter.com/edgarjs">Twitter</a> | <a href="https://chrome.google.com/extensions/detail/fldildgghjoohccppflaohodcnmlacpb">Extension page</a> | <a href="http://instapaper.com">Instapaper</a> <br /> This page is powered by <a href="http://elasticss.com">Elastic CSS</a> + | Icons by <a href="http://famfamfam.com">famfamfam.com</a> </p> </div> </div> </body> </html> \ No newline at end of file diff --git a/popup.html b/popup.html index 66f0944..4c5a322 100644 --- a/popup.html +++ b/popup.html @@ -1,13 +1,22 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta charset="utf-8" /> <title>Instachrome Popup</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript" src="javascripts/app.js"></script> <script type="text/javascript" src="javascripts/popup.js"></script> + <link rel="stylesheet" href="stylesheets/popup.css" type="text/css" /> </head> <body> + <ul class="links"> + <li><a href="#" class="add">Read later</a></li> + <li><a href="#" class="text">Text View</a></li> + <li><a href="#" class="unread">Unread items</a></li> + <li><a href="#" class="starred">Starred items</a></li> + <li><a href="#" class="archive">Archived items</a></li> + <li><a href="#" class="options">Options</a></li> + </ul> </body> </html> \ No newline at end of file diff --git a/stylesheets/popup.css b/stylesheets/popup.css new file mode 100644 index 0000000..9fe67ea --- /dev/null +++ b/stylesheets/popup.css @@ -0,0 +1,55 @@ +body { + margin: 0; +} + +ul.links { + list-style: none; + margin: 0; + padding: 0; + width: 130px; +} + +ul.links li { + margin: 0; + font-size: 13px; +} + +ul.links li > a { + padding: 5px 0 5px 30px; + display: block; + height: 16px; + text-decoration: none; + color: #888; + font-family: sans-serif; + background: #eee 4px 5px no-repeat; +} + +ul.links li > a.add { + background-image: url("../images/add.png"); + border-radius: 5px 5px 0 0; +} + +ul.links li > a.text { + background-image: url("../images/text_view.png"); +} + +ul.links li > a.unread { + background-image: url("../images/unread.png"); +} + +ul.links li > a.starred { + background-image: url("../images/starred.png"); +} + +ul.links li > a.archive { + background-image: url("../images/archive.png"); +} + +ul.links li > a.options { + background-image: url("../images/options.png"); + border-radius: 0 0 5px 5px; +} + +ul.links li > a:hover { + color: #85C25A; +}
edgarjs/instachrome
f397cf052be8dda4a1c2f59b275dbb17dc6ecf75
Added readme file. Added link to get an Instapaper account on options page.
diff --git a/README b/README new file mode 100644 index 0000000..c9ed193 --- /dev/null +++ b/README @@ -0,0 +1,4 @@ +Chrome extension for saving tab to instapaper. + +You can find it here: +https://chrome.google.com/extensions/detail/fldildgghjoohccppflaohodcnmlacpb diff --git a/javascripts/options.js b/javascripts/options.js index 13b6545..11e6ba6 100644 --- a/javascripts/options.js +++ b/javascripts/options.js @@ -1,72 +1,76 @@ (function($) { $.flash = function(msg) { $('.flash').text(msg).fadeIn('fast'); }; })(jQuery); var Options = function() { var BADGE_STYLES = [ 'Red Text', 'Tick Icon' ]; var values = { username: null, password: null, show_popup: false, auto_close: false, badge_style: 0 }; var ui = { username: $('input#username'), password: $('input#password'), show_popup: $('input#show_popup'), auto_close: $('input#auto_close'), badge_style: $('select#badge_style') }; return { restore: function() { if(location.hash === '#setup') { $.flash('Enter your Instapaper credentials in order to save an URL.'); } ui.username.val($.db('username')); ui.password.val($.db('password')); if($.db('show_popup') === '1') { ui.show_popup.attr('checked', true); } if($.db('auto_close') === '1') { ui.auto_close.attr('checked', true); } ui.badge_style.val($.db('badge_style')); }, save: function() { $.db('username', ui.username.val()); $.db('password', ui.password.val()); $.db('show_popup', ui.show_popup.is(':checked') ? '1' : '0'); $.db('auto_close', ui.auto_close.is(':checked') ? '1' : '0'); $.db('badge_style', ui.badge_style.val()); $.flash('Options saved successfully!'); } }; }; $(function() { var o = new Options(); o.restore(); $('.flash').click(function() { $(this).fadeOut('slow'); return false; }); + $('.close').click(function() { + window.close(); + }); + $('form.options').submit(function() { o.save(); return false; }); }); diff --git a/options.html b/options.html index 94aa6ad..51998d2 100644 --- a/options.html +++ b/options.html @@ -1,96 +1,100 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta charset="utf-8" /> <title>Instachrome Options</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript" src="javascripts/elastic.js"></script> <script type="text/javascript" src="javascripts/app.js"></script> <script type="text/javascript" src="javascripts/options.js"></script> <link href="stylesheets/elastic.css" rel="stylesheet" type="text/css" /> <link href="stylesheets/options.css" rel="stylesheet" type="text/css" /> </head> <body> <a href="http://pledgie.com/campaigns/9023" class="ribbon left"></a> <a href="http://github.com/edgarjs/instachrome" class="ribbon right"></a> <div class="container wrapper"> <h1 class="title">Instachrome Options</h1> <div class="flash"></div> <form class="options" action="#" method="post"> <fieldset class="container set"> <legend>Instapaper credentials</legend> <div class="container pad"> <div class="unit on-2 columns same-height"> <div class="column label"> <label for="username" class="vertical-center">Username:</label> </div> <div class="column"> <input type="text" class="text" spellcheck="false" name="username" id="username" /> </div> <div class="column label"> <label for="password">Password:</label> <div class="description">(If you have one)</div> </div> <div class="column"> <input type="password" class="text" name="password" id="password" /> </div> + + <div class="column label span-2"> + <a href="http://www.instapaper.com/user/register" class="vertical-center description">Get a free account</a> + </div> </div> </div> </fieldset> <fieldset class="container set"> <legend>Extras</legend> <div class="container pad"> <div class="unit on-2 columns same-height"> <div class="column label"> <label for="show_popup" class="vertical-center">Show popup:</label> </div> <div class="column"> <input type="checkbox" name="show_popup" class="vertical-center" id="show_popup" value="1" /> </div> <div class="column label"> <label for="auto_close">Auto close:</label> <div class="description">(Close tab after saved)</div> </div> <div class="column"> <input type="checkbox" name="auto_close" class="vertical-center" id="auto_close" value="1" /> </div> <div class="column label"> <label for="badge_style" class="vertical-center">Badge style:</label> </div> <div class="column"> <select name="badge_style" id="badge_style"> <option value="0">Red Text</option> <option value="1">Tick icon</option> </select> </div> </div> </div> </fieldset> <input type="submit" class="button" value="Save" /> or - <a href="#">Close</a> + <a href="#" class="close">Close</a> </form> <div class="container footer"> <p> by <a href="http://e.dgar.org">Edgar J. Suárez</a> | <a href="http://twitter.com/edgarjs">Twitter</a> | <a href="https://chrome.google.com/extensions/detail/fldildgghjoohccppflaohodcnmlacpb">Extension page</a> | <a href="http://instapaper.com">Instapaper</a> <br /> This page is powered by <a href="http://elasticss.com">Elastic CSS</a> </p> </div> </div> </body> </html> \ No newline at end of file
edgarjs/instachrome
23a37d9e632cd5baf0e522deed7183f6f973e1e6
Styled options page. Added keyboard shortcut. Added extra options for auto close. Added option for show popup menu.
diff --git a/background.html b/background.html index de270b6..eea0918 100644 --- a/background.html +++ b/background.html @@ -1,7 +1,13 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" + "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> - <script src="javascripts/instapaper.js" type="text/javascript"></script> + <meta charset="utf-8" /> + <title>Instachrome Popup</title> + <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> + <script type="text/javascript" src="javascripts/app.js"></script> + <script type="text/javascript" src="javascripts/background.js"></script> </head> <body> </body> </html> \ No newline at end of file diff --git a/images/donation_ribbon.png b/images/donation_ribbon.png new file mode 100644 index 0000000..dd69833 Binary files /dev/null and b/images/donation_ribbon.png differ diff --git a/images/forkme_ribbon.png b/images/forkme_ribbon.png new file mode 100644 index 0000000..146ef8a Binary files /dev/null and b/images/forkme_ribbon.png differ diff --git a/javascripts/app.js b/javascripts/app.js new file mode 100644 index 0000000..49382f7 --- /dev/null +++ b/javascripts/app.js @@ -0,0 +1,10 @@ +(function($) { + $.db = function(attr, val) { + if(typeof val === 'undefined') { + return localStorage[attr]; + } else { + localStorage[attr] = val; + return val; + } + }; +})(jQuery); diff --git a/javascripts/background.js b/javascripts/background.js new file mode 100644 index 0000000..2b7b52d --- /dev/null +++ b/javascripts/background.js @@ -0,0 +1,63 @@ +var last_tab_id; +var badge_styles = { + TEXT: 0, + ICON: 1 +}; + +function onComplete(xhr) { + // TODO: validate badge style + if(xhr.srcElement.status == 201) { + if($.db('auto_close') === '1') { + chrome.tabs.remove(last_tab_id); + } else { + chrome.browserAction.setBadgeText({text: 'done', tabId: last_tab_id}); + } + } else { + chrome.browserAction.setBadgeText({text: 'error', tabId: last_tab_id}); + } +} + +function sendRequest(url) { + var xhr = new XMLHttpRequest(); + var username = $.db('username'); + var password = $.db('password') || ''; + + if(!username) { + chrome.browserAction.setIcon({path: 'images/default.png', tabId: last_tab_id}); + chrome.tabs.create({url: chrome.extension.getURL('options.html')}); + return; + } + + username = encodeURIComponent(username); + password = encodeURIComponent(password); + url = encodeURIComponent(url); + + xhr.onreadystatechange = onComplete; + // TODO: set selection to the page selected text, or excerpt + var params = "?url=" + url + "&username=" + username + "&password=" + password + "&auto-title=1"; + + xhr.open("GET", 'https://www.instapaper.com/api/add' + params, true); + xhr.send(); +} + +function readLater(tab) { + last_tab_id = tab.id; + switch(parseInt($.db('badge_style'))) { + case badge_styles.TEXT: + chrome.browserAction.setBadgeText({text: 'saving', tabId: last_tab_id}); + break; + case badge_styles.ICON: + // TODO: use icon + chrome.browserAction.setBadgeText({text: 'saving', tabId: last_tab_id}); + break; + } + sendRequest(tab.url); +} + +chrome.browserAction.onClicked.addListener(readLater); +// from key shortcut +chrome.extension.onRequest.addListener(function(request, sender, sendResponse) { + if(sender.tab) { + readLater(sender.tab); + } + }); diff --git a/javascripts/elastic.js b/javascripts/elastic.js new file mode 100644 index 0000000..47cf844 --- /dev/null +++ b/javascripts/elastic.js @@ -0,0 +1,13 @@ +/* + Elastic CSS Framework + Released under the MIT, BSD, and GPL Licenses. + More information http://elasticss.com + + Elastic Engine + + @author Fernando Trasviña (@azendal) + @core team Sergio de la Garza (@sgarza), Javier Ayala (@javi_ayala) + @copyright 2009 Elastic CSS framework + @version 2.0.2 +*/ +(function($){var CStyle=function(element,pseudoElement){if(window.getComputedStyle){return window.getComputedStyle(element,pseudoElement)}else{return element.currentStyle}};var width=function(element){var width=CStyle(element).width;if(width=="auto"||width.indexOf("px")<0){return $(element).width()}else{return parseFloat(width)}};window.Elastic=function Elastic(context){var r,ra,i,j,k,l,il,jl,kl,ll,econs,econ,econw,econclass,ecols,ecol,ecolclass,eg,egml,egcl,egnl,ecrw,ecw,escol,rp,ig,efcs,efcsw,eecs,eecsw,eecw,eecrw,ecs,ecsw,ec,ecclass,eecfw,ecolminw,ecolmaxw,egreg=/(^|\s+)on\-(\d+)(\s+|$)/,esreg=/(^|\s+)span\-(\d+)(\s+|$)/,eareg=/(^|\s+)adaptive\-(\d+)\-(\d+)(\s+|$)/;eg=[];egcl=egnl=0;econs=$.find(".columns",context);for(i=0,il=econs.length;i<il;i++){econ=econs[i];econclass=econ.className;if(econclass.indexOf("on-")>-1&&egreg.test(econclass)){egml=Number(RegExp.$2)}else{egml=$.find("> .column, > .container > .column",econ).length}econ=$.find("> .container",econ)[0]||econ;econw=width(econ);ecrw=econw/egml;ecw=Math.round(ecrw);if(econclass.indexOf("adaptive-")>-1&&eareg.test(econclass)){ecolminw=Number(RegExp.$2);ecolmaxw=Number(RegExp.$3);if(ecw>ecolmaxw){while(ecw>ecolmaxw){egml=egml+1;ecrw=econw/egml;ecw=Math.round(ecrw)}}else{if(ecw<ecolminw){while(ecw<ecolminw){egml=egml-1;ecrw=econw/egml;ecw=Math.round(ecrw)}}}}ecols=$.find("> .column",econ);for(j=0,jl=ecols.length;j<jl;j++){efcs=[];eecs=[];ecs=[];rp=ig=efcsw=ecsw=0;ecol=ecols[j];ecolclass=ecol.className;escol=1;if(ecolclass.indexOf("span-")>-1&&esreg.test(ecolclass)){escol=Number(RegExp.$2)}ecol.escol=escol=((escol<=egml)?escol:egml);egnl+=escol;if(egnl==egml||j==(jl-1)||ecolclass.indexOf("final")>-1){eg.push(ecol);egcl=0;rp=1}else{if(egnl<egml){eg.push(ecol);egcl=egnl}else{if(egnl>egml){egcl=escol;rp=1;ig=1}}}if(rp){for(k=0,kl=eg.length;k<kl;k++){ec=eg[k];ecclass=ec.className;if(ecclass.indexOf("fixed")>-1){efcs.push(ec);efcsw+=width(ec)}else{if(ecclass.indexOf("elastic")>-1){eecs.push(ec)}else{ecs.push(ec);if(ec==eg[kl-1]){ec.style.width=Math.round(ecrw*ec.escol)+"px"}else{ec.style.width=Math.round(ecw*ec.escol)+"px"}ecsw=ecsw+width(ec)}}}ll=eecs.length;if(ll>0){eecfw=econw-(ecsw+efcsw);if(eecfw<=0){continue}eecrw=eecfw/ll;eecw=Math.round(eecrw);eecsw=eecw*ll;for(l=0;l<ll;l++){eecs[l].style.width=eecw+"px"}if(eecsw>eecfw){ra=eecsw-eecfw+1;for(r=1;r<ra;r++){eecs[eecs.length-r].style.width=(eecw-1)+"px"}}else{if(eecsw<eecfw){ra=eecfw-eecsw+1;for(r=1;r<ra;r++){eecs[eecs.length-r].style.width=(eecw+1)+"px"}}}var tcw=0;for(var f=0;f<ll-1;f++){tcw+=Number(eecs[f].style.width.replace("px",""))}eecs[ll-1].style.width=(econw-(ecsw+efcsw+(tcw)))+"px"}else{if(ecol.escol==egml&&efcs.length===0){ecol.style.width=econw+"px"}else{if(ecs.length>0&&efcs.length===0&&egnl==egml){if(ecsw>econw){ra=ecsw-econw+1;for(r=1;r<ra;r++){ecs[ecs.length-r].style.width=((ecw-1)*ecs[ecs.length-r].escol)+"px"}}else{if(ecsw<econw){ra=econw-ecsw+1;for(r=1;r<ra;r++){ecs[ecs.length-r].style.width=((ecw+1)*ecs[ecs.length-r].escol)+"px"}}}var tcw=0;for(var f=0;f<ecs.length-1;f++){tcw+=Number(ecs[f].style.width.replace("px",""))}ec.style.width=(econw-(tcw))+"px"}else{if(egnl<egml&&ecolclass.indexOf("final")>-1){ecol.style["margin"+((econclass.indexOf("inverted")>-1)?"Left":"Right")]=(econw-ecsw-efcsw)+"px"}}}}eg=[];egnl=0}if(ig){eg=[ecol];egnl=escol}}}for(i in Elastic.helpers){if(Elastic.helpers.hasOwnProperty(i)){Elastic.helpers[i](context)}}};var Elastic=window.Elastic;Elastic.version="2.0.3";Elastic.reset=function Elastic_reset(context){var doc=$(document);doc.trigger("elastic:beforeReset");var i,w,wl,h,hl,p,pl,m,ml;h=$.find(".same-height > *, .full-height, .elastic-height",context);for(i=0,hl=h.length;i<hl;i++){h[i].style.height=""}p=$.find(".vertical-center, .center, .bottom",context);for(i=0,pl=p.length;i<pl;i++){p[i].parentNode.style.paddingTop="";p[i].parentNode.style.height=""}w=$.find(".column:not(.fixed), .full-width",context);for(i=0,wl=w.length;i<wl;i++){w[i].style.width=""}m=$.find(".column.final",context);for(i=0,ml=m.length;i<ml;i++){m[i].style.marginLeft="";m[i].style.marginRight=""}doc.trigger("elastic:reset")};Elastic.refresh=function Elastic_refresh(context){var doc=$(document);doc.trigger("elastic:beforeRefresh");Elastic.reset(context);Elastic(context);doc.trigger("elastic:refresh")};Elastic.configuration={refreshOnResize:true};Elastic.helpers={"full-width":function Elastic_helper_fullWidth(context){var i,$el;var els=$.find(".full-width",context);var elsl=els.length;for(i=0;i<elsl;i++){$el=$(els[i]);$el.width($el.parent().width()-($el.outerWidth(true)-$el.width()))}},"same-height":function Elastic_helper_sameHeight(context){$(".same-height",context).each(function(){var columns=$("> *",this);var maxHeight=0;columns.each(function(){var currentHeight=$(this).outerHeight(true);maxHeight=(maxHeight>currentHeight)?maxHeight:currentHeight}).each(function(){$(this).css("height",maxHeight)})})},"full-height":function Elastic_helper_fullHeight(context){$(".full-height",context).each(function(){var _this=$(this);_this.css("height",$(this.parentNode).height()-(_this.outerHeight(true)-_this.height()))})},"elastic-height":function Elastic_helper_elasticHeight(context){$(".elastic-height",context).each(function(){var _this=$(this);var h=0;$("> *:not(.elastic-height)",this.parentNode).each(function(){h+=$(this).outerHeight(true)});_this.css("height",Math.round(_this.parent().height()-h));Elastic.refresh(this)})},"center":function Elastic_helper_center(context){$(".vertical-center, .center",context).each(function(){var parentNode=$(this.parentNode);var paddingTop=Math.round((parentNode.height()-$(this).outerHeight(true))/2);parentNode.css({paddingTop:paddingTop+"px",height:(parentNode.css("height"))?(parentNode.outerHeight()-paddingTop):""})})},"bottom":function Elastic_helper_bottom(context){$(".bottom",context).each(function(){var parentNode=$(this.parentNode);var paddingTop=Math.round(parentNode.height()-$(this).outerHeight(true));parentNode.css({paddingTop:paddingTop+"px",height:(parentNode.css("height"))?(parentNode.outerHeight()-paddingTop):""})})}};$(document).bind("elastic:beforeInitialize",function(){var r=/(^|\s+)display\s+([\w\_\-\d]+)(\s+|$)/;$(".display").each(function Elastic_layout(){r.test(this.className);var c=".position-"+RegExp.$2;$(c).removeClass(c).appendTo(this)})})})(jQuery);jQuery(window).bind("load",function(){var doc=jQuery(document);var iw=document.body.clientWidth;doc.trigger("elastic:beforeInitialize");Elastic();if(iw!=document.body.clientWidth){Elastic.refresh()}jQuery(window).bind("resize",function Elastic_resizeHandler(){if(Elastic.configuration.refreshOnResize){Elastic.refresh()}});doc.bind("elastic",Elastic.refresh);doc.trigger("elastic:initialize")}); diff --git a/javascripts/instapaper.js b/javascripts/instapaper.js deleted file mode 100644 index 4285272..0000000 --- a/javascripts/instapaper.js +++ /dev/null @@ -1,52 +0,0 @@ -var lastTabId; - -function readLater(tab) { - lastTabId = tab.id; - chrome.browserAction.setBadgeText({text: 'saving', tabId: lastTabId}); - saveURL(tab.url); -} - -function savedComplete(xhr) { - if(xhr.srcElement.status == 201) { - chrome.browserAction.setBadgeText({text: 'done', tabId: lastTabId}); - } else { - chrome.browserAction.setBadgeText({text: 'error', tabId: lastTabId}); - } -} - -function saveURL(url) { - var xhr = new XMLHttpRequest(); - var username = localStorage['username']; - var password = localStorage['password'] || ''; - - if(!username) { - chrome.browserAction.setIcon({path: 'images/default.png', tabId: lastTabId}); - window.open(chrome.extension.getURL('options.html') + '#setup'); - return; - } - - username = encodeURIComponent(username); - password = encodeURIComponent(password); - url = encodeURIComponent(url); - - xhr.onreadystatechange = savedComplete; - var params = "?url=" + url + "&username=" + username + "&password=" + password + "&auto-title=1"; - - xhr.open("GET", 'https://www.instapaper.com/api/add' + params, true); - xhr.send(); -} - -chrome.browserAction.onClicked.addListener(readLater); -// For some reason, tghis event doesn't work. -// window.addEventListener('keyup', function(e) { -// switch (e.which) { -// // Shift + Alt + S -// case 83: -// if(e.altKey) { -// chrome.tabs.getSelected(null, function(tab) { -// readLater(tab); -// }); -// } -// break; -// } -// }, false); diff --git a/javascripts/keyboard.js b/javascripts/keyboard.js new file mode 100644 index 0000000..a85a6e4 --- /dev/null +++ b/javascripts/keyboard.js @@ -0,0 +1,8 @@ +// keyboard shortcut +window.addEventListener('keydown', function(e) { + // TODO: Make it configurable + // Shift + Alt + S + if(e.which === 83 && e.altKey) { + chrome.extension.sendRequest({source: "shortcut"}, function(response) {}); + } +}, false); diff --git a/javascripts/options.js b/javascripts/options.js index 9381c9f..13b6545 100644 --- a/javascripts/options.js +++ b/javascripts/options.js @@ -1,32 +1,72 @@ -function showFlashMsg(msg) { - var status = document.getElementById("status"); - status.innerHTML = msg; - status.style.display = 'block'; - setTimeout(function() { - status.innerHTML = ""; - status.style.display = 'none'; - }, - 5000); -} +(function($) { + $.flash = function(msg) { + $('.flash').text(msg).fadeIn('fast'); + }; +})(jQuery); -function save_options() { - var username = document.getElementById("username"); - var password = document.getElementById("password"); - localStorage["username"] = username.value; - localStorage["password"] = password.value; +var Options = function() { + var BADGE_STYLES = [ + 'Red Text', + 'Tick Icon' + ]; + + var values = { + username: null, + password: null, + show_popup: false, + auto_close: false, + badge_style: 0 + }; + + var ui = { + username: $('input#username'), + password: $('input#password'), + show_popup: $('input#show_popup'), + auto_close: $('input#auto_close'), + badge_style: $('select#badge_style') + }; + + + return { + restore: function() { + if(location.hash === '#setup') { + $.flash('Enter your Instapaper credentials in order to save an URL.'); + } + ui.username.val($.db('username')); + ui.password.val($.db('password')); + if($.db('show_popup') === '1') { + ui.show_popup.attr('checked', true); + } + if($.db('auto_close') === '1') { + ui.auto_close.attr('checked', true); + } + ui.badge_style.val($.db('badge_style')); + }, - showFlashMsg('Options Saved!'); -} + save: function() { + $.db('username', ui.username.val()); + $.db('password', ui.password.val()); + $.db('show_popup', ui.show_popup.is(':checked') ? '1' : '0'); + $.db('auto_close', ui.auto_close.is(':checked') ? '1' : '0'); + $.db('badge_style', ui.badge_style.val()); + + $.flash('Options saved successfully!'); + } + }; +}; -function restore_options() { - var username = localStorage["username"]; - if (document.location.hash == '#setup') { - showFlashMsg("Enter your Instapaper username and password."); - } - - if (!username) { - return; - } - document.getElementById('username').value = username; -} \ No newline at end of file +$(function() { + var o = new Options(); + o.restore(); + + $('.flash').click(function() { + $(this).fadeOut('slow'); + return false; + }); + + $('form.options').submit(function() { + o.save(); + return false; + }); +}); diff --git a/javascripts/popup.js b/javascripts/popup.js new file mode 100644 index 0000000..141d70c --- /dev/null +++ b/javascripts/popup.js @@ -0,0 +1,11 @@ +$(function() { + var show_popup = $.db('show_popup') === "1"; + if(!show_popup) { + chrome.tabs.getSelected(null, function(tab) { + chrome.extension.getBackgroundPage().readLater(tab); + }); + window.close(); + } else { + //show + } +}); diff --git a/manifest.json b/manifest.json index f3297d2..bf1c282 100644 --- a/manifest.json +++ b/manifest.json @@ -1,21 +1,28 @@ { "name": "Instachrome", "version": "1.1.1", "description": "Save your URLs to Instapaper", - "background_page": "background.html", "options_page": "options.html", + "background_page": "background.html", + "content_scripts": [{ + "matches": ["http://*/*", "https://*/*"], + "js": ["javascripts/keyboard.js"], + "run_at": "document_start" + }], "browser_action": { "default_icon": "images/default.png", - "default_title": "Read later" + "default_title": "Save to Instapaper", + "popup": "popup.html" }, "icons": { "32": "images/icon/32.png", "48": "images/icon/48.png", "128": "images/icon/128.png" }, "permissions": [ "tabs", + "http://ajax.googleapis.com/ajax/libs/jquery/**/*", "http://www.instapaper.com/api/", "https://www.instapaper.com/api/" ] } \ No newline at end of file diff --git a/options.html b/options.html index b6d3c44..94aa6ad 100644 --- a/options.html +++ b/options.html @@ -1,23 +1,96 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" + "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> - <title>Instapaper Options</title> + <meta charset="utf-8" /> + <title>Instachrome Options</title> + <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> + <script type="text/javascript" src="javascripts/elastic.js"></script> + <script type="text/javascript" src="javascripts/app.js"></script> <script type="text/javascript" src="javascripts/options.js"></script> + <link href="stylesheets/elastic.css" rel="stylesheet" type="text/css" /> <link href="stylesheets/options.css" rel="stylesheet" type="text/css" /> </head> -<body onload="restore_options()"> - <div id="status" style="display:none;"></div> - <p> - <label for="username">Username:</label> - <input type="text" name="username" id="username" /> - </p> - - <p> - <label for="password">Password (if have one):</label> - <input type="password" name="password" id="password" /> - </p> +<body> + <a href="http://pledgie.com/campaigns/9023" class="ribbon left"></a> + <a href="http://github.com/edgarjs/instachrome" class="ribbon right"></a> + <div class="container wrapper"> + <h1 class="title">Instachrome Options</h1> + + <div class="flash"></div> - <p> - <button onclick="save_options()">Save Options</button> - </p> + <form class="options" action="#" method="post"> + <fieldset class="container set"> + <legend>Instapaper credentials</legend> + <div class="container pad"> + <div class="unit on-2 columns same-height"> + <div class="column label"> + <label for="username" class="vertical-center">Username:</label> + </div> + <div class="column"> + <input type="text" class="text" spellcheck="false" name="username" id="username" /> + </div> + + <div class="column label"> + <label for="password">Password:</label> + <div class="description">(If you have one)</div> + </div> + <div class="column"> + <input type="password" class="text" name="password" id="password" /> + </div> + </div> + </div> + </fieldset> + + <fieldset class="container set"> + <legend>Extras</legend> + <div class="container pad"> + <div class="unit on-2 columns same-height"> + <div class="column label"> + <label for="show_popup" class="vertical-center">Show popup:</label> + </div> + <div class="column"> + <input type="checkbox" name="show_popup" class="vertical-center" id="show_popup" value="1" /> + </div> + + <div class="column label"> + <label for="auto_close">Auto close:</label> + <div class="description">(Close tab after saved)</div> + </div> + <div class="column"> + <input type="checkbox" name="auto_close" class="vertical-center" id="auto_close" value="1" /> + </div> + + <div class="column label"> + <label for="badge_style" class="vertical-center">Badge style:</label> + </div> + <div class="column"> + <select name="badge_style" id="badge_style"> + <option value="0">Red Text</option> + <option value="1">Tick icon</option> + </select> + </div> + </div> + </div> + </fieldset> + + <input type="submit" class="button" value="Save" /> or + <a href="#">Close</a> + </form> + + <div class="container footer"> + <p> + by <a href="http://e.dgar.org">Edgar J. Suárez</a> + | + <a href="http://twitter.com/edgarjs">Twitter</a> + | + <a href="https://chrome.google.com/extensions/detail/fldildgghjoohccppflaohodcnmlacpb">Extension page</a> + | + <a href="http://instapaper.com">Instapaper</a> + <br /> + This page is powered by <a href="http://elasticss.com">Elastic CSS</a> + </p> + </div> + </div> </body> </html> \ No newline at end of file diff --git a/popup.html b/popup.html new file mode 100644 index 0000000..66f0944 --- /dev/null +++ b/popup.html @@ -0,0 +1,13 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" + "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> +<html> + <head> + <meta charset="utf-8" /> + <title>Instachrome Popup</title> + <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> + <script type="text/javascript" src="javascripts/app.js"></script> + <script type="text/javascript" src="javascripts/popup.js"></script> + </head> +<body> +</body> +</html> \ No newline at end of file diff --git a/stylesheets/elastic.css b/stylesheets/elastic.css new file mode 100644 index 0000000..e5b4327 --- /dev/null +++ b/stylesheets/elastic.css @@ -0,0 +1,17 @@ +/* +Copyright (c) 2008, Yahoo! Inc. All rights reserved. +Code licensed under the BSD License: +http://developer.yahoo.net/yui/license.txt +version: 3.0.0pr1 +*/ +html{color:#000;background:#FFF;}body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,code,form,fieldset,legend,input,textarea,p,blockquote,th,td {margin:0;padding:0;}table {border-collapse:collapse;border-spacing:0;}fieldset,img {border:0;}address,caption,cite,code,dfn,em,strong,th,var {font-style:normal;font-weight:normal;}li {list-style:none;}caption,th {text-align:left;}h1,h2,h3,h4,h5,h6 {font-size:100%;font-weight:normal;}q:before,q:after {content:'';}abbr,acronym {border:0;font-variant:normal;}sup {vertical-align:text-top;}sub {vertical-align:text-bottom;}input,textarea,select {font-family:inherit;font-size:inherit;font-weight:inherit;}input,textarea,select {*font-size:100%;}legend {color:#000;}h1 {font-size : 138.5%; }h2 {font-size : 123.1%; }h3 {font-size : 108%; }h1,h2,h3 {margin : 1em 0;}h1,h2,h3,h4,h5,h6,strong {font-weight : bold; }abbr,acronym {border-bottom : 1px dotted #000;cursor : help;} em {font-style : italic;}blockquote,ul,ol,dl {margin : 1em;}ol,ul,dl {margin-left : 2em;}ol li {list-style : decimal outside;}ul li {list-style : disc outside;}dl dd {margin-left : 1em;}th {font-weight : bold;text-align : center;}caption {margin-bottom : .5em;text-align : center;}p,fieldset,table,pre {margin-bottom : 1em;}input[type=text],input[type=password],textarea{width : 12.25em;*width : 11.9em;}body {font:13px/1.231 arial,helvetica,clean,sans-serif;*font-size:small;*font:x-small;}select,input,button,textarea {font:99% arial,helvetica,clean,sans-serif;}table {font-size:inherit;font:100%;}pre,code,kbd,samp,tt {font-family:monospace;*font-size:108%;} + +/* +Elastic CSS Framework +Released under the MIT, BSD, and GPL Licenses. +More information http://elasticss.com + +@author Fernando Trasvi–a (@azendal) +@core team Sergio de la Garza (@sgarza), Javier Ayala (@javi_ayala) +*/ +.unit:after,.container:after,.columns:after,.column:after,.clearfix:after{content:" ";display:block;height:0;clear:both;visibility:hidden;}.unit,.container,.columns,.column,.clearfix{display:block;*zoom:1;*display:inline-block;}.full-height{display:block;}.same-height{display:block;}.elastic-height{height:0;}.horizontal-center{margin:0 auto;}.vertical-center{/* margin:auto 0; */display:block;}.center{/* margin:auto */margin:0 auto;}.column{float:left;}.column.final{display:block;}.column.fixed{width:auto;}.column.elastic{display:block;}.inverted>.column,.inverted>.container>.column{float:right;}.on-2.columns>.column:not(.fixed),.on-2.columns>.container>.column:not(.fixed){width:50%;}.on-3.columns>.column:not(.fixed),.on-3.columns>.container>.column:not(.fixed){width:33.33%;}.on-3.columns>.column.span-2,.on-3.columns>.container>.column.span-2{width:66.66%;}.on-4.columns>.column:not(.fixed),.on-4.columns>.container>.column:not(.fixed){width:25%;}.on-4.columns>.column.span-2,.on-4.columns>.container>.column.span-2{width:50%;}.on-4.columns>.column.span-3,.on-4.columns>.container>.column.span-2{width:75%;} diff --git a/stylesheets/options.css b/stylesheets/options.css index d26982f..2dee754 100644 --- a/stylesheets/options.css +++ b/stylesheets/options.css @@ -1,19 +1,86 @@ -label { +a { + color: #DC8145; +} + +a.ribbon { + top: 0; + position: absolute; + border: 0; display: block; - width: 160px; - float: left; - line-height: 1.5em; + width: 149px; + height: 149px; +} +a.ribbon.right { + right: 0; + background: url("../images/forkme_ribbon.png") 0 0 no-repeat; +} +a.ribbon.left { + left: 0; + background: url("../images/donation_ribbon.png") 0 0 no-repeat; +} + +.wrapper { + width: 500px; + margin: 20px auto; +} + +.flash { + background: #FFFFCC; + border: 1px solid #cccc00; + padding: 5px 0; + color: #666; + text-align: center; + margin: 10px 0; + display: none; + cursor: pointer; +} + +.title { + font-family: "Times New Roman"; + font-size: 2em; +} + +.set { + border: 1px solid #C7E2EF; + border-radius: 3px; + background-color: #ededed; +} + +.set > legend { + margin-left: 12px; + color: #52A8CF; + text-shadow: 1px 1px 1px #ccc; + cursor: default; +} + +.set > .pad { + padding: 6px; +} + +.set .column.label { + text-align: center; + color: #888; +} + +.set .column.label > .description { + font-size: 0.8em; +} + +.set .column > input.text { + border: 1px solid #ccc; + padding: 4px; + margin: 3px 0; + color: #52A8CF; + border-radius: 3px; } -input[type=text], input[type=password] { - border: 1px solid #888; - padding: 5px; - margin: 0; +.footer { + font-size: 0.8em; + color: #888; + text-align: center; + margin-top: 10em; } -#status { - background-color: #ffff99; - padding: 10px; - border: 1px solid #888; - font-weight: bold; +.footer a { + color: #333; } \ No newline at end of file
edgarjs/instachrome
67fa6d22471db1f8efc817b57ddaecd2ce97c6f2
Changed 'saved' to 'done'
diff --git a/javascripts/instapaper.js b/javascripts/instapaper.js index de8a17c..4285272 100644 --- a/javascripts/instapaper.js +++ b/javascripts/instapaper.js @@ -1,52 +1,52 @@ var lastTabId; function readLater(tab) { lastTabId = tab.id; chrome.browserAction.setBadgeText({text: 'saving', tabId: lastTabId}); saveURL(tab.url); } function savedComplete(xhr) { if(xhr.srcElement.status == 201) { - chrome.browserAction.setBadgeText({text: 'saved', tabId: lastTabId}); + chrome.browserAction.setBadgeText({text: 'done', tabId: lastTabId}); } else { chrome.browserAction.setBadgeText({text: 'error', tabId: lastTabId}); } } function saveURL(url) { var xhr = new XMLHttpRequest(); var username = localStorage['username']; var password = localStorage['password'] || ''; if(!username) { chrome.browserAction.setIcon({path: 'images/default.png', tabId: lastTabId}); window.open(chrome.extension.getURL('options.html') + '#setup'); return; } username = encodeURIComponent(username); password = encodeURIComponent(password); url = encodeURIComponent(url); xhr.onreadystatechange = savedComplete; var params = "?url=" + url + "&username=" + username + "&password=" + password + "&auto-title=1"; xhr.open("GET", 'https://www.instapaper.com/api/add' + params, true); xhr.send(); } chrome.browserAction.onClicked.addListener(readLater); // For some reason, tghis event doesn't work. // window.addEventListener('keyup', function(e) { // switch (e.which) { // // Shift + Alt + S // case 83: // if(e.altKey) { // chrome.tabs.getSelected(null, function(tab) { // readLater(tab); // }); // } // break; // } // }, false); diff --git a/manifest.json b/manifest.json index 85d24b9..f3297d2 100644 --- a/manifest.json +++ b/manifest.json @@ -1,21 +1,21 @@ { "name": "Instachrome", - "version": "1.1", + "version": "1.1.1", "description": "Save your URLs to Instapaper", "background_page": "background.html", "options_page": "options.html", "browser_action": { "default_icon": "images/default.png", "default_title": "Read later" }, "icons": { "32": "images/icon/32.png", "48": "images/icon/48.png", "128": "images/icon/128.png" }, "permissions": [ "tabs", "http://www.instapaper.com/api/", "https://www.instapaper.com/api/" ] } \ No newline at end of file