diff --git a/.vimrc b/.vimrc index 861b135..0575edc 100644 --- a/.vimrc +++ b/.vimrc @@ -2,7 +2,7 @@ " autocmd! VimEnter * source ~/.vimrc " Load rename plugin -so ~/.vim/Rename.vim +" so ~/.vim/Rename.vim " let g:EclimCompletionMethod = 'omnifunc' " Java Autocomplete @@ -182,17 +182,13 @@ vnoremap :b# " Quicksave command -noremap :update -vnoremap :update -inoremap :update +" noremap :update +" vnoremap :update +" inoremap :update " Execute current file with python noremap e :!python % -" Quick quit command -noremap E :qa! " Quit all windows - - " bind Ctrl+ keys to move around the windows, instead of using " Ctrl+w + " Every unnecessary keystroke that can be saved is good for your health :) @@ -201,7 +197,6 @@ map k map l map h - " easier moving between tabs map m :bn map n :bp @@ -213,21 +208,17 @@ map t :enew " map sort function to a key vnoremap s :sort - " easier moving of code blocks " Try to go into visual mode (v), thenselect several lines of code here and " then press ``>`` several times. vnoremap < >gv " better indentation - - " Show whitespace " MUST be inserted BEFORE the colorscheme command autocmd ColorScheme * highlight ExtraWhitespace ctermbg=red guibg=red au InsertLeave * match ExtraWhitespace /\s\+$/ - " Color scheme " mkdir -p ~/.vim/colors && cd ~/.vim/colors " wget -O wombat256mod.vim @@ -252,11 +243,11 @@ syntax on " E128 - visual continuation " W391 - blank line at end of file let g:syntastic_python_flake8_args='--ignore=W391, E501, E702' -let g:syntastic_python_flake8_show_quickfix=0 +let g:syntastic_python_flake8_show_quickfix=1 let g:pymode_lint_ignore="E501,W601,W391,W0401,E702" let g:pymode_rope_lookup_project = 0 -let g:pymode_lint_cwindow = 0 -let g:pymode_rope = 0 +let g:pymode_lint_cwindow = 1 +let g:pymode_rope = 1 let g:pymode_python="python3" let g:pymode_lint_checkers = ['pep8'] let g:pymode_breakpoint_cmd = 'import ipdb; ipdb.set_trace() # XXX BREAKPOINT' @@ -274,17 +265,10 @@ set fo-=t " don't automatically wrap text when typing set colorcolumn=120 highlight ColorColumn ctermbg=233 - -" easier formatting of paragraphs -vmap Q gq -nmap Q gqap - - " Useful settings set history=700 set undolevels=700 - " Real programmers don't use TABs but spaces set tabstop=4 set softtabstop=4 @@ -292,14 +276,12 @@ set shiftwidth=4 set shiftround set expandtab - " Make search case insensitive set hlsearch set incsearch set ignorecase set smartcase - " Disable stupid backup and swap files - they trigger too many events " for file system watchers "set nobackup @@ -364,12 +346,12 @@ let g:SuperTabDefaultCompletionType = "" " Settings for jedi-vim " cd ~/.vim/bundle " git clone git://github.com/davidhalter/jedi-vim.git -let g:jedi#usages_command = "z" -let g:jedi#popup_on_dot = 0 -let g:jedi#popup_select_first = 0 -let g:jedi#force_py_version = 3 +" let g:jedi#usages_command = "z" +" let g:jedi#popup_on_dot = 0 +" let g:jedi#popup_select_first = 0 +" let g:jedi#force_py_version = 3 " let g:jedi#completions_command = '.' -map b Oimport ipdb; ipdb.set_trace() # BREAKPOINT +" map b Oimport ipdb; ipdb.set_trace() # BREAKPOINT " Map C-a to select entire file "nnoremap ggVG @@ -381,11 +363,12 @@ noremap noremap " Do splits with Leader-\ and Leader-- +" Close splits with Leader-Shift-\ (leader-|) " nnoremap :vsp " nnoremap :sp noremap \ :vsp noremap - :sp - +noremap \| q " NERDTree settings " Open NERDTree by default @@ -451,14 +434,12 @@ endfunction " map visual mode keycombo 'co' to this function vmap co :call CommentLines() - " Encryption algo (vim -x file) set cm=blowfish2 " Improve perfomance with long lines set synmaxcol=200 - set autoread " Autosave diff --git a/vim-plugins/bundle/jedi-vim/.jedi_vim.py.un~ b/vim-plugins/bundle/jedi-vim/.jedi_vim.py.un~ deleted file mode 100644 index 5da8bd2..0000000 Binary files a/vim-plugins/bundle/jedi-vim/.jedi_vim.py.un~ and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/.travis.yml b/vim-plugins/bundle/jedi-vim/.travis.yml deleted file mode 100644 index 8f407fc..0000000 --- a/vim-plugins/bundle/jedi-vim/.travis.yml +++ /dev/null @@ -1,18 +0,0 @@ -sudo: false -language: python -env: - matrix: - - ENV=test - - ENV=check -matrix: - allow_failures: - # Needs to be fixed! - - env: ENV=test -install: - - | - if [ "$ENV" = "test" ]; then - pip install pytest - fi -script: - - vim --version - - make "$ENV" diff --git a/vim-plugins/bundle/jedi-vim/AUTHORS.txt b/vim-plugins/bundle/jedi-vim/AUTHORS.txt deleted file mode 100644 index 57c581e..0000000 --- a/vim-plugins/bundle/jedi-vim/AUTHORS.txt +++ /dev/null @@ -1,55 +0,0 @@ -Main Authors -============ - -David Halter (@davidhalter) - - -Contributors (in order of contributions) -======================================== - -Patrice Peterson (@runiq) -tek (@tek) -heavenshell (@heavenshell) -Danilo Bargen (@dbrgn) -mattn (@mattn) -Enrico Batista da Luz (@ricobl) -coot (@coot) -Artur Dryomov (@ming13) -andviro (@andviro) -Jean-Louis Fuchs (@ganwell) -Mathieu Comandon (@strycore) -Nick Hurley (@todesschaf) -gpoulin (@gpoulin) -Akinori Hattori (@hattya) -Luper Rouch (@flupke) -Matthew Moses (@mlmoses) -Tyler Wymer (@twymer) -Artem Nezvigin (@artnez) -rogererens (@rogererens) -Emily Strickland (@emilyst) -Tin Tvrtković (@Tinche) -Zekeriya Koc (@zekzekus) -ethinx (@ethinx) -Wouter Overmeire (@lodagro) -Stephen J. Fuhry (@fuhrysteve) -Sheng Yun (@ShengYun) -Yann Thomas-Gérard (@inside) -Colin Su (@littleq0903) -Arthur Jaron (@eyetracker) -Justin M. Keyes (@justinmk) -nagev (@np1) -Chris Lasher (@gotgenes) -Doan Thanh Nam (@tndoan) -Markus Koller (@toupeira) -Justin Cheevers @justincheevers -Talha Ahmed (@talha81) -Matthew Tylee Atkinson (@matatk) -Pedro Ferrari (@petobens) -Daniel Hahler (@blueyed) -Dave Honneffer (@pearofducks) -Bagrat Aznauryan (@n9code) -Tomoyuki Kashiro (@kashiro) -Tommy Allen (@tweekmonster) -Mingliang (@Aulddays) - -@something are github user names. diff --git a/vim-plugins/bundle/jedi-vim/CONTRIBUTING.md b/vim-plugins/bundle/jedi-vim/CONTRIBUTING.md deleted file mode 100644 index 285eb30..0000000 --- a/vim-plugins/bundle/jedi-vim/CONTRIBUTING.md +++ /dev/null @@ -1,12 +0,0 @@ -# We <3 pull requests! - - 1. Fork the Repo on github. - 2. Add yourself to AUTHORS.txt - 3. Add a test if possible. - 4. Push to your fork and submit a pull request. - -Please use PEP8 as a Python code style. For VIM, just try to style your -code similar to the jedi-vim code that is already there. - -# Bug reports -Please include the output of `:version` and `:JediDebugInfo`. diff --git a/vim-plugins/bundle/jedi-vim/LICENSE.txt b/vim-plugins/bundle/jedi-vim/LICENSE.txt deleted file mode 100644 index 12f223f..0000000 --- a/vim-plugins/bundle/jedi-vim/LICENSE.txt +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) <2013> - -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/vim-plugins/bundle/jedi-vim/Makefile b/vim-plugins/bundle/jedi-vim/Makefile deleted file mode 100644 index 22712ef..0000000 --- a/vim-plugins/bundle/jedi-vim/Makefile +++ /dev/null @@ -1,16 +0,0 @@ -test: - py.test - -build: - mkdir $@ -build/vint: | build - virtualenv $@ - $@/bin/pip install vim-vint -check: LINT_FILES:=after autoload ftplugin plugin -check: build/vint - build/vint/bin/vint $(LINT_FILES) - -clean: - rm -rf .cache build - -.PHONY: test check clean diff --git a/vim-plugins/bundle/jedi-vim/README.rst b/vim-plugins/bundle/jedi-vim/README.rst deleted file mode 100644 index 36002cf..0000000 --- a/vim-plugins/bundle/jedi-vim/README.rst +++ /dev/null @@ -1,246 +0,0 @@ -################################################# -jedi-vim - awesome Python autocompletion with VIM -################################################# - -.. image:: https://travis-ci.org/davidhalter/jedi-vim.png?branch=master - :target: https://travis-ci.org/davidhalter/jedi-vim - :alt: Travis-CI build status - -jedi-vim is a VIM binding to the autocompletion library -`Jedi `_. - -Here are some pictures: - -.. image:: https://github.com/davidhalter/jedi/raw/master/docs/_screenshots/screenshot_complete.png - -Completion for almost anything (Ctrl+Space). - -.. image:: https://github.com/davidhalter/jedi/raw/master/docs/_screenshots/screenshot_function.png - -Display of function/class bodies, docstrings. - -.. image:: https://github.com/davidhalter/jedi/raw/master/docs/_screenshots/screenshot_pydoc.png - -Documentation (Pydoc) support (with highlighting, Shift+k). - -There is also support for goto and renaming. - - -Get the latest from `github `_. - -Documentation -============= - -Documentation is available in your vim: ``:help jedi-vim``. You can also look -it up `on github `_. - -You can read the Jedi library documentation `here `_. - -If you want to report issues, just use the github issue tracker. In case of -questions about the software, please use `stackoverflow -`_ and tag your question with ``jedi-vim``. - - -Contributing -============ - -We love Pull Requests! Read the instructions in ``CONTRIBUTING.md``. - - -Features -======== - -The Jedi library understands most of Python's core features. From decorators to -generators, there is broad support. - -Apart from that, jedi-vim supports the following commands - -- Completion ```` -- Goto assignments ``g`` (typical goto function) -- Goto definitions ``d`` (follow identifier as far as possible, - includes imports and statements) -- Show Documentation/Pydoc ``K`` (shows a popup with assignments) -- Renaming ``r`` -- Usages ``n`` (shows all the usages of a name) -- Open module, e.g. ``:Pyimport os`` (opens the ``os`` module) - - -Installation -============ - -Requirements ------------- -You need a VIM version that was compiled with Python 2.6 or later -(``+python`` or ``+python3``), which is typical for most distributions on -Linux. You can check this from within VIM using -``:python3 import sys; print(sys.version)`` (use ``:python`` for Python 2). - -Manual installation -------------------- - -You might want to use `pathogen `_ or -`Vundle `_ to install jedi-vim. - -The first thing you need after that is an up-to-date version of Jedi. You can -either install it via ``pip install jedi`` or with -``git submodule update --init`` in your jedi-vim repository. - -Example installation command using Pathogen: - -.. code-block:: sh - - cd ~/.vim/bundle/ && git clone --recursive https://github.com/davidhalter/jedi-vim.git - - -Installation with your distribution ------------------------------------ - -On Arch Linux, you can also install jedi-vim from official repositories as -`vim-jedi `__. -It is also available on -`Debian (≥8) `__ and -`Ubuntu (≥14.04) `__ as -vim-python-jedi. -On Fedora Linux, it is available as -`vim-jedi `__. - -Please note that this version might be quite old compared to using jedi-vim -from Git. - -Caveats -------- - -Note that the `python-mode `_ VIM plugin seems -to conflict with jedi-vim, therefore you should disable it before enabling -jedi-vim. - -To enjoy the full features of jedi-vim, you should have VIM >= 7.3, compiled with -``+conceal`` (which is not the case on some platforms, including OS X). If your VIM -does not meet these requirements, the parameter recommendation list may not appear -when you type an open bracket after a function name. Please read -`the documentation `_ -for details. - - -Settings -======== - -Jedi is by default automatically initialized. If you don't want that I suggest -you disable the auto-initialization in your ``.vimrc``: - -.. code-block:: vim - - let g:jedi#auto_initialization = 0 - -There are also some VIM options (like ``completeopt`` and key defaults) which -are automatically initialized, but you can skip this: - -.. code-block:: vim - - let g:jedi#auto_vim_configuration = 0 - - -You can make jedi-vim use tabs when going to a definition etc: - -.. code-block:: vim - - let g:jedi#use_tabs_not_buffers = 1 - -If you are a person who likes to use VIM-splits, you might want to put this in your ``.vimrc``: - -.. code-block:: vim - - let g:jedi#use_splits_not_buffers = "left" - -This options could be "left", "right", "top", "bottom" or "winwidth". It will decide the direction where the split open. - -Jedi automatically starts the completion, if you type a dot, e.g. ``str.``, if -you don't want this: - -.. code-block:: vim - - let g:jedi#popup_on_dot = 0 - -Jedi selects the first line of the completion menu: for a better typing-flow -and usually saves one keypress. - -.. code-block:: vim - - let g:jedi#popup_select_first = 0 - -Jedi displays function call signatures in insert mode in real-time, highlighting -the current argument. The call signatures can be displayed as a pop-up in the -buffer (set to 1, the default), which has the advantage of being easier to refer -to, or in Vim's command line aligned with the function call (set to 2), which -can improve the integrity of Vim's undo history. - -.. code-block:: vim - - let g:jedi#show_call_signatures = "1" - -Here are a few more defaults for actions, read the docs (``:help jedi-vim``) to -get more information. If you set them to ``""``, they are not assigned. - -.. code-block:: vim - - NOTE: subject to change! - - let g:jedi#goto_command = "d" - let g:jedi#goto_assignments_command = "g" - let g:jedi#goto_definitions_command = "" - let g:jedi#documentation_command = "K" - let g:jedi#usages_command = "n" - let g:jedi#completions_command = "" - let g:jedi#rename_command = "r" - - -Finally, if you don't want completion, but all the other features, use: - -.. code-block:: vim - - let g:jedi#completions_enabled = 0 - -FAQ -=== - -I don't want the docstring window to popup during completion ------------------------------------------------------------- - -This depends on the ``completeopt`` option. Jedi initializes it in its -``ftplugin``. Add the following line to your ``.vimrc`` to disable it: - -.. code-block:: vim - - autocmd FileType python setlocal completeopt-=preview - - -I want to do autocompletion ---------------------------------- - -Don't even think about changing the Jedi command to ````, -use `supertab `_! - - -The completion is waaay too slow! ---------------------------------- - -Completion of complex libraries (like Numpy) should only be slow the first time -you complete it. After that, the results should be cached and very fast. - -If it's still slow, in case you've installed the python-mode VIM plugin, disable -it. It seems to conflict with jedi-vim. See issue `#163 -`__. - - -Testing -======= - -jedi-vim is being tested with a combination of `vspec -`_ and `py.test `_. - -The tests are in the ``test`` subdirectory, you can run them calling:: - - py.test - -The tests are automatically run with `travis -`_. diff --git a/vim-plugins/bundle/jedi-vim/__pycache__/jedi_vim.cpython-35.pyc b/vim-plugins/bundle/jedi-vim/__pycache__/jedi_vim.cpython-35.pyc deleted file mode 100644 index 7f1a3c5..0000000 Binary files a/vim-plugins/bundle/jedi-vim/__pycache__/jedi_vim.cpython-35.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/__pycache__/jedi_vim.cpython-36.pyc b/vim-plugins/bundle/jedi-vim/__pycache__/jedi_vim.cpython-36.pyc deleted file mode 100644 index 583d222..0000000 Binary files a/vim-plugins/bundle/jedi-vim/__pycache__/jedi_vim.cpython-36.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/after/ftplugin/python/jedi.vim b/vim-plugins/bundle/jedi-vim/after/ftplugin/python/jedi.vim deleted file mode 100644 index 2798207..0000000 --- a/vim-plugins/bundle/jedi-vim/after/ftplugin/python/jedi.vim +++ /dev/null @@ -1,23 +0,0 @@ -if !jedi#init_python() - finish -endif - -if g:jedi#auto_initialization - if g:jedi#completions_enabled - " We need our own omnifunc, so this overrides the omnifunc set by - " $VIMRUNTIME/ftplugin/python.vim. - setlocal omnifunc=jedi#completions - - " map ctrl+space for autocompletion - if g:jedi#completions_command ==# '' - " In terminals, sometimes equals . - imap - smap - endif - if len(g:jedi#completions_command) - execute 'inoremap '.g:jedi#completions_command.' jedi#complete_string(0)' - " A separate mapping for select mode: deletes and completes. - execute 'snoremap '.g:jedi#completions_command." '\c'.jedi#complete_string(0)" - endif - endif -endif diff --git a/vim-plugins/bundle/jedi-vim/after/syntax/python.vim b/vim-plugins/bundle/jedi-vim/after/syntax/python.vim deleted file mode 100644 index a410b3d..0000000 --- a/vim-plugins/bundle/jedi-vim/after/syntax/python.vim +++ /dev/null @@ -1,32 +0,0 @@ -if !jedi#init_python() - finish -endif - -if g:jedi#show_call_signatures > 0 && has('conceal') - " +conceal is the default for vim >= 7.3 - - let s:e = g:jedi#call_signature_escape - let s:full = s:e.'jedi=.\{-}'.s:e.'.\{-}'.s:e.'jedi'.s:e - let s:ignore = s:e.'jedi.\{-}'.s:e - exe 'syn match jediIgnore "'.s:ignore.'" contained conceal' - setlocal conceallevel=2 - syn match jediFatSymbol "\*_\*" contained conceal - syn match jediFat "\*_\*.\{-}\*_\*" contained contains=jediFatSymbol - syn match jediSpace "\v[ ]+( )@=" contained - exe 'syn match jediFunction "'.s:full.'" keepend extend ' - \ .' contains=jediIgnore,jediFat,jediSpace' - \ .' containedin=pythonComment,pythonString,pythonRawString' - unlet! s:e s:full s:ignore - - hi def link jediIgnore Ignore - hi def link jediFatSymbol Ignore - hi def link jediSpace Normal - - if exists('g:colors_name') - hi def link jediFunction CursorLine - hi def link jediFat TabLine - else - hi jediFunction term=NONE cterm=NONE ctermfg=6 guifg=Black gui=NONE ctermbg=0 guibg=Grey - hi jediFat term=bold,underline cterm=bold,underline gui=bold,underline ctermbg=0 guibg=#555555 - endif -endif diff --git a/vim-plugins/bundle/jedi-vim/autoload/.jedi.vim.un~ b/vim-plugins/bundle/jedi-vim/autoload/.jedi.vim.un~ deleted file mode 100644 index cfcf296..0000000 Binary files a/vim-plugins/bundle/jedi-vim/autoload/.jedi.vim.un~ and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/autoload/health/jedi.vim b/vim-plugins/bundle/jedi-vim/autoload/health/jedi.vim deleted file mode 100644 index 8c80e93..0000000 --- a/vim-plugins/bundle/jedi-vim/autoload/health/jedi.vim +++ /dev/null @@ -1,4 +0,0 @@ -function! health#jedi#check() abort - call health#report_start('jedi') - silent call jedi#debug_info() -endfunction diff --git a/vim-plugins/bundle/jedi-vim/autoload/jedi.vim b/vim-plugins/bundle/jedi-vim/autoload/jedi.vim deleted file mode 100644 index 9be2e43..0000000 --- a/vim-plugins/bundle/jedi-vim/autoload/jedi.vim +++ /dev/null @@ -1,609 +0,0 @@ -scriptencoding utf-8 - -" ------------------------------------------------------------------------ -" Settings initialization -" ------------------------------------------------------------------------ -let s:deprecations = { - \ 'get_definition_command': 'goto_definitions_command', - \ 'pydoc': 'documentation_command', - \ 'related_names_command': 'usages_command', - \ 'autocompletion_command': 'completions_command', - \ 'show_function_definition': 'show_call_signatures', -\ } - -let s:default_settings = { - \ 'use_tabs_not_buffers': 0, - \ 'use_splits_not_buffers': 1, - \ 'auto_initialization': 1, - \ 'auto_vim_configuration': 1, - \ 'goto_command': "'d'", - \ 'goto_assignments_command': "'g'", - \ 'goto_definitions_command': "''", - \ 'completions_command': "''", - \ 'call_signatures_command': "'n'", - \ 'usages_command': "'n'", - \ 'rename_command': "'r'", - \ 'popup_on_dot': 1, - \ 'documentation_command': "'K'", - \ 'show_call_signatures': 1, - \ 'show_call_signatures_delay': 500, - \ 'call_signature_escape': "'?!?'", - \ 'auto_close_doc': 1, - \ 'max_doc_height': 30, - \ 'popup_select_first': 1, - \ 'quickfix_window_height': 10, - \ 'completions_enabled': 1, - \ 'force_py_version': "'auto'", - \ 'smart_auto_mappings': 1, - \ 'use_tag_stack': 1 -\ } - -for [s:key, s:val] in items(s:deprecations) - if exists('g:jedi#'.s:key) - echom "'g:jedi#".s:key."' is deprecated. Please use 'g:jedi#".s:val."' instead. Sorry for the inconvenience." - exe 'let g:jedi#'.s:val.' = g:jedi#'.s:key - endif -endfor - -for [s:key, s:val] in items(s:default_settings) - if !exists('g:jedi#'.s:key) - exe 'let g:jedi#'.s:key.' = '.s:val - endif -endfor - - -" ------------------------------------------------------------------------ -" Python initialization -" ------------------------------------------------------------------------ -let s:script_path = fnameescape(expand(':p:h:h')) - -function! s:init_python() abort - if g:jedi#force_py_version !=# 'auto' - " Always use the user supplied version. - try - return jedi#force_py_version(g:jedi#force_py_version) - catch - throw 'Could not setup g:jedi#force_py_version: '.v:exception - endtry - endif - - " Handle "auto" version. - if has('nvim') || (has('python') && has('python3')) - " Neovim usually has both python providers. Skipping the `has` check - " avoids starting both of them. - - " Get default python version from interpreter in $PATH. - let s:def_py = system('python -c '.shellescape('import sys; sys.stdout.write(str(sys.version_info[0]))')) - if v:shell_error != 0 || !len(s:def_py) - if !exists('g:jedi#squelch_py_warning') - echohl WarningMsg - echom 'Warning: jedi-vim failed to get Python version from sys.version_info: ' . s:def_py - echom 'Falling back to version 2.' - echohl None - endif - let s:def_py = 2 - elseif &verbose - echom 'jedi-vim: auto-detected Python: '.s:def_py - endif - - " Make sure that the auto-detected version is available in Vim. - if !has('nvim') || has('python'.(s:def_py == 2 ? '' : s:def_py)) - return jedi#force_py_version(s:def_py) - endif - - " Add a warning in case the auto-detected version is not available, - " usually because of a missing neovim module in a VIRTUAL_ENV. - if has('nvim') - echohl WarningMsg - echom 'jedi-vim: the detected Python version ('.s:def_py.')' - \ 'is not functional.' - \ 'Is the "neovim" module installed?' - \ 'While jedi-vim will work, it might not use the' - \ 'expected Python path.' - echohl None - endif - endif - - if has('python') - call jedi#setup_py_version(2) - elseif has('python3') - call jedi#setup_py_version(3) - else - throw 'jedi-vim requires Vim with support for Python 2 or 3.' - endif - return 1 -endfunction - - -function! jedi#reinit_python() abort - unlet! s:_init_python - call jedi#init_python() -endfunction - - -let s:_init_python = -1 -function! jedi#init_python() abort - if s:_init_python == -1 - try - let s:_init_python = s:init_python() - catch - let s:_init_python = 0 - if !exists('g:jedi#squelch_py_warning') - echoerr 'Error: jedi-vim failed to initialize Python: ' - \ .v:exception.' (in '.v:throwpoint.')' - endif - endtry - endif - return s:_init_python -endfunction - - -let s:python_version = 'null' -function! jedi#setup_py_version(py_version) abort - if a:py_version == 2 - let cmd_init = 'pyfile' - let cmd_exec = 'python' - let s:python_version = 2 - elseif a:py_version == 3 - let cmd_init = 'py3file' - let cmd_exec = 'python3' - let s:python_version = 3 - else - throw 'jedi#setup_py_version: invalid py_version: '.a:py_version - endif - - try - execute cmd_init.' '.s:script_path.'/initialize.py' - catch - throw 'jedi#setup_py_version: '.v:exception - endtry - execute 'command! -nargs=1 PythonJedi '.cmd_exec.' ' - return 1 -endfunction - - -function! jedi#debug_info() abort - if s:python_version ==# 'null' - call s:init_python() - endif - if &verbose - if &filetype !=# 'python' - echohl WarningMsg | echo 'You should run this in a buffer with filetype "python".' | echohl None - endif - endif - echo '#### Jedi-vim debug information' - echo 'Using Python version:' s:python_version - let pyeval = s:python_version == 3 ? 'py3eval' : 'pyeval' - let s:pythonjedi_called = 0 - PythonJedi import vim; vim.command('let s:pythonjedi_called = 1') - if !s:pythonjedi_called - echohl WarningMsg - echom 'PythonJedi failed to run, likely a Python config issue.' - if exists(':CheckHealth') == 2 - echom 'Try :CheckHealth for more information.' - endif - echohl None - else - PythonJedi << EOF -vim.command("echo printf(' - sys.version: `%s`', {0!r})".format(', '.join([x.strip() for x in __import__('sys').version.split('\n')]))) -vim.command("echo printf(' - site module: `%s`', {0!r})".format(__import__('site').__file__)) - -try: - jedi_vim -except Exception as e: - vim.command("echo printf('ERROR: jedi_vim is not available: %s: %s', {0!r}, {1!r})".format(e.__class__.__name__, str(e))) -else: - try: - if jedi_vim.jedi is None: - vim.command("echo 'ERROR: the \"jedi\" Python module could not be imported.'") - vim.command("echo printf(' The error was: %s', {0!r})".format(getattr(jedi_vim, "jedi_import_error", "UNKNOWN"))) - else: - vim.command("echo printf('Jedi path: `%s`', {0!r})".format(jedi_vim.jedi.__file__)) - vim.command("echo printf(' - version: %s', {0!r})".format(jedi_vim.jedi.__version__)) - vim.command("echo ' - sys_path:'") - for p in jedi_vim.jedi.Script('')._evaluator.sys_path: - vim.command("echo printf(' - `%s`', {0!r})".format(p)) - except Exception as e: - vim.command("echo printf('There was an error accessing jedi_vim.jedi: %s', {0!r})".format(e)) -EOF - endif - echo ' - jedi-vim git version: ' - echon substitute(system('git -C '.s:script_path.' describe --tags --always --dirty'), '\v\n$', '', '') - echo ' - jedi git submodule status: ' - echon substitute(system('git -C '.s:script_path.' submodule status'), '\v\n$', '', '') - echo "\n" - echo '##### Settings' - echo '```' - for [k, V] in items(filter(copy(g:), "v:key =~# '\\v^jedi#'")) - exe 'let default = '.get(s:default_settings, - \ substitute(k, '\v^jedi#', '', ''), "'-'") - " vint: -ProhibitUsingUndeclaredVariable - if default !=# V - echo printf('g:%s = %s (default: %s)', k, string(V), string(default)) - unlet! V " Fix variable type mismatch with Vim 7.3. - endif - " vint: +ProhibitUsingUndeclaredVariable - endfor - echo "\n" - verb set omnifunc? completeopt? - echo '```' - - if &verbose - echo "\n" - echo '#### :version' - echo '```' - version - echo '```' - echo "\n" - echo '#### :messages' - echo '```' - messages - echo '```' - echo "\n" - echo "
:scriptnames" - echo "\n" - echo '```' - scriptnames - echo '```' - echo "
" - endif -endfunction - -function! jedi#force_py_version(py_version) abort - let g:jedi#force_py_version = a:py_version - return jedi#setup_py_version(a:py_version) -endfunction - - -function! jedi#force_py_version_switch() abort - if g:jedi#force_py_version == 2 - call jedi#force_py_version(3) - elseif g:jedi#force_py_version == 3 - call jedi#force_py_version(2) - else - throw "Don't know how to switch from ".g:jedi#force_py_version.'!' - endif -endfunction - - -" Helper function instead of `python vim.eval()`, and `.command()` because -" these also return error definitions. -function! jedi#_vim_exceptions(str, is_eval) abort - let l:result = {} - try - if a:is_eval - let l:result.result = eval(a:str) - else - execute a:str - let l:result.result = '' - endif - catch - let l:result.exception = v:exception - let l:result.throwpoint = v:throwpoint - endtry - return l:result -endfunction - -call jedi#init_python() " Might throw an error. - -" ------------------------------------------------------------------------ -" functions that call python code -" ------------------------------------------------------------------------ -function! jedi#goto() abort - PythonJedi jedi_vim.goto(mode="goto") -endfunction - -function! jedi#goto_assignments() abort - PythonJedi jedi_vim.goto(mode="assignment") -endfunction - -function! jedi#goto_definitions() abort - PythonJedi jedi_vim.goto(mode="definition") -endfunction - -function! jedi#usages() abort - PythonJedi jedi_vim.goto(mode="related_name") -endfunction - -function! jedi#rename(...) abort - PythonJedi jedi_vim.rename() -endfunction - -function! jedi#rename_visual(...) abort - PythonJedi jedi_vim.rename_visual() -endfunction - -function! jedi#completions(findstart, base) abort - PythonJedi jedi_vim.completions() -endfunction - -function! jedi#enable_speed_debugging() abort - PythonJedi jedi_vim.jedi.set_debug_function(jedi_vim.print_to_stdout, speed=True, warnings=False, notices=False) -endfunction - -function! jedi#enable_debugging() abort - PythonJedi jedi_vim.jedi.set_debug_function(jedi_vim.print_to_stdout) -endfunction - -function! jedi#disable_debugging() abort - PythonJedi jedi_vim.jedi.set_debug_function(None) -endfunction - -function! jedi#py_import(args) abort - PythonJedi jedi_vim.py_import() -endfun - -function! jedi#py_import_completions(argl, cmdl, pos) abort - PythonJedi jedi_vim.py_import_completions() -endfun - -function! jedi#clear_cache(bang) abort - PythonJedi jedi_vim.jedi.cache.clear_time_caches(True) - if a:bang - PythonJedi jedi_vim.jedi.parser.utils.ParserPickling.clear_cache() - endif -endfunction - - -" ------------------------------------------------------------------------ -" show_documentation -" ------------------------------------------------------------------------ -function! jedi#show_documentation() abort - PythonJedi if jedi_vim.show_documentation() is None: vim.command('return') - - let bn = bufnr('__doc__') - if bn > 0 - let wi=index(tabpagebuflist(tabpagenr()), bn) - if wi >= 0 - " If the __doc__ buffer is open in the current tab, jump to it - silent execute (wi+1).'wincmd w' - else - silent execute 'sbuffer '.bn - endif - else - split '__doc__' - endif - - setlocal modifiable - setlocal noswapfile - setlocal buftype=nofile - silent normal! ggdG - silent $put=l:doc - silent normal! 1Gdd - setlocal nomodifiable - setlocal nomodified - setlocal filetype=rst - - if l:doc_lines > g:jedi#max_doc_height " max lines for plugin - let l:doc_lines = g:jedi#max_doc_height - endif - execute 'resize '.l:doc_lines - - " quit comands - nnoremap q ZQ - execute 'nnoremap '.g:jedi#documentation_command.' ZQ' - - " highlight python code within rst - unlet! b:current_syntax - syn include @rstPythonScript syntax/python.vim - " 4 spaces - syn region rstPythonRegion start=/^\v {4}/ end=/\v^( {4}|\n)@!/ contains=@rstPythonScript - " >>> python code -> (doctests) - syn region rstPythonRegion matchgroup=pythonDoctest start=/^>>>\s*/ end=/\n/ contains=@rstPythonScript - let b:current_syntax = 'rst' -endfunction - -" ------------------------------------------------------------------------ -" helper functions -" ------------------------------------------------------------------------ - -function! jedi#add_goto_window(len) abort - set lazyredraw - cclose - let height = min([a:len, g:jedi#quickfix_window_height]) - execute 'belowright copen '.height - set nolazyredraw - if g:jedi#use_tabs_not_buffers == 1 - noremap :call jedi#goto_window_on_enter() - endif - augroup jedi_goto_window - au! - au WinLeave q " automatically leave, if an option is chosen - augroup END - redraw! -endfunction - - -function! jedi#goto_window_on_enter() abort - let l:list = getqflist() - let l:data = l:list[line('.') - 1] - if l:data.bufnr - " close goto_window buffer - normal! ZQ - PythonJedi jedi_vim.new_buffer(vim.eval('bufname(l:data.bufnr)')) - call cursor(l:data.lnum, l:data.col) - else - echohl WarningMsg | echo 'Builtin module cannot be opened.' | echohl None - endif -endfunction - - -function! s:syn_stack() abort - if !exists('*synstack') - return [] - endif - return map(synstack(line('.'), col('.') - 1), "synIDattr(v:val, 'name')") -endfunc - - -function! jedi#do_popup_on_dot_in_highlight() abort - let highlight_groups = s:syn_stack() - for a in highlight_groups - if a ==# 'pythonDoctest' - return 1 - endif - endfor - - for a in highlight_groups - for b in ['pythonString', 'pythonComment', 'pythonNumber'] - if a == b - return 0 - endif - endfor - endfor - return 1 -endfunc - - -let s:show_call_signatures_last = [0, 0, ''] -function! jedi#show_call_signatures() abort - if s:_init_python == 0 - return 1 - endif - let [line, col] = [line('.'), col('.')] - let curline = getline(line) - let reload_signatures = 1 - - " Caching. On the same line only. - if line == s:show_call_signatures_last[0] - " Check if the number of commas and parenthesis before or after the - " cursor has not changed since the last call, which means that the - " argument position was not changed and we can skip repainting. - let prevcol = s:show_call_signatures_last[1] - let prevline = s:show_call_signatures_last[2] - if substitute(curline[:col-2], '[^,()]', '', 'g') - \ == substitute(prevline[:prevcol-2], '[^,()]', '', 'g') - \ && substitute(curline[(col-2):], '[^,()]', '', 'g') - \ == substitute(prevline[(prevcol-2):], '[^,()]', '', 'g') - let reload_signatures = 0 - endif - endif - let s:show_call_signatures_last = [line, col, curline] - - if reload_signatures - PythonJedi jedi_vim.show_call_signatures() - endif -endfunction - - -function! jedi#clear_call_signatures() abort - if s:_init_python == 0 - return 1 - endif - - let s:show_call_signatures_last = [0, 0, ''] - PythonJedi jedi_vim.clear_call_signatures() -endfunction - - -function! jedi#configure_call_signatures() abort - augroup jedi_call_signatures - autocmd! * - if g:jedi#show_call_signatures == 2 " Command line call signatures - autocmd InsertEnter let g:jedi#first_col = s:save_first_col() - endif - autocmd InsertEnter let s:show_call_signatures_last = [0, 0, ''] - autocmd InsertLeave call jedi#clear_call_signatures() - if g:jedi#show_call_signatures_delay > 0 - autocmd InsertEnter let b:_jedi_orig_updatetime = &updatetime - \ | let &updatetime = g:jedi#show_call_signatures_delay - autocmd InsertLeave if exists('b:_jedi_orig_updatetime') - \ | let &updatetime = b:_jedi_orig_updatetime - \ | unlet b:_jedi_orig_updatetime - \ | endif - autocmd CursorHoldI call jedi#show_call_signatures() - else - autocmd CursorMovedI call jedi#show_call_signatures() - endif - augroup END -endfunction - - -" Determine where the current window is on the screen for displaying call -" signatures in the correct column. -function! s:save_first_col() abort - if bufname('%') ==# '[Command Line]' || winnr('$') == 1 - return 0 - endif - - let startwin = winnr() - let winwidth = winwidth(0) - if winwidth == &columns - return 0 - elseif winnr('$') == 2 - return startwin == 1 ? 0 : (winwidth(1) + 1) - elseif winnr('$') == 3 - if startwin == 1 - return 0 - endif - let ww1 = winwidth(1) - let ww2 = winwidth(2) - let ww3 = winwidth(3) - if ww1 + ww2 + ww3 + 2 == &columns - if startwin == 2 - return ww1 + 1 - else - return ww1 + ww2 + 2 - endif - elseif startwin == 2 - if ww2 + ww3 + 1 == &columns - return 0 - else - return ww1 + 1 - endif - else " startwin == 3 - if ww2 + ww3 + 1 == &columns - return ww2 + 1 - else - return ww1 + 1 - endif - endif - endif - return 0 -endfunction - - -function! jedi#complete_string(is_popup_on_dot) abort - if a:is_popup_on_dot && !(g:jedi#popup_on_dot && jedi#do_popup_on_dot_in_highlight()) - return '' - endif - if pumvisible() && !a:is_popup_on_dot - return "\" - else - return "\\\=jedi#complete_opened(".a:is_popup_on_dot.")\" - endif -endfunction - - -function! jedi#complete_opened(is_popup_on_dot) abort - if pumvisible() - " Only go down if it is visible, user-enabled and the longest - " option is set. - if g:jedi#popup_select_first && stridx(&completeopt, 'longest') > -1 - return "\" - endif - if a:is_popup_on_dot - if &completeopt !~# '\(noinsert\|noselect\)' - " Prevent completion of the first entry with dot completion. - return "\" - endif - endif - endif - return '' -endfunction - - -function! jedi#smart_auto_mappings() abort - " Auto put import statement after from module.name and complete - if search('\m^\s*from\s\+[A-Za-z0-9._]\{1,50}\%#\s*$', 'bcn', line('.')) - " Enter character and start completion. - return "\import \\\=jedi#complete_opened(1)\" - endif - return "\" -endfunction - - -"PythonJedi jedi_vim.jedi.set_debug_function(jedi_vim.print_to_stdout, speed=True, warnings=False, notices=False) -"PythonJedi jedi_vim.jedi.set_debug_function(jedi_vim.print_to_stdout) - -" vim: set et ts=4: diff --git a/vim-plugins/bundle/jedi-vim/conftest.py b/vim-plugins/bundle/jedi-vim/conftest.py deleted file mode 100644 index 34a4603..0000000 --- a/vim-plugins/bundle/jedi-vim/conftest.py +++ /dev/null @@ -1,60 +0,0 @@ -import os -import subprocess -import urllib -import zipfile - -import pytest - -VSPEC_URL = 'https://github.com/kana/vim-vspec/archive/1.4.1.zip' -CACHE_FOLDER = '.cache' -VSPEC_FOLDER = os.path.join(CACHE_FOLDER, 'vim-vspec-1.4.1') -VSPEC_RUNNER = os.path.join(VSPEC_FOLDER, 'bin/vspec') -TEST_DIR = 'test' - - -class IntegrationTestFile(object): - def __init__(self, path): - self.path = path - - def run(self): - output = subprocess.check_output( - [VSPEC_RUNNER, '.', VSPEC_FOLDER, self.path]) - for line in output.splitlines(): - if line.startswith(b'not ok') or line.startswith(b'Error'): - pytest.fail("{0} failed:\n{1}".format( - self.path, output.decode('utf-8')), pytrace=False) - - def __repr__(self): - return "<%s: %s>" % (type(self), self.path) - - -def pytest_configure(config): - if not os.path.isdir(CACHE_FOLDER): - os.mkdir(CACHE_FOLDER) - - if not os.path.exists(VSPEC_FOLDER): - name, hdrs = urllib.urlretrieve(VSPEC_URL) - z = zipfile.ZipFile(name) - for n in z.namelist(): - dest = os.path.join(CACHE_FOLDER, n) - destdir = os.path.dirname(dest) - if not os.path.isdir(destdir): - os.makedirs(destdir) - data = z.read(n) - if not os.path.isdir(dest): - with open(dest, 'w') as f: - f.write(data) - z.close() - os.chmod(VSPEC_RUNNER, 0o777) - - -def pytest_generate_tests(metafunc): - """ - :type metafunc: _pytest.python.Metafunc - """ - def collect_tests(): - for f in os.listdir(TEST_DIR): - if f.endswith('.vim'): - yield IntegrationTestFile(os.path.join(TEST_DIR, f)) - - metafunc.parametrize('case', list(collect_tests())) diff --git a/vim-plugins/bundle/jedi-vim/doc/jedi-vim.txt b/vim-plugins/bundle/jedi-vim/doc/jedi-vim.txt deleted file mode 100644 index 81bf2ce..0000000 --- a/vim-plugins/bundle/jedi-vim/doc/jedi-vim.txt +++ /dev/null @@ -1,544 +0,0 @@ -*jedi-vim.txt* - For Vim version 7.3 - Last change: 2014/07/29 - __ _______ _______ __ ____ ____ __ .___ ___.~ - | | | ____|| \ | | \ \ / / | | | \/ |~ - | | | |__ | .--. || | _____\ \/ / | | | \ / |~ -.--. | | | __| | | | || | |______\ / | | | |\/| |~ -| `--' | | |____ | '--' || | \ / | | | | | |~ - \______/ |_______||_______/ |__| \__/ |__| |__| |__|~ - - jedi-vim - awesome Python autocompletion with Vim - -============================================================================== -Contents *jedi-vim-contents* - -1. Introduction |jedi-vim-introduction| -2. Installation |jedi-vim-installation| - 2.0. Requirements |jedi-vim-installation-requirements| - 2.1. Manually |jedi-vim-installation-manually| - 2.2. Using Pathogen |jedi-vim-installation-pathogen| - 2.3. Using Vundle |jedi-vim-installation-vundle| - 2.4. Installing from Repositories |jedi-vim-installation-repos| -3. Supported Python features |jedi-vim-support| -4. Usage |jedi-vim-usage| -5. Mappings |jedi-vim-keybindings| - 5.1. Start completion |g:jedi#completions_command| - 5.2. Go to definition |g:jedi#goto_command| - 5.3. Go to assignment |g:jedi#goto_assignments_command| - 5.4 Go to definition (deprecated) |g:jedi#goto_definitions_command| - 5.5. Show documentation |g:jedi#documentation_command| - 5.6. Rename variables |g:jedi#rename_command| - 5.7. Show name usages |g:jedi#usages_command| - 5.8. Open module by name |:Pyimport| -6. Configuration |jedi-vim-configuration| - 6.1. auto_initialization |g:jedi#auto_initialization| - 6.2. auto_vim_configuration |g:jedi#auto_vim_configuration| - 6.3. popup_on_dot |g:jedi#popup_on_dot| - 6.4. popup_select_first |g:jedi#popup_select_first| - 6.5. auto_close_doc |g:jedi#auto_close_doc| - 6.6. show_call_signatures |g:jedi#show_call_signatures| - 6.7. show_call_signatures_delay |g:jedi#show_call_signatures_delay| - 6.8. use_tabs_not_buffers |g:jedi#use_tabs_not_buffers| - 6.9. squelch_py_warning |g:jedi#squelch_py_warning| - 6.10. completions_enabled |g:jedi#completions_enabled| - 6.11. use_splits_not_buffers |g:jedi#use_splits_not_buffers| - 6.12. force_py_version |g:jedi#force_py_version| - 6.13. smart_auto_mappings |g:jedi#smart_auto_mappings| - 6.14. use_tag_stack |g:jedi#use_tag_stack| -7. Testing |jedi-vim-testing| -8. Contributing |jedi-vim-contributing| -9. License |jedi-vim-license| - -============================================================================== -1. Introduction *jedi-vim-introduction* - -Jedi-vim is a Vim binding to the awesome Python autocompletion library -`jedi`. Among jedi's (and, therefore, jedi-vim's) features are: - -- Completion for a wide array of Python features (see |jedi-vim-support|) -- Robust in dealing with syntax errors and wrong indentation -- Parses complex module/function/class structures -- Infers function arguments from Sphinx/Epydoc strings -- Doesn't execute Python code -- Supports Virtualenv -- Supports Python 2.5+ and 3.2+ - -By leveraging this library, jedi-vim adds the following capabilities to Vim: - -- Displaying function/class bodies -- "Go to definition" command -- Displaying docstrings -- Renaming and refactoring -- Looking up related names - -============================================================================== -2. Installation *jedi-vim-installation* - ------------------------------------------------------------------------------- -2.0. Requirements *jedi-vim-installation-requirements* - -First of all, jedi-vim requires Vim to be compiled with the `+python` option. - -The jedi library has to be installed for jedi-vim to work properly. You can -install it first, by using e.g. your distribution's package manager, or by -using pip: > - - pip install jedi - -However, you can also install it as a git submodule if you don't want to use -jedi for anything but this plugin. How to do this is detailed below. - -It is best if you have VIM >= 7.3, compiled with the `+conceal` option. With -older versions, you will probably not see the parameter recommendation list -for functions after typing the open bracket. Some platforms (including OS X -releases) do not ship a VIM with `+conceal`. You can check if your VIM has the -feature with > - - :ver - -and look for "`+conceal`" (as opposed to "`-conceal`") or > - - :echo has('conceal') - -which will report 0 (not included) or 1 (included). If your VIM lacks this -feature and you would like function parameter completion, you will need to -build your own VIM, or use a package for your operating system that has this -feature (such as MacVim on OS X, which also contains a console binary). - ------------------------------------------------------------------------------- -2.1. Installing manually *jedi-vim-installation-manually* - -1a. Get the latest repository from Github: > - - git clone http://github.com/davidhalter/jedi-vim path/to/bundles/jedi-vim - -1b. If you want to install jedi as a submodule instead, issue this command: > - - git clone --recursive http://github.com/davidhalter/jedi-vim - -2. Put the plugin files into their respective folders in your vim runtime - directory (usually ~/.vim). Be sure to pay attention to the directory - structure! -3. Update the Vim help tags with > - - :helptags /doc - ------------------------------------------------------------------------------- -2.1. Installing using Pathogen *jedi-vim-installation-pathogen* - -Pathogen simplifies installation considerably. - -1.a Clone the git repository into your bundles directory: > - - git clone http://github.com/davidhalter/jedi-vim path/to/bundles/jedi-vim - -1b. Again, if you want to install jedi as a submodule, use this command - instead: > - - git clone --recursive http://github.com/davidhalter/jedi-vim - ------------------------------------------------------------------------------- -2.3. Installing using Vundle *jedi-vim-installation-vundle* - -1. Vundle automatically downloads subrepositories as git submodules, so you - will automatically get the jedi library with the jedi-vim plugin. Add the - following to the Bundles section in your .vimrc file: > - - Plugin 'davidhalter/jedi-vim' - -2. Issue the following command in Vim: > - - :PluginInstall - -Help tags are generated automatically, so you should be good to go. - ------------------------------------------------------------------------------- -2.4. Installing from Repositories *jedi-vim-installation-repos* - -Some Linux distributions have jedi-vim packages in their official -repositories. On Arch Linux, install vim-jedi. On Debian (8+) or Ubuntu -(14.04+) install vim-python-jedi. - -============================================================================== -3. Supported Python features *jedi-vim-support* - -The Jedi library does all the hard work behind the scenes. It supports -completion of a large number of Python features, among them: - -- Builtins -- Multiple `return`s or `yield`s -- Tuple assignments/array indexing/dictionary indexing -- `with`-statement/exception handling -- `*args` and `**kwargs` -- Decorators, lambdas, closures -- Generators, iterators -- Some descriptors: `property`/`staticmethod`/`classmethod` -- Some magic methods: `__call__`, `__iter__`, `__next__`, `__get__`, - `__getitem__`, `__init__` -- `list.append()`, `set.add()`, `list.extend()`, etc. -- (Nested) list comprehensions and ternary expressions -- Relative `import`s -- `getattr()`/`__getattr__`/`__getattribute__` -- Function annotations (py3k feature, are being ignored at the moment, but are - parsed) -- Class decorators (py3k feature, are being ignored at the moment, but are - parsed) -- Simple/usual `sys.path` modifications -- `isinstance` checks for `if`/`while`/`assert` case, that doesn’t work with - Jedi -- And more... - -Note: This list is not necessarily up to date. For a complete list of -features, please refer to the Jedi documentation at http://jedi.jedidjah.ch. - -============================================================================== -4. Usage *jedi-vim-usage* - -With the default settings, autocompletion can be triggered by typing -. The first entry will automatically be selected, so you can press - to insert it into your code or keep typing and narrow down your -completion options. The usual and / keybindings work as -well. Autocompletion is also triggered by typing a period in insert mode. -Since periods rarely occur in Python code outside of method/import lookups, -this is handy to have (but can be disabled). - -When it encounters a new module, jedi might take a few seconds to parse that -module's contents. Afterwards, the contents are cached and completion will be -almost instantaneous. - -============================================================================== -5. Key Bindings *jedi-vim-keybindings* - -All keybindings can be mapped by setting the appropriate global option. For -example, to set the keybinding for starting omnicompletion to instead of -, add the following setting to your .vimrc file: > - - let g:jedi#completions_command = "" - -Note: If you have |g:jedi#auto_initialization| set to 0, you have to create -a mapping yourself by calling a function: > - - " Using for omnicompletion - inoremap - " Use r (by default <\-r>) for renaming - nnoremap r :call jedi#rename() - " etc. - -Note: You can set commands to '', which means that they are empty and not -assigned. It's an easy way to "disable" functionality of jedi-vim. - ------------------------------------------------------------------------------- -5.1. `g:jedi#completions_command` *g:jedi#completions_command* -Function: n/a; see above -Default: Start completion - -Performs autocompletion (or omnicompletion, to be precise). - -Note: If you want to use for completion, please install Supertab: -https://github.com/ervandew/supertab. - ------------------------------------------------------------------------------- -5.2. `g:jedi#goto_command` *g:jedi#goto_command* -Function: `jedi#goto()` -Default: d Go to definition (or assignment) - -This function first tries |jedi#goto_definitions|, and falls back to -|jedi#goto_assignments| for builtin modules. It produces an error if nothing -could be found. -NOTE: this implementation is subject to change. -Ref: https://github.com/davidhalter/jedi/issues/570 - -This command tries to find the original definition of the function/class under -the cursor. Just like the `jedi#goto_assignments()` function, it does not work -if the definition isn't in a Python source file. - -The difference between `jedi#goto_assignments()` and `jedi#goto_definitions()` -is that the latter performs recursive lookups. Take, for example, the -following module structure: > - - # file1.py: - from file2 import foo - - # file2.py: - from file3 import bar as foo - - # file3.py - def bar(): - pass - -The `jedi#goto_assignments()` function will take you to the > - - from file2 import foo - -statement in file1.py, while the `jedi#goto_definitions()` function will take -you all the way to the > - - def bar(): - -line in file3.py. - ------------------------------------------------------------------------------- -5.3. `g:jedi#goto_assignments_command` *g:jedi#goto_assignments_command* -Function: `jedi#goto_assignments()` -Default: g Go to assignment - -This function finds the first definition of the function/class under the -cursor. It produces an error if the definition is not in a Python file. - ------------------------------------------------------------------------------- -5.4. `g:jedi#goto_definitions_command` *g:jedi#goto_definitions_command* -Function: `jedi#goto_definitions()` -Default: - Go to original definition - -NOTE: Deprecated. Use |g:jedi#goto_command| / |jedi#goto()| instead, which -currently uses this internally. - ------------------------------------------------------------------------------- -5.5. `g:jedi#documentation_command` *g:jedi#documentation_command* -Function: `jedi#show_documentation()` -Default: Show pydoc documentation - -This shows the pydoc documentation for the item currently under the cursor. -The documentation is opened in a horizontally split buffer. The height of this -buffer is controlled by `g:jedi#max_doc_height` (set by default to 30). - ------------------------------------------------------------------------------- -5.6. `g:jedi#rename_command` *g:jedi#rename_command* -Function: `jedi#rename()` -Default: r Rename variables - -Jedi-vim deletes the word currently under the cursor and puts Vim in insert -mode, where the user is expected to enter the new variable name. Upon leaving -insert mode, jedi-vim then renames all occurences of the old variable name -with the new one. The number of performed renames is displayed in the command -line. - ------------------------------------------------------------------------------- -5.7. `g:jedi#usages_command` *g:jedi#usages_command* -Function: `jedi#usages()` -Default: n Show usages of a name. - -The quickfix window is populated with a list of all names which point to the -definition of the name under the cursor. - ------------------------------------------------------------------------------- -5.8. Open module by name *:Pyimport* -Function: `jedi#py_import(args)` -Default: :Pyimport e.g. `:Pyimport os` shows os.py in VIM. - -Simulate an import and open that module in VIM. - -============================================================================== -6. Configuration *jedi-vim-configuration* - -Note: You currently have to set these options in your .vimrc. Setting them in -an ftplugin (e.g. ~/.vim/ftplugin/python/jedi-vim-settings.vim) will not work -because jedi-vim is not set up as an filetype plugin, but as a "regular" -plugin. - ------------------------------------------------------------------------------- -6.1. `g:jedi#auto_initialization` *g:jedi#auto_initialization* - -Upon initialization, jedi-vim performs the following steps: - -1. Set the current buffers 'omnifunc' to its own completion function - `jedi#completions` -2. Create mappings to commands specified in |jedi-vim-keybindings| -3. Call `jedi#configure_call_signatures()` if - `g:jedi#show_call_signatures` is set - -You can disable the default initialization routine by setting this option to -0. Beware that you have to perform the above steps yourself, though. - -Options: 0 or 1 -Default: 1 (Perform automatic initialization) - ------------------------------------------------------------------------------- -6.2. `g:jedi#auto_vim_configuration` *g:jedi#auto_vim_configuration* - -Jedi-vim sets 'completeopt' to `menuone,longest,preview` by default, if -'completeopt' is not changed from Vim's default. -It also remaps to in insert mode. - -If you want to keep your own configuration, disable this setting. - -Options: 0 or 1 -Default: 1 (Set 'completeopt' and mapping as described above) - ------------------------------------------------------------------------------- -6.3. `g:jedi#popup_on_dot` *g:jedi#popup_on_dot* - -Jedi-vim automatically starts completion upon typing a period in insert mode. - -However, when working with large modules, this can slow down your typing flow -since you have to wait for jedi to parse the module and show the completion -menu. By disabling this setting, completion is only started when you manually -press the completion key. - -Options: 0 or 1 -Default: 1 (Start completion on typing a period) - ------------------------------------------------------------------------------- -6.4. `g:jedi#popup_select_first` *g:jedi#popup_select_first* - -Upon starting completion, jedi-vim can automatically select the first entry -that pops up (without actually inserting it). - -This leads to a better typing flow: As you type more characters, the entries -in the completion menu are narrowed down. If they are narrowed down enough, -you can just press to insert the first match. - -Options: 0 or 1 -Default: 1 (Automatically select first completion entry) - ------------------------------------------------------------------------------- -6.5. `g:jedi#auto_close_doc` *g:jedi#auto_close_doc* - -When doing completion, jedi-vim shows the docstring of the currently selected -item in a preview window. By default, this window is being closed after -insertion of a completion item. - -Set this to 0 to leave the preview window open even after leaving insert mode. -This could be useful if you want to browse longer docstrings. - -Options: 0 or 1 -Default: 1 (Automatically close preview window upon leaving insert mode) - ------------------------------------------------------------------------------- -6.6. `g:jedi#show_call_signatures` *g:jedi#show_call_signatures* - -Jedi-vim can display a small window detailing the arguments of the currently -completed function and highlighting the currently selected argument. This can -be disabled by setting this option to 0. Setting this option to 2 shows call -signatures in the command line instead of a popup window. - -Options: 0, 1, or 2 -Default: 1 (Show call signatures window) - -Note: 'showmode' must be disabled for command line call signatures to be -visible. - -Note: This setting is ignored if |g:jedi#auto_initialization| is set to 0. In -that case, if you want to see call signatures, you have to set it up -manually by calling a function in your configuration file: > - - call jedi#configure_call_signatures() - ------------------------------------------------------------------------------- -6.7. `g:jedi#show_call_signatures_delay` *g:jedi#show_call_signatures_delay* - -The delay to be used with |g:jedi#show_call_signatures|. If it is greater -than 0 it will use Vim's |CursorHoldI| event instead of |CursorMovedI|. -It will temporarily set Vim's |'updatetime'| option during insert mode. - -Options: delay in milliseconds -Default: 500 - ------------------------------------------------------------------------------- -6.8. `g:jedi#use_tabs_not_buffers` *g:jedi#use_tabs_not_buffers* - -You can make jedi-vim open a new tab if you use the "go to", "show -definition", or "related names" commands. When you leave this at the default -(0), they open in the current buffer instead. - -Options: 0 or 1 -Default: 0 (Command output is put in a new tab) - ------------------------------------------------------------------------------- -6.9. `g:jedi#squelch_py_warning` *g:jedi#squelch_py_warning* - -When Vim has not been compiled with +python, jedi-vim shows a warning to that -effect and aborts loading itself. Set this to 1 to suppress that warning. - -Options: 0 or 1 -Default: 0 (Warning is shown) - ------------------------------------------------------------------------------- -6.10. `g:jedi#completions_enabled` *g:jedi#completions_enabled* - -If you don't want Jedi completion, but all the other features, you can disable -it in favor of another completion engine (that probably also uses Jedi, like -YCM). - -Options: 0 or 1 -Default: 1 - ------------------------------------------------------------------------------- -6.11. `g:jedi#use_splits_not_buffers` *g:jedi#use_splits_not_buffers* - -If you want to open new split for "go to", you could set this option to the -direction which you want to open a split with. - -Options: top, left, right, bottom or winwidth -Default: "" (not enabled by default) - -Note: with the 'winwidth' option the window is split vertically or horizontally -depending on the width of the window relative to 'textwidth'. This essentially -means that if the window is big enough it will be split vertically but if it is -small a horizontal split happens. - ------------------------------------------------------------------------------- -6.12. `g:jedi#force_py_version` *g:jedi#force_py_version* - -If you have installed both python 2 and python 3, you can force which one jedi -should use by setting this variable. It forces the internal Vim command, which -will be used for every jedi call to the respective python interpreter. -The variable can be set in the .vimrc like this to force python 3: - -let g:jedi#force_py_version = 3 - -This variable can be switched during runtime using the following function: -Function: `jedi#force_py_version_switch()` - -or set directly using this function, which has the same name as the variable: -Function: `jedi#force_py_version(py_version)` - -Options: 2 or 3 -Default: "auto" (will use sys.version_info from "python" in your $PATH) ------------------------------------------------------------------------------- -6.13. `g:jedi#smart_auto_mappings` *g:jedi#smart_auto_mappings* - -When you start typing `from module.name` jedi-vim automatically -adds the "import" statement and displays the autocomplete popup. - -This option can be disabled in the .vimrc: - -`let g:jedi#smart_auto_mappings = 0` - -Options: 0 or 1 -Default: 1 (enabled by default) - ------------------------------------------------------------------------------- -6.14. `g:jedi#use_tag_stack` *g:jedi#use_tag_stack* - -Write results of |jedi#goto| to a temporary file and use the |:tjump| command -to enable full |tagstack| functionality. Use of the tag stack allows -returning to the usage of a function with CTRL-T after exploring the -definition with arbitrary changes to the |jumplist|. - -Options: 0 or 1 -Default: 1 (enabled by default) - -============================================================================== -7. Testing *jedi-vim-testing* - -jedi-vim is being tested with a combination of vspec -https://github.com/kana/vim-vspec and py.test http://pytest.org/. - -The tests are in the test subdirectory, you can run them calling:: - - py.test - -The tests are automatically run with `travis -`_. - -============================================================================== -8. Contributing *jedi-vim-contributing* - -We love Pull Requests! Read the instructions in `CONTRIBUTING.md`. - -============================================================================== -9. License *jedi-vim-license* - -Jedi-vim is licensed with the MIT license. - - vim: textwidth=78 et filetype=help:norightleft: diff --git a/vim-plugins/bundle/jedi-vim/doc/tags b/vim-plugins/bundle/jedi-vim/doc/tags deleted file mode 100644 index 9538e5b..0000000 --- a/vim-plugins/bundle/jedi-vim/doc/tags +++ /dev/null @@ -1,38 +0,0 @@ -:Pyimport jedi-vim.txt /*:Pyimport* -g:jedi#auto_close_doc jedi-vim.txt /*g:jedi#auto_close_doc* -g:jedi#auto_initialization jedi-vim.txt /*g:jedi#auto_initialization* -g:jedi#auto_vim_configuration jedi-vim.txt /*g:jedi#auto_vim_configuration* -g:jedi#completions_command jedi-vim.txt /*g:jedi#completions_command* -g:jedi#completions_enabled jedi-vim.txt /*g:jedi#completions_enabled* -g:jedi#documentation_command jedi-vim.txt /*g:jedi#documentation_command* -g:jedi#force_py_version jedi-vim.txt /*g:jedi#force_py_version* -g:jedi#goto_assignments_command jedi-vim.txt /*g:jedi#goto_assignments_command* -g:jedi#goto_command jedi-vim.txt /*g:jedi#goto_command* -g:jedi#goto_definitions_command jedi-vim.txt /*g:jedi#goto_definitions_command* -g:jedi#popup_on_dot jedi-vim.txt /*g:jedi#popup_on_dot* -g:jedi#popup_select_first jedi-vim.txt /*g:jedi#popup_select_first* -g:jedi#rename_command jedi-vim.txt /*g:jedi#rename_command* -g:jedi#show_call_signatures jedi-vim.txt /*g:jedi#show_call_signatures* -g:jedi#show_call_signatures_delay jedi-vim.txt /*g:jedi#show_call_signatures_delay* -g:jedi#smart_auto_mappings jedi-vim.txt /*g:jedi#smart_auto_mappings* -g:jedi#squelch_py_warning jedi-vim.txt /*g:jedi#squelch_py_warning* -g:jedi#usages_command jedi-vim.txt /*g:jedi#usages_command* -g:jedi#use_splits_not_buffers jedi-vim.txt /*g:jedi#use_splits_not_buffers* -g:jedi#use_tabs_not_buffers jedi-vim.txt /*g:jedi#use_tabs_not_buffers* -g:jedi#use_tag_stack jedi-vim.txt /*g:jedi#use_tag_stack* -jedi-vim-configuration jedi-vim.txt /*jedi-vim-configuration* -jedi-vim-contents jedi-vim.txt /*jedi-vim-contents* -jedi-vim-contributing jedi-vim.txt /*jedi-vim-contributing* -jedi-vim-installation jedi-vim.txt /*jedi-vim-installation* -jedi-vim-installation-manually jedi-vim.txt /*jedi-vim-installation-manually* -jedi-vim-installation-pathogen jedi-vim.txt /*jedi-vim-installation-pathogen* -jedi-vim-installation-repos jedi-vim.txt /*jedi-vim-installation-repos* -jedi-vim-installation-requirements jedi-vim.txt /*jedi-vim-installation-requirements* -jedi-vim-installation-vundle jedi-vim.txt /*jedi-vim-installation-vundle* -jedi-vim-introduction jedi-vim.txt /*jedi-vim-introduction* -jedi-vim-keybindings jedi-vim.txt /*jedi-vim-keybindings* -jedi-vim-license jedi-vim.txt /*jedi-vim-license* -jedi-vim-support jedi-vim.txt /*jedi-vim-support* -jedi-vim-testing jedi-vim.txt /*jedi-vim-testing* -jedi-vim-usage jedi-vim.txt /*jedi-vim-usage* -jedi-vim.txt jedi-vim.txt /*jedi-vim.txt* diff --git a/vim-plugins/bundle/jedi-vim/ftplugin/python/jedi.vim b/vim-plugins/bundle/jedi-vim/ftplugin/python/jedi.vim deleted file mode 100644 index 158ea1f..0000000 --- a/vim-plugins/bundle/jedi-vim/ftplugin/python/jedi.vim +++ /dev/null @@ -1,50 +0,0 @@ -if !jedi#init_python() - finish -endif -" ------------------------------------------------------------------------ -" Initialization of jedi-vim -" ------------------------------------------------------------------------ - -if g:jedi#auto_initialization - " goto / get_definition / usages - if len(g:jedi#goto_command) - execute 'nnoremap '.g:jedi#goto_command.' :call jedi#goto()' - endif - if len(g:jedi#goto_assignments_command) - execute 'nnoremap '.g:jedi#goto_assignments_command.' :call jedi#goto_assignments()' - endif - if len(g:jedi#goto_definitions_command) - execute 'nnoremap '.g:jedi#goto_definitions_command.' :call jedi#goto_definitions()' - endif - if len(g:jedi#usages_command) - execute 'nnoremap '.g:jedi#usages_command.' :call jedi#usages()' - endif - " rename - if len(g:jedi#rename_command) - execute 'nnoremap '.g:jedi#rename_command.' :call jedi#rename()' - execute 'vnoremap '.g:jedi#rename_command.' :call jedi#rename_visual()' - endif - " documentation/pydoc - if len(g:jedi#documentation_command) - execute 'nnoremap '.g:jedi#documentation_command.' :call jedi#show_documentation()' - endif - - if g:jedi#show_call_signatures > 0 && has('conceal') - call jedi#configure_call_signatures() - endif - - if g:jedi#completions_enabled == 1 - inoremap . .=jedi#complete_string(1) - endif - - if g:jedi#smart_auto_mappings == 1 - inoremap =jedi#smart_auto_mappings() - end - - if g:jedi#auto_close_doc - " close preview if its still open after insert - augroup jedi_preview - autocmd! InsertLeave if pumvisible() == 0|pclose|endif - augroup END - endif -endif diff --git a/vim-plugins/bundle/jedi-vim/initialize.py b/vim-plugins/bundle/jedi-vim/initialize.py deleted file mode 100644 index 0636889..0000000 --- a/vim-plugins/bundle/jedi-vim/initialize.py +++ /dev/null @@ -1,26 +0,0 @@ -"""Python initialization for jedi module.""" - -try: - import traceback -except Exception as excinfo: - raise Exception('Failed to import traceback: {0}'.format(excinfo)) - -try: - import os, sys, vim - jedi_path = os.path.join(vim.eval('expand(s:script_path)'), 'jedi') - sys.path.insert(0, jedi_path) - - jedi_vim_path = vim.eval('expand(s:script_path)') - if jedi_vim_path not in sys.path: # Might happen when reloading. - sys.path.insert(0, jedi_vim_path) -except Exception as excinfo: - raise Exception('Failed to add to sys.path: {0}\n{1}'.format( - excinfo, traceback.format_exc())) - -try: - import jedi_vim -except Exception as excinfo: - raise Exception('Failed to import jedi_vim: {0}\n{1}'.format( - excinfo, traceback.format_exc())) -finally: - sys.path.remove(jedi_path) diff --git a/vim-plugins/bundle/jedi-vim/jedi/.coveragerc b/vim-plugins/bundle/jedi-vim/jedi/.coveragerc deleted file mode 100644 index 939a317..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/.coveragerc +++ /dev/null @@ -1,19 +0,0 @@ -[run] -omit = - jedi/_compatibility.py - jedi/evaluate/site.py - -[report] -# Regexes for lines to exclude from consideration -exclude_lines = - # Don't complain about missing debug-only code: - def __repr__ - if self\.debug - - # Don't complain if tests don't hit defensive assertion code: - raise AssertionError - raise NotImplementedError - - # Don't complain if non-runnable code isn't run: - if 0: - if __name__ == .__main__.: diff --git a/vim-plugins/bundle/jedi-vim/jedi/.travis.yml b/vim-plugins/bundle/jedi-vim/jedi/.travis.yml deleted file mode 100644 index 25c3a21..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/.travis.yml +++ /dev/null @@ -1,28 +0,0 @@ -language: python -python: 3.5 -sudo: false -env: - - TOXENV=py26 - - TOXENV=py27 - - TOXENV=py33 - - TOXENV=py34 - - TOXENV=py35 - - TOXENV=pypy - - TOXENV=cov - - TOXENV=sith -matrix: - allow_failures: - - env: TOXENV=cov - - env: TOXENV=sith - - env: TOXENV=pypy -python: 3.5 -install: - - pip install --quiet tox -script: - - tox -after_script: - - if [ $TOXENV == "cov" ]; then - pip install --quiet --use-mirrors coveralls; - coveralls; - fi - diff --git a/vim-plugins/bundle/jedi-vim/jedi/AUTHORS.txt b/vim-plugins/bundle/jedi-vim/jedi/AUTHORS.txt deleted file mode 100644 index bbd7ecd..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/AUTHORS.txt +++ /dev/null @@ -1,45 +0,0 @@ -Main Authors -============ - -David Halter (@davidhalter) -Takafumi Arakaki (@tkf) - -Code Contributors -================= - -Danilo Bargen (@dbrgn) -Laurens Van Houtven (@lvh) <_@lvh.cc> -Aldo Stracquadanio (@Astrac) -Jean-Louis Fuchs (@ganwell) -tek (@tek) -Yasha Borevich (@jjay) -Aaron Griffin -andviro (@andviro) -Mike Gilbert (@floppym) -Aaron Meurer (@asmeurer) -Lubos Trilety -Akinori Hattori (@hattya) -srusskih (@srusskih) -Steven Silvester (@blink1073) -Colin Duquesnoy (@ColinDuquesnoy) -Jorgen Schaefer (@jorgenschaefer) -Fredrik Bergroth (@fbergroth) -Mathias Fußenegger (@mfussenegger) -Syohei Yoshida (@syohex) -ppalucky (@ppalucky) -immerrr (@immerrr) immerrr@gmail.com -Albertas Agejevas (@alga) -Savor d'Isavano (@KenetJervet) -Phillip Berndt (@phillipberndt) -Ian Lee (@IanLee1521) -Farkhad Khatamov (@hatamov) -Kevin Kelley (@kelleyk) -Sid Shanker (@squidarth) -Reinoud Elhorst (@reinhrst) -Guido van Rossum (@gvanrossum) -Dmytro Sadovnychyi (@sadovnychyi) -Cristi Burcă (@scribu) -bstaint (@bstaint) - - -Note: (@user) means a github user name. diff --git a/vim-plugins/bundle/jedi-vim/jedi/CHANGELOG.rst b/vim-plugins/bundle/jedi-vim/jedi/CHANGELOG.rst deleted file mode 100644 index 4d000d8..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/CHANGELOG.rst +++ /dev/null @@ -1,67 +0,0 @@ -.. :changelog: - -Changelog ---------- - -0.10.0 (2016-06-) -+++++++++++++++++ - -- Actual semantic completions for the complete Python syntax. -- Basic type inference for ``yield from`` PEP 380. -- PEP 484 support (most of the important features of it). Thanks Claude! (@reinhrst) -- Added ``get_line_code`` to ``Definition`` and ``Completion`` objects. -- Again a lot of internal changes. - -0.9.0 (2015-04-10) -++++++++++++++++++ - -- The import logic has been rewritten to look more like Python's. There is now - an ``Evaluator.modules`` import cache, which resembles ``sys.modules``. -- Integrated the parser of 2to3. This will make refactoring possible. It will - also be possible to check for error messages (like compiling an AST would give) - in the future. -- With the new parser, the evaluation also completely changed. It's now simpler - and more readable. -- Completely rewritten REPL completion. -- Added ``jedi.names``, a command to do static analysis. Thanks to that - sourcegraph guys for sponsoring this! -- Alpha version of the linter. - - -0.8.1 (2014-07-23) -+++++++++++++++++++ - -- Bugfix release, the last release forgot to include files that improve - autocompletion for builtin libraries. Fixed. - -0.8.0 (2014-05-05) -+++++++++++++++++++ - -- Memory Consumption for compiled modules (e.g. builtins, sys) has been reduced - drastically. Loading times are down as well (it takes basically as long as an - import). -- REPL completion is starting to become usable. -- Various small API changes. Generally this release focuses on stability and - refactoring of internal APIs. -- Introducing operator precedence, which makes calculating correct Array - indices and ``__getattr__`` strings possible. - -0.7.0 (2013-08-09) -++++++++++++++++++ - -- Switched from LGPL to MIT license. -- Added an Interpreter class to the API to make autocompletion in REPL - possible. -- Added autocompletion support for namespace packages. -- Add sith.py, a new random testing method. - -0.6.0 (2013-05-14) -++++++++++++++++++ - -- Much faster parser with builtin part caching. -- A test suite, thanks @tkf. - -0.5 versions (2012) -+++++++++++++++++++ - -- Initial development. diff --git a/vim-plugins/bundle/jedi-vim/jedi/CONTRIBUTING.md b/vim-plugins/bundle/jedi-vim/jedi/CONTRIBUTING.md deleted file mode 100644 index 4dc59bf..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/CONTRIBUTING.md +++ /dev/null @@ -1,28 +0,0 @@ -Pull Requests are great (on the **dev** branch)! Readme/Documentation changes -are ok in the master branch. - - 1. Fork the Repo on github. - 2. If you are adding functionality or fixing a bug, please add a test! - 3. Add your name to AUTHORS.txt - 4. Push to your fork and submit a **pull request to the dev branch**. - -My **master** branch is a 100% stable (should be). I only push to it after I am -certain that things are working out. Many people are using Jedi directly from -the github master branch. - -**Try to use the PEP8 style guide.** - - -Changing Issues to Pull Requests (Github) ------------------------------------------ - -If you have have previously filed a GitHub issue and want to contribute code -that addresses that issue, we prefer it if you use -[hub](https://github.com/github/hub) to convert your existing issue to a pull -request. To do that, first push the changes to a separate branch in your fork -and then issue the following command: - - hub pull-request -b davidhalter:dev -i -h : - -It's no strict requirement though, if you don't have hub installed or prefer to -use the web interface, then feel free to post a traditional pull request. diff --git a/vim-plugins/bundle/jedi-vim/jedi/LICENSE.txt b/vim-plugins/bundle/jedi-vim/jedi/LICENSE.txt deleted file mode 100644 index 9492c4e..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/LICENSE.txt +++ /dev/null @@ -1,82 +0,0 @@ -All contributions towards Jedi are MIT licensed. - -Some Python files have been taken from the standard library and are therefore -PSF licensed. Modifications on these files are dual licensed (both MIT and -PSF). These files are: - -- jedi/parser/pgen2 -- jedi/parser/tokenize.py -- jedi/parser/token.py -- test/test_parser/test_pgen2.py - -------------------------------------------------------------------------------- -The MIT License (MIT) - -Copyright (c) <2013> - -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. -------------------------------------------------------------------------------- - -PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 --------------------------------------------- - -1. This LICENSE AGREEMENT is between the Python Software Foundation -("PSF"), and the Individual or Organization ("Licensee") accessing and -otherwise using this software ("Python") in source or binary form and -its associated documentation. - -2. Subject to the terms and conditions of this License Agreement, PSF hereby -grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, -analyze, test, perform and/or display publicly, prepare derivative works, -distribute, and otherwise use Python alone or in any derivative version, -provided, however, that PSF's License Agreement and PSF's notice of copyright, -i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, -2011, 2012, 2013, 2014, 2015 Python Software Foundation; All Rights Reserved" -are retained in Python alone or in any derivative version prepared by Licensee. - -3. In the event Licensee prepares a derivative work that is based on -or incorporates Python or any part thereof, and wants to make -the derivative work available to others as provided herein, then -Licensee hereby agrees to include in any such work a brief summary of -the changes made to Python. - -4. PSF is making Python available to Licensee on an "AS IS" -basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR -IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND -DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS -FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT -INFRINGE ANY THIRD PARTY RIGHTS. - -5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON -FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS -A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, -OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. - -6. This License Agreement will automatically terminate upon a material -breach of its terms and conditions. - -7. Nothing in this License Agreement shall be deemed to create any -relationship of agency, partnership, or joint venture between PSF and -Licensee. This License Agreement does not grant permission to use PSF -trademarks or trade name in a trademark sense to endorse or promote -products or services of Licensee, or any third party. - -8. By copying, installing or otherwise using Python, Licensee -agrees to be bound by the terms and conditions of this License -Agreement. diff --git a/vim-plugins/bundle/jedi-vim/jedi/MANIFEST.in b/vim-plugins/bundle/jedi-vim/jedi/MANIFEST.in deleted file mode 100644 index f25326a..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/MANIFEST.in +++ /dev/null @@ -1,14 +0,0 @@ -include README.rst -include CHANGELOG.rst -include LICENSE.txt -include AUTHORS.txt -include .coveragerc -include sith.py -include conftest.py -include pytest.ini -include tox.ini -include jedi/evaluate/compiled/fake/*.pym -include jedi/parser/grammar*.txt -recursive-include test * -recursive-include docs * -recursive-exclude * *.pyc diff --git a/vim-plugins/bundle/jedi-vim/jedi/README.rst b/vim-plugins/bundle/jedi-vim/jedi/README.rst deleted file mode 100644 index 1adf138..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/README.rst +++ /dev/null @@ -1,210 +0,0 @@ -################################################################### -Jedi - an awesome autocompletion/static analysis library for Python -################################################################### - -.. image:: https://secure.travis-ci.org/davidhalter/jedi.png?branch=master - :target: http://travis-ci.org/davidhalter/jedi - :alt: Travis-CI build status - -.. image:: https://coveralls.io/repos/davidhalter/jedi/badge.png?branch=master - :target: https://coveralls.io/r/davidhalter/jedi - :alt: Coverage Status - - -*If you have specific questions, please add an issue or ask on* `stackoverflow -`_ *with the label* ``python-jedi``. - - -Jedi is a static analysis tool for Python that can be used in IDEs/editors. Its -historic focus is autocompletion, but does static analysis for now as well. -Jedi is fast and is very well tested. It understands Python on a deeper level -than all other static analysis frameworks for Python. - -Jedi has support for two different goto functions. It's possible to search for -related names and to list all names in a Python file and infer them. Jedi -understands docstrings and you can use Jedi autocompletion in your REPL as -well. - -Jedi uses a very simple API to connect with IDE's. There's a reference -implementation as a `VIM-Plugin `_, -which uses Jedi's autocompletion. We encourage you to use Jedi in your IDEs. -It's really easy. - -Jedi can currently be used with the following editors/projects: - -- Vim (jedi-vim_, YouCompleteMe_, deoplete-jedi_) -- Emacs (Jedi.el_, company-mode_, elpy_, anaconda-mode_, ycmd_) -- Sublime Text (SublimeJEDI_ [ST2 + ST3], anaconda_ [only ST3]) -- TextMate_ (Not sure if it's actually working) -- Kate_ version 4.13+ supports it natively, you have to enable it, though. [`proof - `_] -- Atom_ (autocomplete-python_) -- SourceLair_ -- `GNOME Builder`_ (with support for GObject Introspection) -- `Visual Studio Code`_ (via `Python Extension `_) -- Gedit (gedi_) -- wdb_ - Web Debugger -- `Eric IDE`_ (Available as a plugin) - -and many more! - - -Here are some pictures taken from jedi-vim_: - -.. image:: https://github.com/davidhalter/jedi/raw/master/docs/_screenshots/screenshot_complete.png - -Completion for almost anything (Ctrl+Space). - -.. image:: https://github.com/davidhalter/jedi/raw/master/docs/_screenshots/screenshot_function.png - -Display of function/class bodies, docstrings. - -.. image:: https://github.com/davidhalter/jedi/raw/master/docs/_screenshots/screenshot_pydoc.png - -Pydoc support (Shift+k). - -There is also support for goto and renaming. - -Get the latest version from `github `_ -(master branch should always be kind of stable/working). - -Docs are available at `https://jedi.readthedocs.org/en/latest/ -`_. Pull requests with documentation -enhancements and/or fixes are awesome and most welcome. Jedi uses `semantic -versioning `_. - - -Installation -============ - - pip install jedi - -Note: This just installs the Jedi library, not the editor plugins. For -information about how to make it work with your editor, refer to the -corresponding documentation. - -You don't want to use ``pip``? Please refer to the `manual -`_. - - -Feature Support and Caveats -=========================== - -Jedi really understands your Python code. For a comprehensive list what Jedi -understands, see: `Features -`_. A list of -caveats can be found on the same page. - -You can run Jedi on cPython 2.6, 2.7, 3.3, 3.4 or 3.5 but it should also -understand/parse code older than those versions. - -Tips on how to use Jedi efficiently can be found `here -`_. - -API ---- - -You can find the documentation for the `API here `_. - - -Autocompletion / Goto / Pydoc ------------------------------ - -Please check the API for a good explanation. There are the following commands: - -- ``jedi.Script.goto_assignments`` -- ``jedi.Script.completions`` -- ``jedi.Script.usages`` - -The returned objects are very powerful and really all you might need. - - -Autocompletion in your REPL (IPython, etc.) -------------------------------------------- - -It's possible to have Jedi autocompletion in REPL modes - `example video `_. -This means that IPython and others are `supported -`_. - - -Static Analysis / Linter ------------------------- - -To do all forms of static analysis, please try to use ``jedi.names``. It will -return a list of names that you can use to infer types and so on. - -Linting is another thing that is going to be part of Jedi. For now you can try -an alpha version ``python -m jedi linter``. The API might change though and -it's still buggy. It's Jedi's goal to be smarter than classic linter and -understand ``AttributeError`` and other code issues. - - -Refactoring ------------ - -Jedi's parser would support refactoring, but there's no API to use it right -now. If you're interested in helping out here, let me know. With the latest -parser changes, it should be very easy to actually make it work. - - -Development -=========== - -There's a pretty good and extensive `development documentation -`_. - - -Testing -======= - -The test suite depends on ``tox`` and ``pytest``:: - - pip install tox pytest - -To run the tests for all supported Python versions:: - - tox - -If you want to test only a specific Python version (e.g. Python 2.7), it's as -easy as :: - - tox -e py27 - -Tests are also run automatically on `Travis CI -`_. - -For more detailed information visit the `testing documentation -`_ - - -Acknowledgements -================ - -- Takafumi Arakaki (@tkf) for creating a solid test environment and a lot of - other things. -- Danilo Bargen (@dbrgn) for general housekeeping and being a good friend :). -- Guido van Rossum (@gvanrossum) for creating the parser generator pgen2 - (originally used in lib2to3). - - - -.. _jedi-vim: https://github.com/davidhalter/jedi-vim -.. _youcompleteme: http://valloric.github.io/YouCompleteMe/ -.. _deoplete-jedi: https://github.com/zchee/deoplete-jedi -.. _Jedi.el: https://github.com/tkf/emacs-jedi -.. _company-mode: https://github.com/syohex/emacs-company-jedi -.. _elpy: https://github.com/jorgenschaefer/elpy -.. _anaconda-mode: https://github.com/proofit404/anaconda-mode -.. _ycmd: https://github.com/abingham/emacs-ycmd -.. _sublimejedi: https://github.com/srusskih/SublimeJEDI -.. _anaconda: https://github.com/DamnWidget/anaconda -.. _wdb: https://github.com/Kozea/wdb -.. _TextMate: https://github.com/lawrenceakka/python-jedi.tmbundle -.. _Kate: http://kate-editor.org -.. _Atom: https://atom.io/ -.. _autocomplete-python: https://atom.io/packages/autocomplete-python -.. _SourceLair: https://www.sourcelair.com -.. _GNOME Builder: https://wiki.gnome.org/Apps/Builder -.. _Visual Studio Code: https://code.visualstudio.com/ -.. _gedi: https://github.com/isamert/gedi -.. _Eric IDE: http://eric-ide.python-projects.org diff --git a/vim-plugins/bundle/jedi-vim/jedi/conftest.py b/vim-plugins/bundle/jedi-vim/jedi/conftest.py deleted file mode 100644 index 2567fcd..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/conftest.py +++ /dev/null @@ -1,72 +0,0 @@ -import tempfile -import shutil - -import pytest - -import jedi - -collect_ignore = ["setup.py"] - - -# The following hooks (pytest_configure, pytest_unconfigure) are used -# to modify `jedi.settings.cache_directory` because `clean_jedi_cache` -# has no effect during doctests. Without these hooks, doctests uses -# user's cache (e.g., ~/.cache/jedi/). We should remove this -# workaround once the problem is fixed in py.test. -# -# See: -# - https://github.com/davidhalter/jedi/pull/168 -# - https://bitbucket.org/hpk42/pytest/issue/275/ - -jedi_cache_directory_orig = None -jedi_cache_directory_temp = None - - -def pytest_addoption(parser): - parser.addoption("--jedi-debug", "-D", action='store_true', - help="Enables Jedi's debug output.") - - parser.addoption("--warning-is-error", action='store_true', - help="Warnings are treated as errors.") - - -def pytest_configure(config): - global jedi_cache_directory_orig, jedi_cache_directory_temp - jedi_cache_directory_orig = jedi.settings.cache_directory - jedi_cache_directory_temp = tempfile.mkdtemp(prefix='jedi-test-') - jedi.settings.cache_directory = jedi_cache_directory_temp - - if config.option.jedi_debug: - jedi.set_debug_function() - - if config.option.warning_is_error: - import warnings - warnings.simplefilter("error") - - -def pytest_unconfigure(config): - global jedi_cache_directory_orig, jedi_cache_directory_temp - jedi.settings.cache_directory = jedi_cache_directory_orig - shutil.rmtree(jedi_cache_directory_temp) - - -@pytest.fixture(scope='session') -def clean_jedi_cache(request): - """ - Set `jedi.settings.cache_directory` to a temporary directory during test. - - Note that you can't use built-in `tmpdir` and `monkeypatch` - fixture here because their scope is 'function', which is not used - in 'session' scope fixture. - - This fixture is activated in ../pytest.ini. - """ - from jedi import settings - old = settings.cache_directory - tmp = tempfile.mkdtemp(prefix='jedi-test-') - settings.cache_directory = tmp - - @request.addfinalizer - def restore(): - settings.cache_directory = old - shutil.rmtree(tmp) diff --git a/vim-plugins/bundle/jedi-vim/jedi/docs/Makefile b/vim-plugins/bundle/jedi-vim/jedi/docs/Makefile deleted file mode 100644 index 14cfdf4..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/docs/Makefile +++ /dev/null @@ -1,153 +0,0 @@ -# Makefile for Sphinx documentation -# - -# You can set these variables from the command line. -SPHINXOPTS = -SPHINXBUILD = sphinx-build -PAPER = -BUILDDIR = _build - -# Internal variables. -PAPEROPT_a4 = -D latex_paper_size=a4 -PAPEROPT_letter = -D latex_paper_size=letter -ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . -# the i18n builder cannot share the environment and doctrees with the others -I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . - -.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext - -help: - @echo "Please use \`make ' where is one of" - @echo " html to make standalone HTML files" - @echo " dirhtml to make HTML files named index.html in directories" - @echo " singlehtml to make a single large HTML file" - @echo " pickle to make pickle files" - @echo " json to make JSON files" - @echo " htmlhelp to make HTML files and a HTML help project" - @echo " qthelp to make HTML files and a qthelp project" - @echo " devhelp to make HTML files and a Devhelp project" - @echo " epub to make an epub" - @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" - @echo " latexpdf to make LaTeX files and run them through pdflatex" - @echo " text to make text files" - @echo " man to make manual pages" - @echo " texinfo to make Texinfo files" - @echo " info to make Texinfo files and run them through makeinfo" - @echo " gettext to make PO message catalogs" - @echo " changes to make an overview of all changed/added/deprecated items" - @echo " linkcheck to check all external links for integrity" - @echo " doctest to run all doctests embedded in the documentation (if enabled)" - -clean: - -rm -rf $(BUILDDIR)/* - -html: - $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html - @echo - @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." - -dirhtml: - $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml - @echo - @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." - -singlehtml: - $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml - @echo - @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." - -pickle: - $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle - @echo - @echo "Build finished; now you can process the pickle files." - -json: - $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json - @echo - @echo "Build finished; now you can process the JSON files." - -htmlhelp: - $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp - @echo - @echo "Build finished; now you can run HTML Help Workshop with the" \ - ".hhp project file in $(BUILDDIR)/htmlhelp." - -qthelp: - $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp - @echo - @echo "Build finished; now you can run "qcollectiongenerator" with the" \ - ".qhcp project file in $(BUILDDIR)/qthelp, like this:" - @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Jedi.qhcp" - @echo "To view the help file:" - @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Jedi.qhc" - -devhelp: - $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp - @echo - @echo "Build finished." - @echo "To view the help file:" - @echo "# mkdir -p $$HOME/.local/share/devhelp/Jedi" - @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Jedi" - @echo "# devhelp" - -epub: - $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub - @echo - @echo "Build finished. The epub file is in $(BUILDDIR)/epub." - -latex: - $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex - @echo - @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." - @echo "Run \`make' in that directory to run these through (pdf)latex" \ - "(use \`make latexpdf' here to do that automatically)." - -latexpdf: - $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex - @echo "Running LaTeX files through pdflatex..." - $(MAKE) -C $(BUILDDIR)/latex all-pdf - @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." - -text: - $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text - @echo - @echo "Build finished. The text files are in $(BUILDDIR)/text." - -man: - $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man - @echo - @echo "Build finished. The manual pages are in $(BUILDDIR)/man." - -texinfo: - $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo - @echo - @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." - @echo "Run \`make' in that directory to run these through makeinfo" \ - "(use \`make info' here to do that automatically)." - -info: - $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo - @echo "Running Texinfo files through makeinfo..." - make -C $(BUILDDIR)/texinfo info - @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." - -gettext: - $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale - @echo - @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." - -changes: - $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes - @echo - @echo "The overview file is in $(BUILDDIR)/changes." - -linkcheck: - $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck - @echo - @echo "Link check complete; look for any errors in the above output " \ - "or in $(BUILDDIR)/linkcheck/output.txt." - -doctest: - $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest - @echo "Testing of doctests in the sources finished, look at the " \ - "results in $(BUILDDIR)/doctest/output.txt." diff --git a/vim-plugins/bundle/jedi-vim/jedi/docs/_screenshots/screenshot_complete.png b/vim-plugins/bundle/jedi-vim/jedi/docs/_screenshots/screenshot_complete.png deleted file mode 100644 index 2bafad6..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/docs/_screenshots/screenshot_complete.png and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/docs/_screenshots/screenshot_function.png b/vim-plugins/bundle/jedi-vim/jedi/docs/_screenshots/screenshot_function.png deleted file mode 100644 index 6109703..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/docs/_screenshots/screenshot_function.png and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/docs/_screenshots/screenshot_pydoc.png b/vim-plugins/bundle/jedi-vim/jedi/docs/_screenshots/screenshot_pydoc.png deleted file mode 100644 index a399d5f..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/docs/_screenshots/screenshot_pydoc.png and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/docs/_static/logo-src.txt b/vim-plugins/bundle/jedi-vim/jedi/docs/_static/logo-src.txt deleted file mode 100644 index 59aa4f6..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/docs/_static/logo-src.txt +++ /dev/null @@ -1,3 +0,0 @@ -The source of the logo is a photoshop file hosted here: - -https://dl.dropboxusercontent.com/u/170011615/Jedi12_Logo.psd.xz diff --git a/vim-plugins/bundle/jedi-vim/jedi/docs/_static/logo.png b/vim-plugins/bundle/jedi-vim/jedi/docs/_static/logo.png deleted file mode 100644 index 9f3d244..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/docs/_static/logo.png and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/docs/_templates/ghbuttons.html b/vim-plugins/bundle/jedi-vim/jedi/docs/_templates/ghbuttons.html deleted file mode 100644 index badb06a..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/docs/_templates/ghbuttons.html +++ /dev/null @@ -1,4 +0,0 @@ -

Github

- -

diff --git a/vim-plugins/bundle/jedi-vim/jedi/docs/_templates/sidebarlogo.html b/vim-plugins/bundle/jedi-vim/jedi/docs/_templates/sidebarlogo.html deleted file mode 100644 index d9243c4..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/docs/_templates/sidebarlogo.html +++ /dev/null @@ -1,3 +0,0 @@ - diff --git a/vim-plugins/bundle/jedi-vim/jedi/docs/_themes/flask/LICENSE b/vim-plugins/bundle/jedi-vim/jedi/docs/_themes/flask/LICENSE deleted file mode 100644 index 8daab7e..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/docs/_themes/flask/LICENSE +++ /dev/null @@ -1,37 +0,0 @@ -Copyright (c) 2010 by Armin Ronacher. - -Some rights reserved. - -Redistribution and use in source and binary forms of the theme, with or -without modification, are permitted provided that the following conditions -are met: - -* Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - -* Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials provided - with the distribution. - -* The names of the contributors may not be used to endorse or - promote products derived from this software without specific - prior written permission. - -We kindly ask you to only use these themes in an unmodified manner just -for Flask and Flask-related products, not for unrelated projects. If you -like the visual style and want to use it for your own projects, please -consider making some larger changes to the themes (such as changing -font faces, sizes, colors or margins). - -THIS THEME IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS THEME, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. diff --git a/vim-plugins/bundle/jedi-vim/jedi/docs/_themes/flask/layout.html b/vim-plugins/bundle/jedi-vim/jedi/docs/_themes/flask/layout.html deleted file mode 100644 index e781a11..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/docs/_themes/flask/layout.html +++ /dev/null @@ -1,28 +0,0 @@ -{%- extends "basic/layout.html" %} -{%- block extrahead %} - {{ super() }} - {% if theme_touch_icon %} - - {% endif %} - - - Fork me on GitHub - -{% endblock %} -{%- block relbar2 %}{% endblock %} -{% block header %} - {{ super() }} - {% if pagename == 'index' %} -
- {% endif %} -{% endblock %} -{%- block footer %} - - {% if pagename == 'index' %} -
- {% endif %} -{%- endblock %} diff --git a/vim-plugins/bundle/jedi-vim/jedi/docs/_themes/flask/relations.html b/vim-plugins/bundle/jedi-vim/jedi/docs/_themes/flask/relations.html deleted file mode 100644 index 3bbcde8..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/docs/_themes/flask/relations.html +++ /dev/null @@ -1,19 +0,0 @@ -

Related Topics

- diff --git a/vim-plugins/bundle/jedi-vim/jedi/docs/_themes/flask/static/flasky.css_t b/vim-plugins/bundle/jedi-vim/jedi/docs/_themes/flask/static/flasky.css_t deleted file mode 100644 index 79ab478..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/docs/_themes/flask/static/flasky.css_t +++ /dev/null @@ -1,394 +0,0 @@ -/* - * flasky.css_t - * ~~~~~~~~~~~~ - * - * :copyright: Copyright 2010 by Armin Ronacher. - * :license: Flask Design License, see LICENSE for details. - */ - -{% set page_width = '940px' %} -{% set sidebar_width = '220px' %} - -@import url("basic.css"); - -/* -- page layout ----------------------------------------------------------- */ - -body { - font-family: 'Georgia', serif; - font-size: 17px; - background-color: white; - color: #000; - margin: 0; - padding: 0; -} - -div.document { - width: {{ page_width }}; - margin: 30px auto 0 auto; -} - -div.documentwrapper { - float: left; - width: 100%; -} - -div.bodywrapper { - margin: 0 0 0 {{ sidebar_width }}; -} - -div.sphinxsidebar { - width: {{ sidebar_width }}; -} - -hr { - border: 1px solid #B1B4B6; -} - -div.body { - background-color: #ffffff; - color: #3E4349; - padding: 0 30px 0 30px; -} - -img.floatingflask { - padding: 0 0 10px 10px; - float: right; -} - -div.footer { - width: {{ page_width }}; - margin: 20px auto 30px auto; - font-size: 14px; - color: #888; - text-align: right; -} - -div.footer a { - color: #888; -} - -div.related { - display: none; -} - -div.sphinxsidebar a { - color: #444; - text-decoration: none; - border-bottom: 1px dotted #999; -} - -div.sphinxsidebar a:hover { - border-bottom: 1px solid #999; -} - -div.sphinxsidebar { - font-size: 14px; - line-height: 1.5; -} - -div.sphinxsidebarwrapper { - padding: 18px 10px; -} - -div.sphinxsidebarwrapper p.logo { - padding: 0 0 20px 0; - margin: 0; - text-align: center; -} - -div.sphinxsidebar h3, -div.sphinxsidebar h4 { - font-family: 'Garamond', 'Georgia', serif; - color: #444; - font-size: 24px; - font-weight: normal; - margin: 0 0 5px 0; - padding: 0; -} - -div.sphinxsidebar h4 { - font-size: 20px; -} - -div.sphinxsidebar h3 a { - color: #444; -} - -div.sphinxsidebar p.logo a, -div.sphinxsidebar h3 a, -div.sphinxsidebar p.logo a:hover, -div.sphinxsidebar h3 a:hover { - border: none; -} - -div.sphinxsidebar p { - color: #555; - margin: 10px 0; -} - -div.sphinxsidebar ul { - margin: 10px 0; - padding: 0; - color: #000; -} - -div.sphinxsidebar input { - border: 1px solid #ccc; - font-family: 'Georgia', serif; - font-size: 1em; -} - -/* -- body styles ----------------------------------------------------------- */ - -a { - color: #004B6B; - text-decoration: underline; -} - -a:hover { - color: #6D4100; - text-decoration: underline; -} - -div.body h1, -div.body h2, -div.body h3, -div.body h4, -div.body h5, -div.body h6 { - font-family: 'Garamond', 'Georgia', serif; - font-weight: normal; - margin: 30px 0px 10px 0px; - padding: 0; -} - -{% if theme_index_logo %} -div.indexwrapper h1 { - text-indent: -999999px; - background: url({{ theme_index_logo }}) no-repeat center center; - height: {{ theme_index_logo_height }}; -} -{% endif %} - -div.body h1 { margin-top: 0; padding-top: 0; font-size: 240%; } -div.body h2 { font-size: 180%; } -div.body h3 { font-size: 150%; } -div.body h4 { font-size: 130%; } -div.body h5 { font-size: 100%; } -div.body h6 { font-size: 100%; } - -a.headerlink { - color: #ddd; - padding: 0 4px; - text-decoration: none; -} - -a.headerlink:hover { - color: #444; -} - -div.body p, div.body dd, div.body li { - line-height: 1.4em; -} - -div.admonition { - background: #fafafa; - margin: 20px -30px; - padding: 10px 30px; - border-top: 1px solid #ccc; - border-bottom: 1px solid #ccc; -} - -div.admonition tt.xref, div.admonition a tt { - border-bottom: 1px solid #fafafa; -} - -dd div.admonition { - margin-left: -60px; - padding-left: 60px; -} - -div.admonition p.admonition-title { - font-family: 'Garamond', 'Georgia', serif; - font-weight: normal; - font-size: 24px; - margin: 0 0 10px 0; - padding: 0; - line-height: 1; -} - -div.admonition p.last { - margin-bottom: 0; -} - -div.highlight { - background-color: white; -} - -dt:target, .highlight { - background: #FAF3E8; -} - -div.note { - background-color: #eee; - border: 1px solid #ccc; -} - -div.seealso { - background-color: #ffc; - border: 1px solid #ff6; -} - -div.topic { - background-color: #eee; -} - -p.admonition-title { - display: inline; -} - -p.admonition-title:after { - content: ":"; -} - -pre, tt { - font-family: 'Consolas', 'Menlo', 'Deja Vu Sans Mono', 'Bitstream Vera Sans Mono', monospace; - font-size: 0.9em; -} - -img.screenshot { -} - -tt.descname, tt.descclassname { - font-size: 0.95em; -} - -tt.descname { - padding-right: 0.08em; -} - -img.screenshot { - -moz-box-shadow: 2px 2px 4px #eee; - -webkit-box-shadow: 2px 2px 4px #eee; - box-shadow: 2px 2px 4px #eee; -} - -table.docutils { - border: 1px solid #888; - -moz-box-shadow: 2px 2px 4px #eee; - -webkit-box-shadow: 2px 2px 4px #eee; - box-shadow: 2px 2px 4px #eee; -} - -table.docutils td, table.docutils th { - border: 1px solid #888; - padding: 0.25em 0.7em; -} - -table.field-list, table.footnote { - border: none; - -moz-box-shadow: none; - -webkit-box-shadow: none; - box-shadow: none; -} - -table.footnote { - margin: 15px 0; - width: 100%; - border: 1px solid #eee; - background: #fdfdfd; - font-size: 0.9em; -} - -table.footnote + table.footnote { - margin-top: -15px; - border-top: none; -} - -table.field-list th { - padding: 0 0.8em 0 0; -} - -table.field-list td { - padding: 0; -} - -table.footnote td.label { - width: 0px; - padding: 0.3em 0 0.3em 0.5em; -} - -table.footnote td { - padding: 0.3em 0.5em; -} - -dl { - margin: 0; - padding: 0; -} - -dl dd { - margin-left: 30px; -} - -blockquote { - margin: 0 0 0 30px; - padding: 0; -} - -ul, ol { - margin: 10px 0 10px 30px; - padding: 0; -} - -pre { - background: #eee; - padding: 7px 30px; - margin: 15px -30px; - line-height: 1.3em; -} - -dl pre, blockquote pre, li pre { - margin-left: -60px; - padding-left: 60px; -} - -dl dl pre { - margin-left: -90px; - padding-left: 90px; -} - -tt { - background-color: #ecf0f3; - color: #222; - /* padding: 1px 2px; */ -} - -tt.xref, a tt { - background-color: #FBFBFB; - border-bottom: 1px solid white; -} - -a.reference { - text-decoration: none; - border-bottom: 1px dotted #004B6B; -} - -a.reference:hover { - border-bottom: 1px solid #6D4100; -} - -a.footnote-reference { - text-decoration: none; - font-size: 0.7em; - vertical-align: top; - border-bottom: 1px dotted #004B6B; -} - -a.footnote-reference:hover { - border-bottom: 1px solid #6D4100; -} - -a:hover tt { - background: #EEE; -} diff --git a/vim-plugins/bundle/jedi-vim/jedi/docs/_themes/flask/static/small_flask.css b/vim-plugins/bundle/jedi-vim/jedi/docs/_themes/flask/static/small_flask.css deleted file mode 100644 index 1c6df30..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/docs/_themes/flask/static/small_flask.css +++ /dev/null @@ -1,70 +0,0 @@ -/* - * small_flask.css_t - * ~~~~~~~~~~~~~~~~~ - * - * :copyright: Copyright 2010 by Armin Ronacher. - * :license: Flask Design License, see LICENSE for details. - */ - -body { - margin: 0; - padding: 20px 30px; -} - -div.documentwrapper { - float: none; - background: white; -} - -div.sphinxsidebar { - display: block; - float: none; - width: 102.5%; - margin: 50px -30px -20px -30px; - padding: 10px 20px; - background: #333; - color: white; -} - -div.sphinxsidebar h3, div.sphinxsidebar h4, div.sphinxsidebar p, -div.sphinxsidebar h3 a { - color: white; -} - -div.sphinxsidebar a { - color: #aaa; -} - -div.sphinxsidebar p.logo { - display: none; -} - -div.document { - width: 100%; - margin: 0; -} - -div.related { - display: block; - margin: 0; - padding: 10px 0 20px 0; -} - -div.related ul, -div.related ul li { - margin: 0; - padding: 0; -} - -div.footer { - display: none; -} - -div.bodywrapper { - margin: 0; -} - -div.body { - min-height: 0; - padding: 0; -} diff --git a/vim-plugins/bundle/jedi-vim/jedi/docs/_themes/flask/theme.conf b/vim-plugins/bundle/jedi-vim/jedi/docs/_themes/flask/theme.conf deleted file mode 100644 index 1d5657f..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/docs/_themes/flask/theme.conf +++ /dev/null @@ -1,9 +0,0 @@ -[theme] -inherit = basic -stylesheet = flasky.css -pygments_style = flask_theme_support.FlaskyStyle - -[options] -index_logo = -index_logo_height = 120px -touch_icon = diff --git a/vim-plugins/bundle/jedi-vim/jedi/docs/_themes/flask_theme_support.py b/vim-plugins/bundle/jedi-vim/jedi/docs/_themes/flask_theme_support.py deleted file mode 100644 index d3e33c0..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/docs/_themes/flask_theme_support.py +++ /dev/null @@ -1,125 +0,0 @@ -""" -Copyright (c) 2010 by Armin Ronacher. - -Some rights reserved. - -Redistribution and use in source and binary forms of the theme, with or -without modification, are permitted provided that the following conditions -are met: - -* Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - -* Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials provided - with the distribution. - -* The names of the contributors may not be used to endorse or - promote products derived from this software without specific - prior written permission. - -We kindly ask you to only use these themes in an unmodified manner just -for Flask and Flask-related products, not for unrelated projects. If you -like the visual style and want to use it for your own projects, please -consider making some larger changes to the themes (such as changing -font faces, sizes, colors or margins). - -THIS THEME IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS THEME, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. -""" -# flasky extensions. flasky pygments style based on tango style -from pygments.style import Style -from pygments.token import Keyword, Name, Comment, String, Error, \ - Number, Operator, Generic, Whitespace, Punctuation, Other, Literal - - -class FlaskyStyle(Style): - background_color = "#f8f8f8" - default_style = "" - - styles = { - # No corresponding class for the following: - #Text: "", # class: '' - Whitespace: "underline #f8f8f8", # class: 'w' - Error: "#a40000 border:#ef2929", # class: 'err' - Other: "#000000", # class 'x' - - Comment: "italic #8f5902", # class: 'c' - Comment.Preproc: "noitalic", # class: 'cp' - - Keyword: "bold #004461", # class: 'k' - Keyword.Constant: "bold #004461", # class: 'kc' - Keyword.Declaration: "bold #004461", # class: 'kd' - Keyword.Namespace: "bold #004461", # class: 'kn' - Keyword.Pseudo: "bold #004461", # class: 'kp' - Keyword.Reserved: "bold #004461", # class: 'kr' - Keyword.Type: "bold #004461", # class: 'kt' - - Operator: "#582800", # class: 'o' - Operator.Word: "bold #004461", # class: 'ow' - like keywords - - Punctuation: "bold #000000", # class: 'p' - - # because special names such as Name.Class, Name.Function, etc. - # are not recognized as such later in the parsing, we choose them - # to look the same as ordinary variables. - Name: "#000000", # class: 'n' - Name.Attribute: "#c4a000", # class: 'na' - to be revised - Name.Builtin: "#004461", # class: 'nb' - Name.Builtin.Pseudo: "#3465a4", # class: 'bp' - Name.Class: "#000000", # class: 'nc' - to be revised - Name.Constant: "#000000", # class: 'no' - to be revised - Name.Decorator: "#888", # class: 'nd' - to be revised - Name.Entity: "#ce5c00", # class: 'ni' - Name.Exception: "bold #cc0000", # class: 'ne' - Name.Function: "#000000", # class: 'nf' - Name.Property: "#000000", # class: 'py' - Name.Label: "#f57900", # class: 'nl' - Name.Namespace: "#000000", # class: 'nn' - to be revised - Name.Other: "#000000", # class: 'nx' - Name.Tag: "bold #004461", # class: 'nt' - like a keyword - Name.Variable: "#000000", # class: 'nv' - to be revised - Name.Variable.Class: "#000000", # class: 'vc' - to be revised - Name.Variable.Global: "#000000", # class: 'vg' - to be revised - Name.Variable.Instance: "#000000", # class: 'vi' - to be revised - - Number: "#990000", # class: 'm' - - Literal: "#000000", # class: 'l' - Literal.Date: "#000000", # class: 'ld' - - String: "#4e9a06", # class: 's' - String.Backtick: "#4e9a06", # class: 'sb' - String.Char: "#4e9a06", # class: 'sc' - String.Doc: "italic #8f5902", # class: 'sd' - like a comment - String.Double: "#4e9a06", # class: 's2' - String.Escape: "#4e9a06", # class: 'se' - String.Heredoc: "#4e9a06", # class: 'sh' - String.Interpol: "#4e9a06", # class: 'si' - String.Other: "#4e9a06", # class: 'sx' - String.Regex: "#4e9a06", # class: 'sr' - String.Single: "#4e9a06", # class: 's1' - String.Symbol: "#4e9a06", # class: 'ss' - - Generic: "#000000", # class: 'g' - Generic.Deleted: "#a40000", # class: 'gd' - Generic.Emph: "italic #000000", # class: 'ge' - Generic.Error: "#ef2929", # class: 'gr' - Generic.Heading: "bold #000080", # class: 'gh' - Generic.Inserted: "#00A000", # class: 'gi' - Generic.Output: "#888", # class: 'go' - Generic.Prompt: "#745334", # class: 'gp' - Generic.Strong: "bold #000000", # class: 'gs' - Generic.Subheading: "bold #800080", # class: 'gu' - Generic.Traceback: "bold #a40000", # class: 'gt' - } diff --git a/vim-plugins/bundle/jedi-vim/jedi/docs/conf.py b/vim-plugins/bundle/jedi-vim/jedi/docs/conf.py deleted file mode 100644 index 0e25a88..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/docs/conf.py +++ /dev/null @@ -1,291 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Jedi documentation build configuration file, created by -# sphinx-quickstart on Wed Dec 26 00:11:34 2012. -# -# This file is execfile()d with the current directory set to its containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import datetime - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath('..')) -sys.path.append(os.path.abspath('_themes')) - -# -- General configuration ----------------------------------------------------- - -# If your documentation needs a minimal Sphinx version, state it here. -#needs_sphinx = '1.0' - -# Add any Sphinx extension module names here, as strings. They can be extensions -# coming with Sphinx (named 'sphinx.ext.*') or your custom ones. -extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.todo', - 'sphinx.ext.intersphinx', 'sphinx.ext.inheritance_diagram'] - -# Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] - -# The suffix of source filenames. -source_suffix = '.rst' - -# The encoding of source files. -source_encoding = 'utf-8' - -# The master toctree document. -master_doc = 'index' - -# General information about the project. -project = u'Jedi' -copyright = u'2012 - {today.year}, Jedi contributors'.format(today=datetime.date.today()) - -import jedi -from jedi.utils import version_info - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The short X.Y version. -version = '.'.join(str(x) for x in version_info()[:2]) -# The full version, including alpha/beta/rc tags. -release = jedi.__version__ - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -#language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -#today = '' -# Else, today_fmt is used as the format for a strftime call. -#today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = [] - -# The reST default role (used for this markup: `text`) to use for all documents. -#default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -#add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -#add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -#show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = 'sphinx' - -# A list of ignored prefixes for module index sorting. -#modindex_common_prefix = [] - - -# -- Options for HTML output --------------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = 'flask' - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -#html_theme_options = {} - -# Add any paths that contain custom themes here, relative to this directory. -html_theme_path = ['_themes'] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -#html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -#html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -#html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -#html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ['_static'] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -#html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -#html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -html_sidebars = { - '**': [ - 'sidebarlogo.html', - 'localtoc.html', - #'relations.html', - 'ghbuttons.html', - #'sourcelink.html', - #'searchbox.html' - ] -} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -#html_additional_pages = {} - -# If false, no module index is generated. -#html_domain_indices = True - -# If false, no index is generated. -#html_use_index = True - -# If true, the index is split into individual pages for each letter. -#html_split_index = False - -# If true, links to the reST sources are added to the pages. -#html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -#html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -#html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -#html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -#html_file_suffix = None - -# Output file base name for HTML help builder. -htmlhelp_basename = 'Jedidoc' - -#html_style = 'default.css' # Force usage of default template on RTD - - -# -- Options for LaTeX output -------------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - #'papersize': 'letterpaper', - - # The font size ('10pt', '11pt' or '12pt'). - #'pointsize': '10pt', - - # Additional stuff for the LaTeX preamble. - #'preamble': '', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, author, documentclass [howto/manual]). -latex_documents = [ - ('index', 'Jedi.tex', u'Jedi Documentation', - u'Jedi contributors', 'manual'), -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -#latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -#latex_use_parts = False - -# If true, show page references after internal links. -#latex_show_pagerefs = False - -# If true, show URL addresses after external links. -#latex_show_urls = False - -# Documents to append as an appendix to all manuals. -#latex_appendices = [] - -# If false, no module index is generated. -#latex_domain_indices = True - - -# -- Options for manual page output -------------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ('index', 'jedi', u'Jedi Documentation', - [u'Jedi contributors'], 1) -] - -# If true, show URL addresses after external links. -#man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------------ - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ('index', 'Jedi', u'Jedi Documentation', - u'Jedi contributors', 'Jedi', 'Awesome Python autocompletion library.', - 'Miscellaneous'), -] - -# Documents to append as an appendix to all manuals. -#texinfo_appendices = [] - -# If false, no module index is generated. -#texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -#texinfo_show_urls = 'footnote' - -# -- Options for todo module --------------------------------------------------- - -todo_include_todos = False - -# -- Options for autodoc module ------------------------------------------------ - -autoclass_content = 'both' -autodoc_member_order = 'bysource' -autodoc_default_flags = [] -#autodoc_default_flags = ['members', 'undoc-members'] - - -# -- Options for intersphinx module -------------------------------------------- - -intersphinx_mapping = { - 'http://docs.python.org/': None, -} - - -def skip_deprecated(app, what, name, obj, skip, options): - """ - All attributes containing a deprecated note shouldn't be documented - anymore. This makes it even clearer that they are not supported anymore. - """ - doc = obj.__doc__ - return skip or doc and '.. deprecated::' in doc - - -def setup(app): - app.connect('autodoc-skip-member', skip_deprecated) diff --git a/vim-plugins/bundle/jedi-vim/jedi/docs/docs/development.rst b/vim-plugins/bundle/jedi-vim/jedi/docs/docs/development.rst deleted file mode 100644 index bb2c479..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/docs/docs/development.rst +++ /dev/null @@ -1,248 +0,0 @@ -.. include:: ../global.rst - -Jedi Development -================ - -.. currentmodule:: jedi - -.. note:: This documentation is for Jedi developers who want to improve Jedi - itself, but have no idea how Jedi works. If you want to use Jedi for - your IDE, look at the `plugin api `_. - - -Introduction ------------- - -This page tries to address the fundamental demand for documentation of the -|jedi| interals. Understanding a dynamic language is a complex task. Especially -because type inference in Python can be a very recursive task. Therefore |jedi| -couldn't get rid of complexity. I know that **simple is better than complex**, -but unfortunately it sometimes requires complex solutions to understand complex -systems. - -Since most of the Jedi internals have been written by me (David Halter), this -introduction will be written mostly by me, because no one else understands to -the same level how Jedi works. Actually this is also the reason for exactly this -part of the documentation. To make multiple people able to edit the Jedi core. - -In five chapters I'm trying to describe the internals of |jedi|: - -- :ref:`The Jedi Core ` -- :ref:`Core Extensions ` -- :ref:`Imports & Modules ` -- :ref:`Caching & Recursions ` -- :ref:`Helper modules ` - -.. note:: Testing is not documented here, you'll find that - `right here `_. - - -.. _core: - -The Jedi Core -------------- - -The core of Jedi consists of three parts: - -- :ref:`Parser ` -- :ref:`Python code evaluation ` -- :ref:`API ` - -Most people are probably interested in :ref:`code evaluation `, -because that's where all the magic happens. I need to introduce the :ref:`parser -` first, because :mod:`jedi.evaluate` uses it extensively. - -.. _parser: - -Parser (parser/__init__.py) -~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. automodule:: jedi.parser - -Parser Representation (parser/representation.py) -++++++++++++++++++++++++++++++++++++++++++++++++ - -.. automodule:: jedi.parser.representation - -Class inheritance diagram: - -.. inheritance-diagram:: - SubModule - Class - Function - Lambda - Flow - ForFlow - Import - Statement - Param - Call - Array - Name - ListComprehension - :parts: 1 - -.. _evaluate: - -Evaluation of python code (evaluate/__init__.py) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. automodule:: jedi.evaluate - -Evaluation Representation (evaluate/representation.py) -++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -.. automodule:: jedi.evaluate.representation - -.. inheritance-diagram:: - Executable - Instance - InstanceElement - Class - Function - FunctionExecution - :parts: 1 - - -.. _name_resolution: - -Name resolution (evaluate/finder.py) -++++++++++++++++++++++++++++++++++++ - -.. automodule:: jedi.evaluate.finder - - -.. _dev-api: - -API (api.py and api_classes.py) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The API has been designed to be as easy to use as possible. The API -documentation can be found `here `_. The API itself contains -little code that needs to be mentioned here. Generally I'm trying to be -conservative with the API. I'd rather not add new API features if they are not -necessary, because it's much harder to deprecate stuff than to add it later. - - -.. _core-extensions: - -Core Extensions ---------------- - -Core Extensions is a summary of the following topics: - -- :ref:`Iterables & Dynamic Arrays ` -- :ref:`Dynamic Parameters ` -- :ref:`Fast Parser ` -- :ref:`Docstrings ` -- :ref:`Refactoring ` - -These topics are very important to understand what Jedi additionally does, but -they could be removed from Jedi and Jedi would still work. But slower and -without some features. - -.. _iterables: - -Iterables & Dynamic Arrays (evaluate/iterable.py) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -To understand Python on a deeper level, |jedi| needs to understand some of the -dynamic features of Python, however this probably the most complicated part: - -.. automodule:: jedi.evaluate.iterable - - -.. _dynamic: - -Parameter completion (evaluate/dynamic.py) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. automodule:: jedi.evaluate.dynamic - - -.. _fast_parser: - -Fast Parser (parser/fast.py) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. automodule:: jedi.parser.fast - -.. _docstrings: - -Docstrings (evaluate/docstrings.py) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. automodule:: jedi.evaluate.docstrings - -.. _refactoring: - -Refactoring (evaluate/refactoring.py) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. automodule:: jedi.refactoring - - -.. _imports-modules: - -Imports & Modules -------------------- - - -- :ref:`Modules ` -- :ref:`Builtin Modules ` -- :ref:`Imports ` - - -.. _builtin: - -Compiled Modules (evaluate/compiled.py) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. automodule:: jedi.evaluate.compiled - - -.. _imports: - -Imports (evaluate/imports.py) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. automodule:: jedi.evaluate.imports - - -.. _caching-recursions: - -Caching & Recursions --------------------- - - -- :ref:`Caching ` -- :ref:`Recursions ` - -.. _cache: - -Caching (cache.py) -~~~~~~~~~~~~~~~~~~ - -.. automodule:: jedi.cache - -.. _recursion: - -Recursions (recursion.py) -~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. automodule:: jedi.evaluate.recursion - - -.. _dev-helpers: - -Helper Modules ---------------- - -Most other modules are not really central to how Jedi works. They all contain -relevant code, but you if you understand the modules above, you pretty much -understand Jedi. - -Python 2/3 compatibility (_compatibility.py) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. automodule:: jedi._compatibility diff --git a/vim-plugins/bundle/jedi-vim/jedi/docs/docs/features.rst b/vim-plugins/bundle/jedi-vim/jedi/docs/docs/features.rst deleted file mode 100644 index fd5b3ba..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/docs/docs/features.rst +++ /dev/null @@ -1,263 +0,0 @@ -.. include:: ../global.rst - -Features and Caveats -==================== - -Jedi obviously supports autocompletion. It's also possible to get it working in -(:ref:`your REPL (IPython, etc.) `). - -Static analysis is also possible by using the command ``jedi.names``. - -The Jedi Linter is currently in an alpha version and can be tested by calling -``python -m jedi linter``. - -Jedi would in theory support refactoring, but we have never publicized it, -because it's not production ready. If you're interested in helping out here, -let me know. With the latest parser changes, it should be very easy to actually -make it work. - - -General Features ----------------- - -- python 2.6+ and 3.3+ support -- ignores syntax errors and wrong indentation -- can deal with complex module / function / class structures -- virtualenv support -- can infer function arguments from sphinx, epydoc and basic numpydoc docstrings, - and PEP0484-style type hints (:ref:`type hinting `) - - -Supported Python Features -------------------------- - -|jedi| supports many of the widely used Python features: - -- builtins -- returns, yields, yield from -- tuple assignments / array indexing / dictionary indexing / star unpacking -- with-statement / exception handling -- ``*args`` / ``**kwargs`` -- decorators / lambdas / closures -- generators / iterators -- some descriptors: property / staticmethod / classmethod -- some magic methods: ``__call__``, ``__iter__``, ``__next__``, ``__get__``, - ``__getitem__``, ``__init__`` -- ``list.append()``, ``set.add()``, ``list.extend()``, etc. -- (nested) list comprehensions / ternary expressions -- relative imports -- ``getattr()`` / ``__getattr__`` / ``__getattribute__`` -- function annotations (py3k feature, are ignored right now, but being parsed. - I don't know what to do with them.) -- class decorators (py3k feature, are being ignored too, until I find a use - case, that doesn't work with |jedi|) -- simple/usual ``sys.path`` modifications -- ``isinstance`` checks for if/while/assert -- namespace packages (includes ``pkgutil`` and ``pkg_resources`` namespaces) -- Django / Flask / Buildout support - - -Unsupported Features --------------------- - -Not yet implemented: - -- manipulations of instances outside the instance variables without using - methods -- implicit namespace packages (Python 3.3+, `PEP 420 `_) - -Will probably never be implemented: - -- metaclasses (how could an auto-completion ever support this) -- ``setattr()``, ``__import__()`` -- writing to some dicts: ``globals()``, ``locals()``, ``object.__dict__`` -- evaluating ``if`` / ``while`` / ``del`` - - -Caveats -------- - -**Malformed Syntax** - -Syntax errors and other strange stuff may lead to undefined behaviour of the -completion. |jedi| is **NOT** a Python compiler, that tries to correct you. It -is a tool that wants to help you. But **YOU** have to know Python, not |jedi|. - -**Legacy Python 2 Features** - -This framework should work for both Python 2/3. However, some things were just -not as *pythonic* in Python 2 as things should be. To keep things simple, some -older Python 2 features have been left out: - -- Classes: Always Python 3 like, therefore all classes inherit from ``object``. -- Generators: No ``next()`` method. The ``__next__()`` method is used instead. - -**Slow Performance** - -Importing ``numpy`` can be quite slow sometimes, as well as loading the -builtins the first time. If you want to speed things up, you could write import -hooks in |jedi|, which preload stuff. However, once loaded, this is not a -problem anymore. The same is true for huge modules like ``PySide``, ``wx``, -etc. - -**Security** - -Security is an important issue for |jedi|. Therefore no Python code is -executed. As long as you write pure python, everything is evaluated -statically. But: If you use builtin modules (``c_builtin``) there is no other -option than to execute those modules. However: Execute isn't that critical (as -e.g. in pythoncomplete, which used to execute *every* import!), because it -means one import and no more. So basically the only dangerous thing is using -the import itself. If your ``c_builtin`` uses some strange initializations, it -might be dangerous. But if it does you're screwed anyways, because eventualy -you're going to execute your code, which executes the import. - - -Recipes -------- - -Here are some tips on how to use |jedi| efficiently. - - -.. _type-hinting: - -Type Hinting -~~~~~~~~~~~~ - -If |jedi| cannot detect the type of a function argument correctly (due to the -dynamic nature of Python), you can help it by hinting the type using -one of the following docstring/annotation syntax styles: - -**PEP-0484 style** - -https://www.python.org/dev/peps/pep-0484/ - -function annotations (python 3 only; python 2 function annotations with -comments in planned but not yet implemented) - -:: - - def myfunction(node: ProgramNode, foo: str) -> None: - """Do something with a ``node``. - - """ - node.| # complete here - - -assignment, for-loop and with-statement type hints (all python versions). -Note that the type hints must be on the same line as the statement - -:: - - x = foo() # type: int - x, y = 2, 3 # type: typing.Optional[int], typing.Union[int, str] # typing module is mostly supported - for key, value in foo.items(): # type: str, Employee # note that Employee must be in scope - pass - with foo() as f: # type: int - print(f + 3) - -Most of the features in PEP-0484 are supported including the typing module -(for python < 3.5 you have to do ``pip install typing`` to use these), -and forward references. - -Things that are missing (and this is not an exhaustive list; some of these -are planned, others might be hard to implement and provide little worth): - -- annotating functions with comments: https://www.python.org/dev/peps/pep-0484/#suggested-syntax-for-python-2-7-and-straddling-code -- understanding ``typing.cast()`` -- stub files: https://www.python.org/dev/peps/pep-0484/#stub-files -- ``typing.Callable`` -- ``typing.TypeVar`` -- User defined generic types: https://www.python.org/dev/peps/pep-0484/#user-defined-generic-types - -**Sphinx style** - -http://sphinx-doc.org/domains.html#info-field-lists - -:: - - def myfunction(node, foo): - """Do something with a ``node``. - - :type node: ProgramNode - :param str foo: foo parameter description - - """ - node.| # complete here - -**Epydoc** - -http://epydoc.sourceforge.net/manual-fields.html - -:: - - def myfunction(node): - """Do something with a ``node``. - - @type node: ProgramNode - - """ - node.| # complete here - -**Numpydoc** - -https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt - -In order to support the numpydoc format, you need to install the `numpydoc -`__ package. - -:: - - def foo(var1, var2, long_var_name='hi'): - r"""A one-line summary that does not use variable names or the - function name. - - ... - - Parameters - ---------- - var1 : array_like - Array_like means all those objects -- lists, nested lists, - etc. -- that can be converted to an array. We can also - refer to variables like `var1`. - var2 : int - The type above can either refer to an actual Python type - (e.g. ``int``), or describe the type of the variable in more - detail, e.g. ``(N,) ndarray`` or ``array_like``. - long_variable_name : {'hi', 'ho'}, optional - Choices in brackets, default first when optional. - - ... - - """ - var2.| # complete here - -A little history ----------------- - -The Star Wars Jedi are awesome. My Jedi software tries to imitate a little bit -of the precognition the Jedi have. There's even an awesome `scene -`_ of Monty Python Jedis :-). - -But actually the name hasn't so much to do with Star Wars. It's part of my -second name. - -After I explained Guido van Rossum, how some parts of my auto-completion work, -he said (we drank a beer or two): - - *"Oh, that worries me..."* - -When it's finished, I hope he'll like it :-) - -I actually started Jedi, because there were no good solutions available for VIM. -Most auto-completions just didn't work well. The only good solution was PyCharm. -But I like my good old VIM. Rope was never really intended to be an -auto-completion (and also I really hate project folders for my Python scripts). -It's more of a refactoring suite. So I decided to do my own version of a -completion, which would execute non-dangerous code. But I soon realized, that -this wouldn't work. So I built an extremely recursive thing which understands -many of Python's key features. - -By the way, I really tried to program it as understandable as possible. But I -think understanding it might need quite some time, because of its recursive -nature. diff --git a/vim-plugins/bundle/jedi-vim/jedi/docs/docs/installation.rst b/vim-plugins/bundle/jedi-vim/jedi/docs/docs/installation.rst deleted file mode 100644 index c6acbe9..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/docs/docs/installation.rst +++ /dev/null @@ -1,83 +0,0 @@ -.. include:: ../global.rst - -Installation and Configuration -============================== - -You can either include |jedi| as a submodule in your text editor plugin (like -jedi-vim_ does by default), or you can install it systemwide. - -.. note:: This just installs the |jedi| library, not the :ref:`editor plugins - `. For information about how to make it work with your - editor, refer to the corresponding documentation. - - -The preferred way ------------------ - -On any system you can install |jedi| directly from the Python package index -using pip:: - - sudo pip install jedi - -If you want to install the current development version (master branch):: - - sudo pip install -e git://github.com/davidhalter/jedi.git#egg=jedi - - -System-wide installation via a package manager ----------------------------------------------- - -Arch Linux -~~~~~~~~~~ - -You can install |jedi| directly from official Arch Linux packages: - -- `python-jedi `__ - (Python 3) -- `python2-jedi `__ - (Python 2) - -The specified Python version just refers to the *runtime environment* for -|jedi|. Use the Python 2 version if you're running vim (or whatever editor you -use) under Python 2. Otherwise, use the Python 3 version. But whatever version -you choose, both are able to complete both Python 2 and 3 *code*. - -(There is also a packaged version of the vim plugin available: `vim-jedi at -Arch Linux`__.) - -Debian -~~~~~~ - -Debian packages are available in the `unstable repository -`__. - -Others -~~~~~~ - -We are in the discussion of adding |jedi| to the Fedora repositories. - - -Manual installation from a downloaded package ---------------------------------------------- - -If you prefer not to use an automated package installer, you can `download -`__ a current copy of -|jedi| and install it manually. - -To install it, navigate to the directory containing `setup.py` on your console -and type:: - - sudo python setup.py install - - -Inclusion as a submodule ------------------------- - -If you use an editor plugin like jedi-vim_, you can simply include |jedi| as a -git submodule of the plugin directory. Vim plugin managers like Vundle_ or -Pathogen_ make it very easy to keep submodules up to date. - - -.. _jedi-vim: https://github.com/davidhalter/jedi-vim -.. _vundle: https://github.com/gmarik/vundle -.. _pathogen: https://github.com/tpope/vim-pathogen diff --git a/vim-plugins/bundle/jedi-vim/jedi/docs/docs/plugin-api-classes.rst b/vim-plugins/bundle/jedi-vim/jedi/docs/docs/plugin-api-classes.rst deleted file mode 100644 index 74eb28b..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/docs/docs/plugin-api-classes.rst +++ /dev/null @@ -1,10 +0,0 @@ -.. include:: ../global.rst - -.. _plugin-api-classes: - -API Return Classes ------------------- - -.. automodule:: jedi.api.classes - :members: - :undoc-members: diff --git a/vim-plugins/bundle/jedi-vim/jedi/docs/docs/plugin-api.rst b/vim-plugins/bundle/jedi-vim/jedi/docs/docs/plugin-api.rst deleted file mode 100644 index 93b081e..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/docs/docs/plugin-api.rst +++ /dev/null @@ -1,100 +0,0 @@ -.. include:: ../global.rst - -The Plugin API -============== - -.. currentmodule:: jedi - -Note: This documentation is for Plugin developers, who want to improve their -editors/IDE autocompletion - -If you want to use |jedi|, you first need to ``import jedi``. You then have -direct access to the :class:`.Script`. You can then call the functions -documented here. These functions return :ref:`API classes -`. - - -Deprecations ------------- - -The deprecation process is as follows: - -1. A deprecation is announced in the next major/minor release. -2. We wait either at least a year & at least two minor releases until we remove - the deprecated functionality. - - -API documentation ------------------ - -API Interface -~~~~~~~~~~~~~ - -.. automodule:: jedi.api - :members: - :undoc-members: - - -Examples --------- - -Completions: - -.. sourcecode:: python - - >>> import jedi - >>> source = '''import json; json.l''' - >>> script = jedi.Script(source, 1, 19, '') - >>> script - - >>> completions = script.completions() - >>> completions - [, ] - >>> completions[1] - - >>> completions[1].complete - 'oads' - >>> completions[1].name - 'loads' - -Definitions / Goto: - -.. sourcecode:: python - - >>> import jedi - >>> source = '''def my_func(): - ... print 'called' - ... - ... alias = my_func - ... my_list = [1, None, alias] - ... inception = my_list[2] - ... - ... inception()''' - >>> script = jedi.Script(source, 8, 1, '') - >>> - >>> script.goto_assignments() - [] - >>> - >>> script.goto_definitions() - [] - -Related names: - -.. sourcecode:: python - - >>> import jedi - >>> source = '''x = 3 - ... if 1 == 2: - ... x = 4 - ... else: - ... del x''' - >>> script = jedi.Script(source, 5, 8, '') - >>> rns = script.related_names() - >>> rns - [, ] - >>> rns[0].start_pos - (3, 4) - >>> rns[0].is_keyword - False - >>> rns[0].text - 'x' diff --git a/vim-plugins/bundle/jedi-vim/jedi/docs/docs/settings.rst b/vim-plugins/bundle/jedi-vim/jedi/docs/docs/settings.rst deleted file mode 100644 index 640a110..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/docs/docs/settings.rst +++ /dev/null @@ -1,6 +0,0 @@ -.. include:: ../global.rst - -Settings -======== - -.. automodule:: jedi.settings diff --git a/vim-plugins/bundle/jedi-vim/jedi/docs/docs/static_analsysis.rst b/vim-plugins/bundle/jedi-vim/jedi/docs/docs/static_analsysis.rst deleted file mode 100644 index 7ad03c7..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/docs/docs/static_analsysis.rst +++ /dev/null @@ -1,106 +0,0 @@ - -This file is the start of the documentation of how static analysis works. - -Below is a list of parser names that are used within nodes_to_execute. - ------------- cared for: -global_stmt -exec_stmt # no priority -assert_stmt -if_stmt -while_stmt -for_stmt -try_stmt -(except_clause) -with_stmt -(with_item) -(with_var) -print_stmt -del_stmt -return_stmt -raise_stmt -yield_expr -file_input -funcdef -param -old_lambdef -lambdef -import_name -import_from -(import_as_name) -(dotted_as_name) -(import_as_names) -(dotted_as_names) -(dotted_name) -classdef -comp_for -(comp_if) ? -decorator - ------------ add basic -test -or_test -and_test -not_test -expr -xor_expr -and_expr -shift_expr -arith_expr -term -factor -power -atom -comparison -expr_stmt -testlist -testlist1 -testlist_safe - ------------ special care: -# mostly depends on how we handle the other ones. -testlist_star_expr # should probably just work with expr_stmt -star_expr -exprlist # just ignore? then names are just resolved. Strange anyway, bc expr is not really allowed in the list, typically. - ------------ ignore: -suite -subscriptlist -subscript -simple_stmt -?? sliceop # can probably just be added. -testlist_comp # prob ignore and care about it with atom. -dictorsetmaker -trailer -decorators -decorated -# always execute function arguments? -> no problem with stars. -# Also arglist and argument are different in different grammars. -arglist -argument - - ------------ remove: -tname # only exists in current Jedi parser. REMOVE! -tfpdef # python 2: tuple assignment; python 3: annotation -vfpdef # reduced in python 3 and therefore not existing. -tfplist # not in 3 -vfplist # not in 3 - ---------- not existing with parser reductions. -small_stmt -import_stmt -flow_stmt -compound_stmt -stmt -pass_stmt -break_stmt -continue_stmt -comp_op -augassign -old_test -typedargslist # afaik becomes [param] -varargslist # dito -vname -comp_iter -test_nocond diff --git a/vim-plugins/bundle/jedi-vim/jedi/docs/docs/testing.rst b/vim-plugins/bundle/jedi-vim/jedi/docs/docs/testing.rst deleted file mode 100644 index 0c666a1..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/docs/docs/testing.rst +++ /dev/null @@ -1,40 +0,0 @@ -.. include:: ../global.rst - -Jedi Testing -============ - -The test suite depends on ``tox`` and ``pytest``:: - - pip install tox pytest - -To run the tests for all supported Python versions:: - - tox - -If you want to test only a specific Python version (e.g. Python 2.7), it's as -easy as:: - - tox -e py27 - -Tests are also run automatically on `Travis CI -`_. - -You want to add a test for |jedi|? Great! We love that. Normally you should -write your tests as :ref:`Blackbox Tests `. Most tests would -fit right in there. - -For specific API testing we're using simple unit tests, with a focus on a -simple and readable testing structure. - -.. _blackbox: - -Blackbox Tests (run.py) -~~~~~~~~~~~~~~~~~~~~~~~ - -.. automodule:: test.run - -Refactoring Tests (refactor.py) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. automodule:: test.refactor - diff --git a/vim-plugins/bundle/jedi-vim/jedi/docs/docs/usage.rst b/vim-plugins/bundle/jedi-vim/jedi/docs/docs/usage.rst deleted file mode 100644 index 82e1040..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/docs/docs/usage.rst +++ /dev/null @@ -1,119 +0,0 @@ -.. include:: ../global.rst - -End User Usage -============== - -If you are a not an IDE Developer, the odds are that you just want to use -|jedi| as a browser plugin or in the shell. Yes that's :ref:`also possible -`! - -|jedi| is relatively young and can be used in a variety of Plugins and -Software. If your Editor/IDE is not among them, recommend |jedi| to your IDE -developers. - - -.. _editor-plugins: - -Editor Plugins --------------- - -Vim: - -- jedi-vim_ -- YouCompleteMe_ -- deoplete-jedi_ - -Emacs: - -- Jedi.el_ -- elpy_ -- anaconda-mode_ - -Sublime Text 2/3: - -- SublimeJEDI_ (ST2 & ST3) -- anaconda_ (only ST3) - -SynWrite: - -- SynJedi_ - -TextMate: - -- Textmate_ (Not sure if it's actually working) - -Kate: - -- Kate_ version 4.13+ `supports it natively - `__, - you have to enable it, though. - -Visual Studio Code: - -- `Python Extension`_ - -Atom: - -- autocomplete-python_ - -SourceLair: - -- SourceLair_ - -GNOME Builder: - -- `GNOME Builder`_ `supports it natively - `__, - and is enabled by default. - -Gedit: - -- gedi_ - -Eric IDE: - -- `Eric IDE`_ (Available as a plugin) - -Web Debugger: - -- wdb_ - -and many more! - -.. _repl-completion: - -Tab completion in the Python Shell ----------------------------------- - -There are two different options how you can use Jedi autocompletion in -your Python interpreter. One with your custom ``$HOME/.pythonrc.py`` file -and one that uses ``PYTHONSTARTUP``. - -Using ``PYTHONSTARTUP`` -~~~~~~~~~~~~~~~~~~~~~~~ - -.. automodule:: jedi.replstartup - -Using a custom ``$HOME/.pythonrc.py`` -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. autofunction:: jedi.utils.setup_readline - -.. _jedi-vim: https://github.com/davidhalter/jedi-vim -.. _youcompleteme: http://valloric.github.io/YouCompleteMe/ -.. _deoplete-jedi: https://github.com/zchee/deoplete-jedi -.. _Jedi.el: https://github.com/tkf/emacs-jedi -.. _elpy: https://github.com/jorgenschaefer/elpy -.. _anaconda-mode: https://github.com/proofit404/anaconda-mode -.. _sublimejedi: https://github.com/srusskih/SublimeJEDI -.. _anaconda: https://github.com/DamnWidget/anaconda -.. _SynJedi: http://uvviewsoft.com/synjedi/ -.. _wdb: https://github.com/Kozea/wdb -.. _TextMate: https://github.com/lawrenceakka/python-jedi.tmbundle -.. _kate: http://kate-editor.org/ -.. _autocomplete-python: https://atom.io/packages/autocomplete-python -.. _SourceLair: https://www.sourcelair.com -.. _GNOME Builder: https://wiki.gnome.org/Apps/Builder/ -.. _gedi: https://github.com/isamert/gedi -.. _Eric IDE: http://eric-ide.python-projects.org -.. _Python Extension: https://marketplace.visualstudio.com/items?itemName=donjayamanne.python diff --git a/vim-plugins/bundle/jedi-vim/jedi/docs/global.rst b/vim-plugins/bundle/jedi-vim/jedi/docs/global.rst deleted file mode 100644 index 0279842..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/docs/global.rst +++ /dev/null @@ -1,3 +0,0 @@ -:orphan: - -.. |jedi| replace:: *Jedi* diff --git a/vim-plugins/bundle/jedi-vim/jedi/docs/index.rst b/vim-plugins/bundle/jedi-vim/jedi/docs/index.rst deleted file mode 100644 index 19c0706..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/docs/index.rst +++ /dev/null @@ -1,40 +0,0 @@ -.. include global.rst - -Jedi - an awesome autocompletion/static analysis library for Python -=================================================================== - -Release v\ |release|. (:doc:`Installation `) - -.. automodule:: jedi - -Autocompletion can look like this (e.g. VIM plugin): - -.. figure:: _screenshots/screenshot_complete.png - - -.. _toc: - -Docs ----- - -.. toctree:: - :maxdepth: 2 - - docs/usage - docs/installation - docs/features - docs/plugin-api - docs/plugin-api-classes - docs/settings - docs/development - docs/testing - - -.. _resources: - -Resources ---------- - -- `Source Code on Github `_ -- `Travis Testing `_ -- `Python Package Index `_ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/__init__.py b/vim-plugins/bundle/jedi-vim/jedi/jedi/__init__.py deleted file mode 100644 index c278276..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/__init__.py +++ /dev/null @@ -1,43 +0,0 @@ -""" -Jedi is a static analysis tool for Python that can be used in IDEs/editors. Its -historic focus is autocompletion, but does static analysis for now as well. -Jedi is fast and is very well tested. It understands Python on a deeper level -than all other static analysis frameworks for Python. - -Jedi has support for two different goto functions. It's possible to search for -related names and to list all names in a Python file and infer them. Jedi -understands docstrings and you can use Jedi autocompletion in your REPL as -well. - -Jedi uses a very simple API to connect with IDE's. There's a reference -implementation as a `VIM-Plugin `_, -which uses Jedi's autocompletion. We encourage you to use Jedi in your IDEs. -It's really easy. - -To give you a simple example how you can use the Jedi library, here is an -example for the autocompletion feature: - ->>> import jedi ->>> source = ''' -... import datetime -... datetime.da''' ->>> script = jedi.Script(source, 3, len('datetime.da'), 'example.py') ->>> script - ->>> completions = script.completions() ->>> completions #doctest: +ELLIPSIS -[, , ...] ->>> print(completions[0].complete) -te ->>> print(completions[0].name) -date - -As you see Jedi is pretty simple and allows you to concentrate on writing a -good text editor, while still having very good IDE features for Python. -""" - -__version__ = '0.10.0' - -from jedi.api import Script, Interpreter, NotFoundError, set_debug_function -from jedi.api import preload_module, defined_names, names -from jedi import settings diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/__main__.py b/vim-plugins/bundle/jedi-vim/jedi/jedi/__main__.py deleted file mode 100644 index f2ee047..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/__main__.py +++ /dev/null @@ -1,48 +0,0 @@ -import sys -from os.path import join, dirname, abspath, isdir - - -def _start_linter(): - """ - This is a pre-alpha API. You're not supposed to use it at all, except for - testing. It will very likely change. - """ - import jedi - - if '--debug' in sys.argv: - jedi.set_debug_function() - - for path in sys.argv[2:]: - if path.startswith('--'): - continue - if isdir(path): - import fnmatch - import os - - paths = [] - for root, dirnames, filenames in os.walk(path): - for filename in fnmatch.filter(filenames, '*.py'): - paths.append(os.path.join(root, filename)) - else: - paths = [path] - - try: - for path in paths: - for error in jedi.Script(path=path)._analysis(): - print(error) - except Exception: - if '--pdb' in sys.argv: - import traceback - traceback.print_exc() - import pdb - pdb.post_mortem() - else: - raise - - -if len(sys.argv) == 2 and sys.argv[1] == 'repl': - # don't want to use __main__ only for repl yet, maybe we want to use it for - # something else. So just use the keyword ``repl`` for now. - print(join(dirname(abspath(__file__)), 'api', 'replstartup.py')) -elif len(sys.argv) > 1 and sys.argv[1] == 'linter': - _start_linter() diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/__pycache__/__init__.cpython-35.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/__pycache__/__init__.cpython-35.pyc deleted file mode 100644 index e36f041..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/__pycache__/__init__.cpython-35.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/__pycache__/__init__.cpython-36.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/__pycache__/__init__.cpython-36.pyc deleted file mode 100644 index a55b3a4..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/__pycache__/__init__.cpython-36.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/__pycache__/_compatibility.cpython-35.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/__pycache__/_compatibility.cpython-35.pyc deleted file mode 100644 index 5c1c895..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/__pycache__/_compatibility.cpython-35.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/__pycache__/_compatibility.cpython-36.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/__pycache__/_compatibility.cpython-36.pyc deleted file mode 100644 index 8fd0c84..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/__pycache__/_compatibility.cpython-36.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/__pycache__/cache.cpython-35.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/__pycache__/cache.cpython-35.pyc deleted file mode 100644 index 6b893df..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/__pycache__/cache.cpython-35.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/__pycache__/cache.cpython-36.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/__pycache__/cache.cpython-36.pyc deleted file mode 100644 index c38f739..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/__pycache__/cache.cpython-36.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/__pycache__/common.cpython-35.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/__pycache__/common.cpython-35.pyc deleted file mode 100644 index e84d7d8..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/__pycache__/common.cpython-35.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/__pycache__/common.cpython-36.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/__pycache__/common.cpython-36.pyc deleted file mode 100644 index 9494c98..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/__pycache__/common.cpython-36.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/__pycache__/debug.cpython-35.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/__pycache__/debug.cpython-35.pyc deleted file mode 100644 index f47f611..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/__pycache__/debug.cpython-35.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/__pycache__/debug.cpython-36.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/__pycache__/debug.cpython-36.pyc deleted file mode 100644 index ec6d4d4..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/__pycache__/debug.cpython-36.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/__pycache__/settings.cpython-35.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/__pycache__/settings.cpython-35.pyc deleted file mode 100644 index a95e9c4..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/__pycache__/settings.cpython-35.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/__pycache__/settings.cpython-36.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/__pycache__/settings.cpython-36.pyc deleted file mode 100644 index 01c8f27..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/__pycache__/settings.cpython-36.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/__pycache__/utils.cpython-35.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/__pycache__/utils.cpython-35.pyc deleted file mode 100644 index 5596853..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/__pycache__/utils.cpython-35.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/__pycache__/utils.cpython-36.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/__pycache__/utils.cpython-36.pyc deleted file mode 100644 index 72fffe2..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/__pycache__/utils.cpython-36.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/_compatibility.py b/vim-plugins/bundle/jedi-vim/jedi/jedi/_compatibility.py deleted file mode 100644 index 3c14b6f..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/_compatibility.py +++ /dev/null @@ -1,263 +0,0 @@ -""" -To ensure compatibility from Python ``2.6`` - ``3.3``, a module has been -created. Clearly there is huge need to use conforming syntax. -""" -import sys -import imp -import os -import re -import pkgutil -try: - import importlib -except ImportError: - pass - -is_py3 = sys.version_info[0] >= 3 -is_py33 = is_py3 and sys.version_info.minor >= 3 -is_py34 = is_py3 and sys.version_info.minor >= 4 -is_py35 = is_py3 and sys.version_info.minor >= 5 -is_py26 = not is_py3 and sys.version_info[1] < 7 - - -class DummyFile(object): - def __init__(self, loader, string): - self.loader = loader - self.string = string - - def read(self): - return self.loader.get_source(self.string) - - def close(self): - del self.loader - - -def find_module_py33(string, path=None): - loader = importlib.machinery.PathFinder.find_module(string, path) - - if loader is None and path is None: # Fallback to find builtins - try: - loader = importlib.find_loader(string) - except ValueError as e: - # See #491. Importlib might raise a ValueError, to avoid this, we - # just raise an ImportError to fix the issue. - raise ImportError("Originally " + repr(e)) - - if loader is None: - raise ImportError("Couldn't find a loader for {0}".format(string)) - - try: - is_package = loader.is_package(string) - if is_package: - if hasattr(loader, 'path'): - module_path = os.path.dirname(loader.path) - else: - # At least zipimporter does not have path attribute - module_path = os.path.dirname(loader.get_filename(string)) - if hasattr(loader, 'archive'): - module_file = DummyFile(loader, string) - else: - module_file = None - else: - module_path = loader.get_filename(string) - module_file = DummyFile(loader, string) - except AttributeError: - # ExtensionLoader has not attribute get_filename, instead it has a - # path attribute that we can use to retrieve the module path - try: - module_path = loader.path - module_file = DummyFile(loader, string) - except AttributeError: - module_path = string - module_file = None - finally: - is_package = False - - if hasattr(loader, 'archive'): - module_path = loader.archive - - return module_file, module_path, is_package - - -def find_module_pre_py33(string, path=None): - try: - module_file, module_path, description = imp.find_module(string, path) - module_type = description[2] - return module_file, module_path, module_type is imp.PKG_DIRECTORY - except ImportError: - pass - - if path is None: - path = sys.path - for item in path: - loader = pkgutil.get_importer(item) - if loader: - try: - loader = loader.find_module(string) - if loader: - is_package = loader.is_package(string) - is_archive = hasattr(loader, 'archive') - try: - module_path = loader.get_filename(string) - except AttributeError: - # fallback for py26 - try: - module_path = loader._get_filename(string) - except AttributeError: - continue - if is_package: - module_path = os.path.dirname(module_path) - if is_archive: - module_path = loader.archive - file = None - if not is_package or is_archive: - file = DummyFile(loader, string) - return (file, module_path, is_package) - except ImportError: - pass - raise ImportError("No module named {0}".format(string)) - - -find_module = find_module_py33 if is_py33 else find_module_pre_py33 -find_module.__doc__ = """ -Provides information about a module. - -This function isolates the differences in importing libraries introduced with -python 3.3 on; it gets a module name and optionally a path. It will return a -tuple containin an open file for the module (if not builtin), the filename -or the name of the module if it is a builtin one and a boolean indicating -if the module is contained in a package. -""" - - -# unicode function -try: - unicode = unicode -except NameError: - unicode = str - -if is_py3: - u = lambda s: s -else: - u = lambda s: s.decode('utf-8') - -u.__doc__ = """ -Decode a raw string into unicode object. Do nothing in Python 3. -""" - -# exec function -if is_py3: - def exec_function(source, global_map): - exec(source, global_map) -else: - eval(compile("""def exec_function(source, global_map): - exec source in global_map """, 'blub', 'exec')) - -# re-raise function -if is_py3: - def reraise(exception, traceback): - raise exception.with_traceback(traceback) -else: - eval(compile(""" -def reraise(exception, traceback): - raise exception, None, traceback -""", 'blub', 'exec')) - -reraise.__doc__ = """ -Re-raise `exception` with a `traceback` object. - -Usage:: - - reraise(Exception, sys.exc_info()[2]) - -""" - -class Python3Method(object): - def __init__(self, func): - self.func = func - - def __get__(self, obj, objtype): - if obj is None: - return lambda *args, **kwargs: self.func(*args, **kwargs) - else: - return lambda *args, **kwargs: self.func(obj, *args, **kwargs) - - -def use_metaclass(meta, *bases): - """ Create a class with a metaclass. """ - if not bases: - bases = (object,) - return meta("HackClass", bases, {}) - - -try: - encoding = sys.stdout.encoding - if encoding is None: - encoding = 'utf-8' -except AttributeError: - encoding = 'ascii' - - -def u(string): - """Cast to unicode DAMMIT! - Written because Python2 repr always implicitly casts to a string, so we - have to cast back to a unicode (and we now that we always deal with valid - unicode, because we check that in the beginning). - """ - if is_py3: - return str(string) - elif not isinstance(string, unicode): - return unicode(str(string), 'UTF-8') - return string - -try: - import builtins # module name in python 3 -except ImportError: - import __builtin__ as builtins - - -import ast - - -def literal_eval(string): - # py3.0, py3.1 and py32 don't support unicode literals. Support those, I - # don't want to write two versions of the tokenizer. - if is_py3 and sys.version_info.minor < 3: - if re.match('[uU][\'"]', string): - string = string[1:] - return ast.literal_eval(string) - - -try: - from itertools import zip_longest -except ImportError: - from itertools import izip_longest as zip_longest # Python 2 - - -def no_unicode_pprint(dct): - """ - Python 2/3 dict __repr__ may be different, because of unicode differens - (with or without a `u` prefix). Normally in doctests we could use `pprint` - to sort dicts and check for equality, but here we have to write a separate - function to do that. - """ - import pprint - s = pprint.pformat(dct) - print(re.sub("u'", "'", s)) - - -def utf8_repr(func): - """ - ``__repr__`` methods in Python 2 don't allow unicode objects to be - returned. Therefore cast them to utf-8 bytes in this decorator. - """ - def wrapper(self): - result = func(self) - if isinstance(result, unicode): - return result.encode('utf-8') - else: - return result - - if is_py3: - return func - else: - return wrapper diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/api/__init__.py b/vim-plugins/bundle/jedi-vim/jedi/jedi/api/__init__.py deleted file mode 100644 index d443910..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/api/__init__.py +++ /dev/null @@ -1,463 +0,0 @@ -""" -The API basically only provides one class. You can create a :class:`Script` and -use its methods. - -Additionally you can add a debug function with :func:`set_debug_function`. -Alternatively, if you don't need a custom function and are happy with printing -debug messages to stdout, simply call :func:`set_debug_function` without -arguments. - -.. warning:: Please, note that Jedi is **not thread safe**. -""" -import os -import warnings -import sys - -from jedi._compatibility import unicode -from jedi.parser import load_grammar -from jedi.parser import tree -from jedi.parser.fast import FastParser -from jedi.parser.utils import save_parser -from jedi import debug -from jedi import settings -from jedi import common -from jedi import cache -from jedi.api import classes -from jedi.api import interpreter -from jedi.api import usages -from jedi.api import helpers -from jedi.api.completion import Completion -from jedi.evaluate import Evaluator -from jedi.evaluate import representation as er -from jedi.evaluate import imports -from jedi.evaluate.param import try_iter_content -from jedi.evaluate.helpers import get_module_names -from jedi.evaluate.sys_path import get_venv_path -from jedi.evaluate.iterable import unpack_tuple_to_dict - -# Jedi uses lots and lots of recursion. By setting this a little bit higher, we -# can remove some "maximum recursion depth" errors. -sys.setrecursionlimit(2000) - - -class NotFoundError(Exception): - """A custom error to avoid catching the wrong exceptions. - - .. deprecated:: 0.9.0 - Not in use anymore, Jedi just returns no goto result if you're not on a - valid name. - .. todo:: Remove! - """ - - -class Script(object): - """ - A Script is the base for completions, goto or whatever you want to do with - |jedi|. - - You can either use the ``source`` parameter or ``path`` to read a file. - Usually you're going to want to use both of them (in an editor). - - The script might be analyzed in a different ``sys.path`` than |jedi|: - - - if `sys_path` parameter is not ``None``, it will be used as ``sys.path`` - for the script; - - - if `sys_path` parameter is ``None`` and ``VIRTUAL_ENV`` environment - variable is defined, ``sys.path`` for the specified environment will be - guessed (see :func:`jedi.evaluate.sys_path.get_venv_path`) and used for - the script; - - - otherwise ``sys.path`` will match that of |jedi|. - - :param source: The source code of the current file, separated by newlines. - :type source: str - :param line: The line to perform actions on (starting with 1). - :type line: int - :param column: The column of the cursor (starting with 0). - :type column: int - :param path: The path of the file in the file system, or ``''`` if - it hasn't been saved yet. - :type path: str or None - :param encoding: The encoding of ``source``, if it is not a - ``unicode`` object (default ``'utf-8'``). - :type encoding: str - :param source_encoding: The encoding of ``source``, if it is not a - ``unicode`` object (default ``'utf-8'``). - :type encoding: str - :param sys_path: ``sys.path`` to use during analysis of the script - :type sys_path: list - - """ - def __init__(self, source=None, line=None, column=None, path=None, - encoding='utf-8', source_path=None, source_encoding=None, - sys_path=None): - if source_path is not None: - warnings.warn("Use path instead of source_path.", DeprecationWarning) - path = source_path - if source_encoding is not None: - warnings.warn("Use encoding instead of source_encoding.", DeprecationWarning) - encoding = source_encoding - - self._orig_path = path - # An empty path (also empty string) should always result in no path. - self.path = os.path.abspath(path) if path else None - - if source is None: - # TODO add a better warning than the traceback! - with open(path, 'rb') as f: - source = f.read() - - self._source = common.source_to_unicode(source, encoding) - self._code_lines = common.splitlines(self._source) - line = max(len(self._code_lines), 1) if line is None else line - if not (0 < line <= len(self._code_lines)): - raise ValueError('`line` parameter is not in a valid range.') - - line_len = len(self._code_lines[line - 1]) - column = line_len if column is None else column - if not (0 <= column <= line_len): - raise ValueError('`column` parameter is not in a valid range.') - self._pos = line, column - self._path = path - - cache.clear_time_caches() - debug.reset_time() - self._grammar = load_grammar(version='%s.%s' % sys.version_info[:2]) - if sys_path is None: - venv = os.getenv('VIRTUAL_ENV') - if venv: - sys_path = list(get_venv_path(venv)) - self._evaluator = Evaluator(self._grammar, sys_path=sys_path) - debug.speed('init') - - def _get_module(self): - cache.invalidate_star_import_cache(self._path) - parser = FastParser(self._grammar, self._source, self.path) - save_parser(self.path, parser, pickling=False) - - module = self._evaluator.wrap(parser.module) - imports.add_module(self._evaluator, unicode(module.name), module) - return parser.module - - @property - def source_path(self): - """ - .. deprecated:: 0.7.0 - Use :attr:`.path` instead. - .. todo:: Remove! - """ - warnings.warn("Use path instead of source_path.", DeprecationWarning) - return self.path - - def __repr__(self): - return '<%s: %s>' % (self.__class__.__name__, repr(self._orig_path)) - - def completions(self): - """ - Return :class:`classes.Completion` objects. Those objects contain - information about the completions, more than just names. - - :return: Completion objects, sorted by name and __ comes last. - :rtype: list of :class:`classes.Completion` - """ - debug.speed('completions start') - completion = Completion( - self._evaluator, self._get_module(), self._code_lines, - self._pos, self.call_signatures - ) - completions = completion.completions() - debug.speed('completions end') - return completions - - def goto_definitions(self): - """ - Return the definitions of a the path under the cursor. goto function! - This follows complicated paths and returns the end, not the first - definition. The big difference between :meth:`goto_assignments` and - :meth:`goto_definitions` is that :meth:`goto_assignments` doesn't - follow imports and statements. Multiple objects may be returned, - because Python itself is a dynamic language, which means depending on - an option you can have two different versions of a function. - - :rtype: list of :class:`classes.Definition` - """ - leaf = self._get_module().name_for_position(self._pos) - if leaf is None: - leaf = self._get_module().get_leaf_for_position(self._pos) - if leaf is None: - return [] - definitions = helpers.evaluate_goto_definition(self._evaluator, leaf) - - names = [s.name for s in definitions] - defs = [classes.Definition(self._evaluator, name) for name in names] - # The additional set here allows the definitions to become unique in an - # API sense. In the internals we want to separate more things than in - # the API. - return helpers.sorted_definitions(set(defs)) - - def goto_assignments(self, follow_imports=False): - """ - Return the first definition found, while optionally following imports. - Multiple objects may be returned, because Python itself is a - dynamic language, which means depending on an option you can have two - different versions of a function. - - :rtype: list of :class:`classes.Definition` - """ - def filter_follow_imports(names): - for name in names: - definition = name.get_definition() - if definition.type in ('import_name', 'import_from'): - imp = imports.ImportWrapper(self._evaluator, name) - for name in filter_follow_imports(imp.follow(is_goto=True)): - yield name - else: - yield name - - names = self._goto() - if follow_imports: - names = filter_follow_imports(names) - - defs = [classes.Definition(self._evaluator, d) for d in set(names)] - return helpers.sorted_definitions(defs) - - def _goto(self): - """ - Used for goto_assignments and usages. - """ - name = self._get_module().name_for_position(self._pos) - if name is None: - return [] - return list(self._evaluator.goto(name)) - - def usages(self, additional_module_paths=()): - """ - Return :class:`classes.Definition` objects, which contain all - names that point to the definition of the name under the cursor. This - is very useful for refactoring (renaming), or to show all usages of a - variable. - - .. todo:: Implement additional_module_paths - - :rtype: list of :class:`classes.Definition` - """ - temp, settings.dynamic_flow_information = \ - settings.dynamic_flow_information, False - try: - user_stmt = self._get_module().get_statement_for_position(self._pos) - definitions = self._goto() - if not definitions and isinstance(user_stmt, tree.Import): - # For not defined imports (goto doesn't find something, we take - # the name as a definition. This is enough, because every name - # points to it. - name = user_stmt.name_for_position(self._pos) - if name is None: - # Must be syntax - return [] - definitions = [name] - - if not definitions: - # Without a definition for a name we cannot find references. - return [] - - if not isinstance(user_stmt, tree.Import): - # import case is looked at with add_import_name option - definitions = usages.usages_add_import_modules(self._evaluator, - definitions) - - module = set([d.get_parent_until() for d in definitions]) - module.add(self._get_module()) - names = usages.usages(self._evaluator, definitions, module) - - for d in set(definitions): - names.append(classes.Definition(self._evaluator, d)) - finally: - settings.dynamic_flow_information = temp - - return helpers.sorted_definitions(set(names)) - - def call_signatures(self): - """ - Return the function object of the call you're currently in. - - E.g. if the cursor is here:: - - abs(# <-- cursor is here - - This would return the ``abs`` function. On the other hand:: - - abs()# <-- cursor is here - - This would return an empty list.. - - :rtype: list of :class:`classes.CallSignature` - """ - call_signature_details = \ - helpers.get_call_signature_details(self._get_module(), self._pos) - if call_signature_details is None: - return [] - - with common.scale_speed_settings(settings.scale_call_signatures): - definitions = helpers.cache_call_signatures( - self._evaluator, - call_signature_details.bracket_leaf, - self._code_lines, - self._pos - ) - debug.speed('func_call followed') - - return [classes.CallSignature(self._evaluator, d.name, - call_signature_details.bracket_leaf.start_pos, - call_signature_details.call_index, - call_signature_details.keyword_name_str) - for d in definitions if hasattr(d, 'py__call__')] - - def _analysis(self): - self._evaluator.is_analysis = True - self._evaluator.analysis_modules = [self._get_module()] - try: - for node in self._get_module().nodes_to_execute(): - if node.type in ('funcdef', 'classdef'): - if node.type == 'classdef': - continue - raise NotImplementedError - er.Function(self._evaluator, node).get_decorated_func() - elif isinstance(node, tree.Import): - import_names = set(node.get_defined_names()) - if node.is_nested(): - import_names |= set(path[-1] for path in node.paths()) - for n in import_names: - imports.ImportWrapper(self._evaluator, n).follow() - elif node.type == 'expr_stmt': - types = self._evaluator.eval_element(node) - for testlist in node.children[:-1:2]: - # Iterate tuples. - unpack_tuple_to_dict(self._evaluator, types, testlist) - else: - try_iter_content(self._evaluator.goto_definitions(node)) - self._evaluator.reset_recursion_limitations() - - ana = [a for a in self._evaluator.analysis if self.path == a.path] - return sorted(set(ana), key=lambda x: x.line) - finally: - self._evaluator.is_analysis = False - - -class Interpreter(Script): - """ - Jedi API for Python REPLs. - - In addition to completion of simple attribute access, Jedi - supports code completion based on static code analysis. - Jedi can complete attributes of object which is not initialized - yet. - - >>> from os.path import join - >>> namespace = locals() - >>> script = Interpreter('join("").up', [namespace]) - >>> print(script.completions()[0].name) - upper - """ - - def __init__(self, source, namespaces, **kwds): - """ - Parse `source` and mixin interpreted Python objects from `namespaces`. - - :type source: str - :arg source: Code to parse. - :type namespaces: list of dict - :arg namespaces: a list of namespace dictionaries such as the one - returned by :func:`locals`. - - Other optional arguments are same as the ones for :class:`Script`. - If `line` and `column` are None, they are assumed be at the end of - `source`. - """ - try: - namespaces = [dict(n) for n in namespaces] - except Exception: - raise TypeError("namespaces must be a non-empty list of dicts.") - - super(Interpreter, self).__init__(source, **kwds) - self.namespaces = namespaces - - parser_module = super(Interpreter, self)._get_module() - self._module = interpreter.MixedModule(self._evaluator, parser_module, self.namespaces) - - def _get_module(self): - return self._module - - -def defined_names(source, path=None, encoding='utf-8'): - """ - Get all definitions in `source` sorted by its position. - - This functions can be used for listing functions, classes and - data defined in a file. This can be useful if you want to list - them in "sidebar". Each element in the returned list also has - `defined_names` method which can be used to get sub-definitions - (e.g., methods in class). - - :rtype: list of classes.Definition - - .. deprecated:: 0.9.0 - Use :func:`names` instead. - .. todo:: Remove! - """ - warnings.warn("Use call_signatures instead.", DeprecationWarning) - return names(source, path, encoding) - - -def names(source=None, path=None, encoding='utf-8', all_scopes=False, - definitions=True, references=False): - """ - Returns a list of `Definition` objects, containing name parts. - This means you can call ``Definition.goto_assignments()`` and get the - reference of a name. - The parameters are the same as in :py:class:`Script`, except or the - following ones: - - :param all_scopes: If True lists the names of all scopes instead of only - the module namespace. - :param definitions: If True lists the names that have been defined by a - class, function or a statement (``a = b`` returns ``a``). - :param references: If True lists all the names that are not listed by - ``definitions=True``. E.g. ``a = b`` returns ``b``. - """ - def def_ref_filter(_def): - is_def = _def.is_definition() - return definitions and is_def or references and not is_def - - # Set line/column to a random position, because they don't matter. - script = Script(source, line=1, column=0, path=path, encoding=encoding) - defs = [classes.Definition(script._evaluator, name_part) - for name_part in get_module_names(script._get_module(), all_scopes)] - return sorted(filter(def_ref_filter, defs), key=lambda x: (x.line, x.column)) - - -def preload_module(*modules): - """ - Preloading modules tells Jedi to load a module now, instead of lazy parsing - of modules. Usful for IDEs, to control which modules to load on startup. - - :param modules: different module names, list of string. - """ - for m in modules: - s = "import %s as x; x." % m - Script(s, 1, len(s), None).completions() - - -def set_debug_function(func_cb=debug.print_to_stdout, warnings=True, - notices=True, speed=True): - """ - Define a callback debug function to get all the debug messages. - - If you don't specify any arguments, debug messages will be printed to stdout. - - :param func_cb: The callback function for debug messages, with n params. - """ - debug.debug_function = func_cb - debug.enable_warning = warnings - debug.enable_notice = notices - debug.enable_speed = speed diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/api/__pycache__/__init__.cpython-35.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/api/__pycache__/__init__.cpython-35.pyc deleted file mode 100644 index cf46de3..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/api/__pycache__/__init__.cpython-35.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/api/__pycache__/__init__.cpython-36.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/api/__pycache__/__init__.cpython-36.pyc deleted file mode 100644 index 9362925..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/api/__pycache__/__init__.cpython-36.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/api/__pycache__/classes.cpython-35.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/api/__pycache__/classes.cpython-35.pyc deleted file mode 100644 index dc9b58a..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/api/__pycache__/classes.cpython-35.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/api/__pycache__/classes.cpython-36.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/api/__pycache__/classes.cpython-36.pyc deleted file mode 100644 index 6419232..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/api/__pycache__/classes.cpython-36.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/api/__pycache__/completion.cpython-35.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/api/__pycache__/completion.cpython-35.pyc deleted file mode 100644 index 1ef7440..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/api/__pycache__/completion.cpython-35.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/api/__pycache__/completion.cpython-36.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/api/__pycache__/completion.cpython-36.pyc deleted file mode 100644 index 047f2bc..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/api/__pycache__/completion.cpython-36.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/api/__pycache__/helpers.cpython-35.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/api/__pycache__/helpers.cpython-35.pyc deleted file mode 100644 index fa7cd3a..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/api/__pycache__/helpers.cpython-35.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/api/__pycache__/helpers.cpython-36.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/api/__pycache__/helpers.cpython-36.pyc deleted file mode 100644 index e2e675d..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/api/__pycache__/helpers.cpython-36.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/api/__pycache__/interpreter.cpython-35.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/api/__pycache__/interpreter.cpython-35.pyc deleted file mode 100644 index 283022f..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/api/__pycache__/interpreter.cpython-35.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/api/__pycache__/interpreter.cpython-36.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/api/__pycache__/interpreter.cpython-36.pyc deleted file mode 100644 index 5743fd7..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/api/__pycache__/interpreter.cpython-36.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/api/__pycache__/keywords.cpython-35.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/api/__pycache__/keywords.cpython-35.pyc deleted file mode 100644 index 2c8dde5..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/api/__pycache__/keywords.cpython-35.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/api/__pycache__/keywords.cpython-36.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/api/__pycache__/keywords.cpython-36.pyc deleted file mode 100644 index 1994403..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/api/__pycache__/keywords.cpython-36.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/api/__pycache__/usages.cpython-35.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/api/__pycache__/usages.cpython-35.pyc deleted file mode 100644 index 767b47e..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/api/__pycache__/usages.cpython-35.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/api/__pycache__/usages.cpython-36.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/api/__pycache__/usages.cpython-36.pyc deleted file mode 100644 index 324efef..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/api/__pycache__/usages.cpython-36.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/api/classes.py b/vim-plugins/bundle/jedi-vim/jedi/jedi/api/classes.py deleted file mode 100644 index a1d3ce8..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/api/classes.py +++ /dev/null @@ -1,764 +0,0 @@ -""" -The :mod:`jedi.api.classes` module contains the return classes of the API. -These classes are the much bigger part of the whole API, because they contain -the interesting information about completion and goto operations. -""" -import warnings -from itertools import chain -import re - -from jedi._compatibility import unicode, use_metaclass -from jedi import settings -from jedi import common -from jedi.parser import tree -from jedi.parser.utils import load_parser -from jedi.evaluate.cache import memoize_default, CachedMetaClass -from jedi.evaluate import representation as er -from jedi.evaluate import iterable -from jedi.evaluate import imports -from jedi.evaluate import compiled -from jedi.evaluate.compiled import mixed -from jedi.api import keywords -from jedi.evaluate.finder import filter_definition_names - - -def defined_names(evaluator, scope): - """ - List sub-definitions (e.g., methods in class). - - :type scope: Scope - :rtype: list of Definition - """ - dct = scope.names_dict - names = list(chain.from_iterable(dct.values())) - names = filter_definition_names(names, scope) - return [Definition(evaluator, d) for d in sorted(names, key=lambda s: s.start_pos)] - - -class BaseDefinition(object): - _mapping = { - 'posixpath': 'os.path', - 'riscospath': 'os.path', - 'ntpath': 'os.path', - 'os2emxpath': 'os.path', - 'macpath': 'os.path', - 'genericpath': 'os.path', - 'posix': 'os', - '_io': 'io', - '_functools': 'functools', - '_sqlite3': 'sqlite3', - '__builtin__': '', - 'builtins': '', - } - - _tuple_mapping = dict((tuple(k.split('.')), v) for (k, v) in { - 'argparse._ActionsContainer': 'argparse.ArgumentParser', - '_sre.SRE_Match': 're.MatchObject', - '_sre.SRE_Pattern': 're.RegexObject', - }.items()) - - def __init__(self, evaluator, name): - self._evaluator = evaluator - self._name = name - """ - An instance of :class:`jedi.parser.reprsentation.Name` subclass. - """ - self._definition = evaluator.wrap(self._name.get_definition()) - self.is_keyword = isinstance(self._definition, keywords.Keyword) - - # generate a path to the definition - self._module = name.get_parent_until() - if self.in_builtin_module(): - self.module_path = None - else: - self.module_path = self._module.path - """Shows the file path of a module. e.g. ``/usr/lib/python2.7/os.py``""" - - @property - def name(self): - """ - Name of variable/function/class/module. - - For example, for ``x = None`` it returns ``'x'``. - - :rtype: str or None - """ - return unicode(self._name) - - @property - def start_pos(self): - """ - .. deprecated:: 0.7.0 - Use :attr:`.line` and :attr:`.column` instead. - .. todo:: Remove! - """ - warnings.warn("Use line/column instead.", DeprecationWarning) - return self._name.start_pos - - @property - def type(self): - """ - The type of the definition. - - Here is an example of the value of this attribute. Let's consider - the following source. As what is in ``variable`` is unambiguous - to Jedi, :meth:`jedi.Script.goto_definitions` should return a list of - definition for ``sys``, ``f``, ``C`` and ``x``. - - >>> from jedi import Script - >>> source = ''' - ... import keyword - ... - ... class C: - ... pass - ... - ... class D: - ... pass - ... - ... x = D() - ... - ... def f(): - ... pass - ... - ... for variable in [keyword, f, C, x]: - ... variable''' - - >>> script = Script(source) - >>> defs = script.goto_definitions() - - Before showing what is in ``defs``, let's sort it by :attr:`line` - so that it is easy to relate the result to the source code. - - >>> defs = sorted(defs, key=lambda d: d.line) - >>> defs # doctest: +NORMALIZE_WHITESPACE - [, , - , ] - - Finally, here is what you can get from :attr:`type`: - - >>> defs[0].type - 'module' - >>> defs[1].type - 'class' - >>> defs[2].type - 'instance' - >>> defs[3].type - 'function' - - """ - stripped = self._definition - if isinstance(stripped, er.InstanceElement): - stripped = stripped.var - - if isinstance(stripped, (compiled.CompiledObject, mixed.MixedObject)): - return stripped.api_type() - elif isinstance(stripped, iterable.Array): - return 'instance' - elif isinstance(stripped, tree.Import): - return 'import' - - string = type(stripped).__name__.lower().replace('wrapper', '') - if string == 'exprstmt': - return 'statement' - else: - return string - - def _path(self): - """The path to a module/class/function definition.""" - path = [] - par = self._definition - while par is not None: - if isinstance(par, tree.Import): - path += imports.ImportWrapper(self._evaluator, self._name).import_path - break - try: - name = par.name - except AttributeError: - pass - else: - if isinstance(par, er.ModuleWrapper): - # TODO just make the path dotted from the beginning, we - # shouldn't really split here. - path[0:0] = par.py__name__().split('.') - break - else: - path.insert(0, unicode(name)) - par = par.parent - return path - - @property - def module_name(self): - """ - The module name. - - >>> from jedi import Script - >>> source = 'import json' - >>> script = Script(source, path='example.py') - >>> d = script.goto_definitions()[0] - >>> print(d.module_name) # doctest: +ELLIPSIS - json - """ - return str(self._module.name) - - def in_builtin_module(self): - """Whether this is a builtin module.""" - return isinstance(self._module, compiled.CompiledObject) - - @property - def line(self): - """The line where the definition occurs (starting with 1).""" - if self.in_builtin_module(): - return None - return self._name.start_pos[0] - - @property - def column(self): - """The column where the definition occurs (starting with 0).""" - if self.in_builtin_module(): - return None - return self._name.start_pos[1] - - def docstring(self, raw=False): - r""" - Return a document string for this completion object. - - Example: - - >>> from jedi import Script - >>> source = '''\ - ... def f(a, b=1): - ... "Document for function f." - ... ''' - >>> script = Script(source, 1, len('def f'), 'example.py') - >>> doc = script.goto_definitions()[0].docstring() - >>> print(doc) - f(a, b=1) - - Document for function f. - - Notice that useful extra information is added to the actual - docstring. For function, it is call signature. If you need - actual docstring, use ``raw=True`` instead. - - >>> print(script.goto_definitions()[0].docstring(raw=True)) - Document for function f. - - """ - if raw: - return _Help(self._definition).raw() - else: - return _Help(self._definition).full() - - @property - def doc(self): - """ - .. deprecated:: 0.8.0 - Use :meth:`.docstring` instead. - .. todo:: Remove! - """ - warnings.warn("Use docstring() instead.", DeprecationWarning) - return self.docstring() - - @property - def raw_doc(self): - """ - .. deprecated:: 0.8.0 - Use :meth:`.docstring` instead. - .. todo:: Remove! - """ - warnings.warn("Use docstring() instead.", DeprecationWarning) - return self.docstring(raw=True) - - @property - def description(self): - """A textual description of the object.""" - return unicode(self._name) - - @property - def full_name(self): - """ - Dot-separated path of this object. - - It is in the form of ``[.[...]][.]``. - It is useful when you want to look up Python manual of the - object at hand. - - Example: - - >>> from jedi import Script - >>> source = ''' - ... import os - ... os.path.join''' - >>> script = Script(source, 3, len('os.path.join'), 'example.py') - >>> print(script.goto_definitions()[0].full_name) - os.path.join - - Notice that it correctly returns ``'os.path.join'`` instead of - (for example) ``'posixpath.join'``. - - """ - path = [unicode(p) for p in self._path()] - # TODO add further checks, the mapping should only occur on stdlib. - if not path: - return None # for keywords the path is empty - - with common.ignored(KeyError): - path[0] = self._mapping[path[0]] - for key, repl in self._tuple_mapping.items(): - if tuple(path[:len(key)]) == key: - path = [repl] + path[len(key):] - - return '.'.join(path if path[0] else path[1:]) - - def goto_assignments(self): - defs = self._evaluator.goto(self._name) - return [Definition(self._evaluator, d) for d in defs] - - @memoize_default() - def _follow_statements_imports(self): - """ - Follow both statements and imports, as far as possible. - """ - if self._definition.isinstance(tree.ExprStmt): - return self._evaluator.eval_statement(self._definition) - elif self._definition.isinstance(tree.Import): - return imports.ImportWrapper(self._evaluator, self._name).follow() - else: - return set([self._definition]) - - @property - @memoize_default() - def params(self): - """ - Raises an ``AttributeError``if the definition is not callable. - Otherwise returns a list of `Definition` that represents the params. - """ - followed = list(self._follow_statements_imports()) - if not followed or not hasattr(followed[0], 'py__call__'): - raise AttributeError() - followed = followed[0] # only check the first one. - - if followed.type in ('funcdef', 'lambda'): - if isinstance(followed, er.InstanceElement): - params = followed.params[1:] - else: - params = followed.params - elif followed.isinstance(er.compiled.CompiledObject): - params = followed.params - elif isinstance(followed, er.Class): - try: - sub = followed.get_subscope_by_name('__init__') - params = sub.params[1:] # ignore self - except KeyError: - return [] - elif isinstance(followed, er.Instance): - try: - sub = followed.get_subscope_by_name('__call__') - params = sub.params[1:] # ignore self - except KeyError: - return [] - else: - return [] - return [_Param(self._evaluator, p.name) for p in params] - - def parent(self): - scope = self._definition.get_parent_scope() - scope = self._evaluator.wrap(scope) - return Definition(self._evaluator, scope.name) - - def __repr__(self): - return "<%s %s>" % (type(self).__name__, self.description) - - def get_line_code(self, before=0, after=0): - """ - Returns the line of code where this object was defined. - - :param before: Add n lines before the current line to the output. - :param after: Add n lines after the current line to the output. - - :return str: Returns the line(s) of code or an empty string if it's a - builtin. - """ - if self.in_builtin_module(): - return '' - - path = self._definition.get_parent_until().path - parser = load_parser(path) - lines = common.splitlines(parser.source) - - line_nr = self._name.start_pos[0] - start_line_nr = line_nr - before - return '\n'.join(lines[start_line_nr:line_nr + after + 1]) - - -class Completion(BaseDefinition): - """ - `Completion` objects are returned from :meth:`api.Script.completions`. They - provide additional information about a completion. - """ - def __init__(self, evaluator, name, stack, like_name_length): - super(Completion, self).__init__(evaluator, name) - - self._like_name_length = like_name_length - self._stack = stack - - # Completion objects with the same Completion name (which means - # duplicate items in the completion) - self._same_name_completions = [] - - def _complete(self, like_name): - append = '' - if settings.add_bracket_after_function \ - and self.type == 'Function': - append = '(' - - if isinstance(self._definition, tree.Param) and self._stack is not None: - node_names = list(self._stack.get_node_names(self._evaluator.grammar)) - if 'trailer' in node_names and 'argument' not in node_names: - append += '=' - - name = str(self._name) - if like_name: - name = name[self._like_name_length:] - return name + append - - @property - def complete(self): - """ - Return the rest of the word, e.g. completing ``isinstance``:: - - isinstan# <-- Cursor is here - - would return the string 'ce'. It also adds additional stuff, depending - on your `settings.py`. - """ - return self._complete(True) - - @property - def name_with_symbols(self): - """ - Similar to :attr:`name`, but like :attr:`name` - returns also the symbols, for example:: - - list() - - would return ``.append`` and others (which means it adds a dot). - """ - return self._complete(False) - - @property - def description(self): - """Provide a description of the completion object.""" - if self._definition is None: - return '' - t = self.type - if t == 'statement' or t == 'import': - desc = self._definition.get_code() - else: - desc = '.'.join(unicode(p) for p in self._path()) - - line = '' if self.in_builtin_module else '@%s' % self.line - return '%s: %s%s' % (t, desc, line) - - def __repr__(self): - return '<%s: %s>' % (type(self).__name__, self._name) - - def docstring(self, raw=False, fast=True): - """ - :param fast: Don't follow imports that are only one level deep like - ``import foo``, but follow ``from foo import bar``. This makes - sense for speed reasons. Completing `import a` is slow if you use - the ``foo.docstring(fast=False)`` on every object, because it - parses all libraries starting with ``a``. - """ - definition = self._definition - if isinstance(definition, tree.Import): - i = imports.ImportWrapper(self._evaluator, self._name) - if len(i.import_path) > 1 or not fast: - followed = self._follow_statements_imports() - if followed: - # TODO: Use all of the followed objects as input to Documentation. - definition = list(followed)[0] - - if raw: - return _Help(definition).raw() - else: - return _Help(definition).full() - - @property - def type(self): - """ - The type of the completion objects. Follows imports. For a further - description, look at :attr:`jedi.api.classes.BaseDefinition.type`. - """ - if isinstance(self._definition, tree.Import): - i = imports.ImportWrapper(self._evaluator, self._name) - if len(i.import_path) <= 1: - return 'module' - - followed = self.follow_definition() - if followed: - # Caveat: Only follows the first one, ignore the other ones. - # This is ok, since people are almost never interested in - # variations. - return followed[0].type - return super(Completion, self).type - - @memoize_default() - def _follow_statements_imports(self): - # imports completion is very complicated and needs to be treated - # separately in Completion. - definition = self._definition - if definition.isinstance(tree.Import): - i = imports.ImportWrapper(self._evaluator, self._name) - return i.follow() - return super(Completion, self)._follow_statements_imports() - - @memoize_default() - def follow_definition(self): - """ - Return the original definitions. I strongly recommend not using it for - your completions, because it might slow down |jedi|. If you want to - read only a few objects (<=20), it might be useful, especially to get - the original docstrings. The basic problem of this function is that it - follows all results. This means with 1000 completions (e.g. numpy), - it's just PITA-slow. - """ - defs = self._follow_statements_imports() - return [Definition(self._evaluator, d.name) for d in defs] - - -class Definition(use_metaclass(CachedMetaClass, BaseDefinition)): - """ - *Definition* objects are returned from :meth:`api.Script.goto_assignments` - or :meth:`api.Script.goto_definitions`. - """ - def __init__(self, evaluator, definition): - super(Definition, self).__init__(evaluator, definition) - - @property - def description(self): - """ - A description of the :class:`.Definition` object, which is heavily used - in testing. e.g. for ``isinstance`` it returns ``def isinstance``. - - Example: - - >>> from jedi import Script - >>> source = ''' - ... def f(): - ... pass - ... - ... class C: - ... pass - ... - ... variable = f if random.choice([0,1]) else C''' - >>> script = Script(source, column=3) # line is maximum by default - >>> defs = script.goto_definitions() - >>> defs = sorted(defs, key=lambda d: d.line) - >>> defs - [, ] - >>> str(defs[0].description) # strip literals in python2 - 'def f' - >>> str(defs[1].description) - 'class C' - - """ - d = self._definition - if isinstance(d, er.InstanceElement): - d = d.var - - if isinstance(d, compiled.CompiledObject): - typ = d.api_type() - if typ == 'instance': - typ = 'class' # The description should be similar to Py objects. - d = typ + ' ' + d.name.get_code() - elif isinstance(d, iterable.Array): - d = 'class ' + d.type - elif isinstance(d, (tree.Class, er.Class, er.Instance)): - d = 'class ' + unicode(d.name) - elif isinstance(d, (er.Function, tree.Function)): - d = 'def ' + unicode(d.name) - elif isinstance(d, tree.Module): - # only show module name - d = 'module %s' % self.module_name - elif isinstance(d, tree.Param): - d = d.get_code().strip() - if d.endswith(','): - d = d[:-1] # Remove the comma. - else: # ExprStmt - try: - first_leaf = d.first_leaf() - except AttributeError: - # `d` is already a Leaf (Name). - first_leaf = d - # Remove the prefix, because that's not what we want for get_code - # here. - old, first_leaf.prefix = first_leaf.prefix, '' - try: - d = d.get_code() - finally: - first_leaf.prefix = old - # Delete comments: - d = re.sub('#[^\n]+\n', ' ', d) - # Delete multi spaces/newlines - return re.sub('\s+', ' ', d).strip() - - @property - def desc_with_module(self): - """ - In addition to the definition, also return the module. - - .. warning:: Don't use this function yet, its behaviour may change. If - you really need it, talk to me. - - .. todo:: Add full path. This function is should return a - `module.class.function` path. - """ - position = '' if self.in_builtin_module else '@%s' % (self.line) - return "%s:%s%s" % (self.module_name, self.description, position) - - @memoize_default() - def defined_names(self): - """ - List sub-definitions (e.g., methods in class). - - :rtype: list of Definition - """ - defs = self._follow_statements_imports() - # For now we don't want base classes or evaluate decorators. - defs = [d.base if isinstance(d, (er.Class, er.Function)) else d for d in defs] - iterable = (defined_names(self._evaluator, d) for d in defs) - iterable = list(iterable) - return list(chain.from_iterable(iterable)) - - def is_definition(self): - """ - Returns True, if defined as a name in a statement, function or class. - Returns False, if it's a reference to such a definition. - """ - return self._name.is_definition() - - def __eq__(self, other): - return self._name.start_pos == other._name.start_pos \ - and self.module_path == other.module_path \ - and self.name == other.name \ - and self._evaluator == other._evaluator - - def __ne__(self, other): - return not self.__eq__(other) - - def __hash__(self): - return hash((self._name.start_pos, self.module_path, self.name, self._evaluator)) - - -class CallSignature(Definition): - """ - `CallSignature` objects is the return value of `Script.function_definition`. - It knows what functions you are currently in. e.g. `isinstance(` would - return the `isinstance` function. without `(` it would return nothing. - """ - def __init__(self, evaluator, executable_name, bracket_start_pos, index, key_name_str): - super(CallSignature, self).__init__(evaluator, executable_name) - self._index = index - self._key_name_str = key_name_str - self._bracket_start_pos = bracket_start_pos - - @property - def index(self): - """ - The Param index of the current call. - Returns None if the index cannot be found in the curent call. - """ - if self._key_name_str is not None: - for i, param in enumerate(self.params): - if self._key_name_str == param.name: - return i - if self.params and self.params[-1]._name.get_definition().stars == 2: - return i - else: - return None - - if self._index >= len(self.params): - - for i, param in enumerate(self.params): - # *args case - if param._name.get_definition().stars == 1: - return i - return None - return self._index - - @property - def bracket_start(self): - """ - The indent of the bracket that is responsible for the last function - call. - """ - return self._bracket_start_pos - - @property - def call_name(self): - """ - .. deprecated:: 0.8.0 - Use :attr:`.name` instead. - .. todo:: Remove! - - The name (e.g. 'isinstance') as a string. - """ - warnings.warn("Use name instead.", DeprecationWarning) - return unicode(self.name) - - @property - def module(self): - """ - .. deprecated:: 0.8.0 - Use :attr:`.module_name` for the module name. - .. todo:: Remove! - """ - return self._executable.get_parent_until() - - def __repr__(self): - return '<%s: %s index %s>' % (type(self).__name__, self._name, - self.index) - - -class _Param(Definition): - """ - Just here for backwards compatibility. - """ - def get_code(self): - """ - .. deprecated:: 0.8.0 - Use :attr:`.description` and :attr:`.name` instead. - .. todo:: Remove! - - A function to get the whole code of the param. - """ - warnings.warn("Use description instead.", DeprecationWarning) - return self.description - - -class _Help(object): - """ - Temporary implementation, will be used as `Script.help() or something in - the future. - """ - def __init__(self, definition): - self._name = definition - - def full(self): - try: - return self._name.doc - except AttributeError: - return self.raw() - - def raw(self): - """ - The raw docstring ``__doc__`` for any object. - - See :attr:`doc` for example. - """ - try: - return self._name.raw_doc - except AttributeError: - return '' diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/api/completion.py b/vim-plugins/bundle/jedi-vim/jedi/jedi/api/completion.py deleted file mode 100644 index 2c0c44d..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/api/completion.py +++ /dev/null @@ -1,256 +0,0 @@ -from itertools import chain - -from jedi.parser import token -from jedi.parser import tree -from jedi import debug -from jedi import settings -from jedi.api import classes -from jedi.api import helpers -from jedi.evaluate import imports -from jedi.api import keywords -from jedi.evaluate import compiled -from jedi.evaluate.helpers import call_of_leaf -from jedi.evaluate.finder import global_names_dict_generator, filter_definition_names - - -def get_call_signature_param_names(call_signatures): - # add named params - for call_sig in call_signatures: - # Allow protected access, because it's a public API. - module = call_sig._name.get_parent_until() - # Compiled modules typically don't allow keyword arguments. - if not isinstance(module, compiled.CompiledObject): - for p in call_sig.params: - # Allow access on _definition here, because it's a - # public API and we don't want to make the internal - # Name object public. - if p._definition.stars == 0: # no *args/**kwargs - yield p._name - - -def filter_names(evaluator, completion_names, stack, like_name): - comp_dct = {} - for name in set(completion_names): - if settings.case_insensitive_completion \ - and str(name).lower().startswith(like_name.lower()) \ - or str(name).startswith(like_name): - - if isinstance(name.parent, (tree.Function, tree.Class)): - # TODO I think this is a hack. It should be an - # er.Function/er.Class before that. - name = evaluator.wrap(name.parent).name - new = classes.Completion( - evaluator, - name, - stack, - len(like_name) - ) - k = (new.name, new.complete) # key - if k in comp_dct and settings.no_completion_duplicates: - comp_dct[k]._same_name_completions.append(new) - else: - comp_dct[k] = new - yield new - - -def get_user_scope(module, position): - """ - Returns the scope in which the user resides. This includes flows. - """ - user_stmt = module.get_statement_for_position(position) - if user_stmt is None: - def scan(scope): - for s in scope.children: - if s.start_pos <= position <= s.end_pos: - if isinstance(s, (tree.Scope, tree.Flow)): - return scan(s) or s - elif s.type in ('suite', 'decorated'): - return scan(s) - return None - - return scan(module) or module - else: - return user_stmt.get_parent_scope(include_flows=True) - - -class Completion: - def __init__(self, evaluator, module, code_lines, position, call_signatures_method): - self._evaluator = evaluator - self._module = evaluator.wrap(module) - self._code_lines = code_lines - - # The first step of completions is to get the name - self._like_name = helpers.get_on_completion_name(module, code_lines, position) - # The actual cursor position is not what we need to calculate - # everything. We want the start of the name we're on. - self._position = position[0], position[1] - len(self._like_name) - self._call_signatures_method = call_signatures_method - - def completions(self): - completion_names = self._get_context_completions() - - completions = filter_names(self._evaluator, completion_names, - self.stack, self._like_name) - - return sorted(completions, key=lambda x: (x.name.startswith('__'), - x.name.startswith('_'), - x.name.lower())) - - def _get_context_completions(self): - """ - Analyzes the context that a completion is made in and decides what to - return. - - Technically this works by generating a parser stack and analysing the - current stack for possible grammar nodes. - - Possible enhancements: - - global/nonlocal search global - - yield from / raise from <- could be only exceptions/generators - - In args: */**: no completion - - In params (also lambda): no completion before = - """ - - grammar = self._evaluator.grammar - - try: - self.stack = helpers.get_stack_at_position( - grammar, self._code_lines, self._module, self._position - ) - except helpers.OnErrorLeaf as e: - self.stack = None - if e.error_leaf.value == '.': - # After ErrorLeaf's that are dots, we will not do any - # completions since this probably just confuses the user. - return [] - # If we don't have a context, just use global completion. - - return self._global_completions() - - allowed_keywords, allowed_tokens = \ - helpers.get_possible_completion_types(grammar, self.stack) - - completion_names = list(self._get_keyword_completion_names(allowed_keywords)) - - if token.NAME in allowed_tokens: - # This means that we actually have to do type inference. - - symbol_names = list(self.stack.get_node_names(grammar)) - - nodes = list(self.stack.get_nodes()) - - if "import_stmt" in symbol_names: - level = 0 - only_modules = True - level, names = self._parse_dotted_names(nodes) - if "import_from" in symbol_names: - if 'import' in nodes: - only_modules = False - else: - assert "import_name" in symbol_names - - completion_names += self._get_importer_names( - names, - level, - only_modules - ) - elif nodes and nodes[-1] in ('as', 'def', 'class'): - # No completions for ``with x as foo`` and ``import x as foo``. - # Also true for defining names as a class or function. - return list(self._get_class_context_completions(is_function=True)) - elif symbol_names[-1] == 'trailer' and nodes[-1] == '.': - dot = self._module.get_leaf_for_position(self._position) - atom_expr = call_of_leaf(dot.get_previous_leaf()) - completion_names += self._trailer_completions(atom_expr) - else: - completion_names += self._global_completions() - completion_names += self._get_class_context_completions(is_function=False) - - if 'trailer' in symbol_names: - call_signatures = self._call_signatures_method() - completion_names += get_call_signature_param_names(call_signatures) - - return completion_names - - def _get_keyword_completion_names(self, keywords_): - for k in keywords_: - yield keywords.keyword(self._evaluator, k).name - - def _global_completions(self): - scope = get_user_scope(self._module, self._position) - if not scope.is_scope(): # Might be a flow (if/while/etc). - scope = scope.get_parent_scope() - scope = self._evaluator.wrap(scope) - debug.dbg('global completion scope: %s', scope) - names_dicts = global_names_dict_generator( - self._evaluator, - scope, - self._position - ) - completion_names = [] - for names_dict, pos in names_dicts: - names = list(chain.from_iterable(names_dict.values())) - if not names: - continue - completion_names += filter_definition_names( - names, self._module.get_statement_for_position(self._position), pos - ) - return completion_names - - def _trailer_completions(self, atom_expr): - scopes = self._evaluator.eval_element(atom_expr) - completion_names = [] - debug.dbg('trailer completion scopes: %s', scopes) - for s in scopes: - names = [] - for names_dict in s.names_dicts(search_global=False): - names += chain.from_iterable(names_dict.values()) - - completion_names += filter_definition_names( - names, self._module.get_statement_for_position(self._position) - ) - return completion_names - - def _parse_dotted_names(self, nodes): - level = 0 - names = [] - for node in nodes[1:]: - if node in ('.', '...'): - if not names: - level += len(node.value) - elif node.type == 'dotted_name': - names += node.children[::2] - elif node.type == 'name': - names.append(node) - else: - break - return level, names - - def _get_importer_names(self, names, level=0, only_modules=True): - names = [str(n) for n in names] - i = imports.Importer(self._evaluator, names, self._module, level) - return i.completion_names(self._evaluator, only_modules=only_modules) - - def _get_class_context_completions(self, is_function=True): - """ - Autocomplete inherited methods when overriding in child class. - """ - leaf = self._module.get_leaf_for_position(self._position, include_prefixes=True) - cls = leaf.get_parent_until(tree.Class) - if isinstance(cls, (tree.Class, tree.Function)): - # Complete the methods that are defined in the super classes. - cls = self._evaluator.wrap(cls) - else: - return - - if cls.start_pos[1] >= leaf.start_pos[1]: - return - - names_dicts = cls.names_dicts(search_global=False, is_instance=True) - # The first dict is the dictionary of class itself. - next(names_dicts) - for names_dict in names_dicts: - for values in names_dict.values(): - for value in values: - if (value.parent.type == 'funcdef') == is_function: - yield value diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/api/helpers.py b/vim-plugins/bundle/jedi-vim/jedi/jedi/api/helpers.py deleted file mode 100644 index 8102cc7..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/api/helpers.py +++ /dev/null @@ -1,315 +0,0 @@ -""" -Helpers for the API -""" -import re -from collections import namedtuple - -from jedi._compatibility import u -from jedi.evaluate.helpers import call_of_leaf -from jedi import parser -from jedi.parser import tokenize -from jedi.cache import time_cache -from jedi import common - - -CompletionParts = namedtuple('CompletionParts', ['path', 'has_dot', 'name']) - - -def sorted_definitions(defs): - # Note: `or ''` below is required because `module_path` could be - return sorted(defs, key=lambda x: (x.module_path or '', x.line or 0, x.column or 0)) - - -def get_on_completion_name(module, lines, position): - leaf = module.get_leaf_for_position(position) - if leaf is None or leaf.type in ('string', 'error_leaf'): - # Completions inside strings are a bit special, we need to parse the - # string. The same is true for comments and error_leafs. - line = lines[position[0] - 1] - # The first step of completions is to get the name - return re.search(r'(?!\d)\w+$|$', line[:position[1]]).group(0) - elif leaf.type not in ('name', 'keyword'): - return '' - - return leaf.value[:position[1] - leaf.start_pos[1]] - - -def _get_code(code_lines, start_pos, end_pos): - # Get relevant lines. - lines = code_lines[start_pos[0] - 1:end_pos[0]] - # Remove the parts at the end of the line. - lines[-1] = lines[-1][:end_pos[1]] - # Remove first line indentation. - lines[0] = lines[0][start_pos[1]:] - return '\n'.join(lines) - - -class OnErrorLeaf(Exception): - @property - def error_leaf(self): - return self.args[0] - - -def _is_on_comment(leaf, position): - # We might be on a comment. - if leaf.type == 'endmarker': - try: - dedent = leaf.get_previous_leaf() - if dedent.type == 'dedent' and dedent.prefix: - # TODO This is needed because the fast parser uses multiple - # endmarker tokens within a file which is obviously ugly. - # This is so ugly that I'm not even commenting how it exactly - # happens, but let me tell you that I want to get rid of it. - leaf = dedent - except IndexError: - pass - - comment_lines = common.splitlines(leaf.prefix) - difference = leaf.start_pos[0] - position[0] - prefix_start_pos = leaf.get_start_pos_of_prefix() - if difference == 0: - indent = leaf.start_pos[1] - elif position[0] == prefix_start_pos[0]: - indent = prefix_start_pos[1] - else: - indent = 0 - line = comment_lines[-difference - 1][:position[1] - indent] - return '#' in line - - -def _get_code_for_stack(code_lines, module, position): - leaf = module.get_leaf_for_position(position, include_prefixes=True) - # It might happen that we're on whitespace or on a comment. This means - # that we would not get the right leaf. - if leaf.start_pos >= position: - if _is_on_comment(leaf, position): - return u('') - - # If we're not on a comment simply get the previous leaf and proceed. - try: - leaf = leaf.get_previous_leaf() - except IndexError: - return u('') # At the beginning of the file. - - is_after_newline = leaf.type == 'newline' - while leaf.type == 'newline': - try: - leaf = leaf.get_previous_leaf() - except IndexError: - return u('') - - if leaf.type in ('indent', 'dedent'): - return u('') - elif leaf.type == 'error_leaf' or leaf.type == 'string': - # Error leafs cannot be parsed, completion in strings is also - # impossible. - raise OnErrorLeaf(leaf) - else: - if leaf == ';': - user_stmt = leaf.parent - else: - user_stmt = leaf.get_definition() - if user_stmt.parent.type == 'simple_stmt': - user_stmt = user_stmt.parent - - if is_after_newline: - if user_stmt.start_pos[1] > position[1]: - # This means that it's actually a dedent and that means that we - # start without context (part of a suite). - return u('') - - # This is basically getting the relevant lines. - return _get_code(code_lines, user_stmt.get_start_pos_of_prefix(), position) - - -def get_stack_at_position(grammar, code_lines, module, pos): - """ - Returns the possible node names (e.g. import_from, xor_test or yield_stmt). - """ - class EndMarkerReached(Exception): - pass - - def tokenize_without_endmarker(code): - tokens = tokenize.source_tokens(code, use_exact_op_types=True) - for token_ in tokens: - if token_.string == safeword: - raise EndMarkerReached() - else: - yield token_ - - code = _get_code_for_stack(code_lines, module, pos) - # We use a word to tell Jedi when we have reached the start of the - # completion. - # Use Z as a prefix because it's not part of a number suffix. - safeword = 'ZZZ_USER_WANTS_TO_COMPLETE_HERE_WITH_JEDI' - # Remove as many indents from **all** code lines as possible. - code = code + safeword - - p = parser.ParserWithRecovery(grammar, code, start_parsing=False) - try: - p.parse(tokenizer=tokenize_without_endmarker(code)) - except EndMarkerReached: - return Stack(p.stack) - raise SystemError("This really shouldn't happen. There's a bug in Jedi.") - - -class Stack(list): - def get_node_names(self, grammar): - for dfa, state, (node_number, nodes) in self: - yield grammar.number2symbol[node_number] - - def get_nodes(self): - for dfa, state, (node_number, nodes) in self: - for node in nodes: - yield node - - -def get_possible_completion_types(grammar, stack): - def add_results(label_index): - try: - grammar_labels.append(inversed_tokens[label_index]) - except KeyError: - try: - keywords.append(inversed_keywords[label_index]) - except KeyError: - t, v = grammar.labels[label_index] - assert t >= 256 - # See if it's a symbol and if we're in its first set - inversed_keywords - itsdfa = grammar.dfas[t] - itsstates, itsfirst = itsdfa - for first_label_index in itsfirst.keys(): - add_results(first_label_index) - - inversed_keywords = dict((v, k) for k, v in grammar.keywords.items()) - inversed_tokens = dict((v, k) for k, v in grammar.tokens.items()) - - keywords = [] - grammar_labels = [] - - def scan_stack(index): - dfa, state, node = stack[index] - states, first = dfa - arcs = states[state] - - for label_index, new_state in arcs: - if label_index == 0: - # An accepting state, check the stack below. - scan_stack(index - 1) - else: - add_results(label_index) - - scan_stack(-1) - - return keywords, grammar_labels - - -def evaluate_goto_definition(evaluator, leaf): - if leaf.type == 'name': - # In case of a name we can just use goto_definition which does all the - # magic itself. - return evaluator.goto_definitions(leaf) - - node = None - parent = leaf.parent - if parent.type == 'atom': - node = leaf.parent - elif parent.type == 'trailer': - node = call_of_leaf(leaf) - - if node is None: - return [] - return evaluator.eval_element(node) - - -CallSignatureDetails = namedtuple( - 'CallSignatureDetails', - ['bracket_leaf', 'call_index', 'keyword_name_str'] -) - - -def _get_index_and_key(nodes, position): - """ - Returns the amount of commas and the keyword argument string. - """ - nodes_before = [c for c in nodes if c.start_pos < position] - if nodes_before[-1].type == 'arglist': - nodes_before = [c for c in nodes_before[-1].children if c.start_pos < position] - - key_str = None - - if nodes_before: - last = nodes_before[-1] - if last.type == 'argument' and last.children[1].end_pos <= position: - # Checked if the argument - key_str = last.children[0].value - elif last == '=': - key_str = nodes_before[-2].value - - return nodes_before.count(','), key_str - - -def _get_call_signature_details_from_error_node(node, position): - for index, element in reversed(list(enumerate(node.children))): - # `index > 0` means that it's a trailer and not an atom. - if element == '(' and element.end_pos <= position and index > 0: - # It's an error node, we don't want to match too much, just - # until the parentheses is enough. - children = node.children[index:] - name = element.get_previous_leaf() - if name.type == 'name' or name.parent.type in ('trailer', 'atom'): - return CallSignatureDetails( - element, - *_get_index_and_key(children, position) - ) - - -def get_call_signature_details(module, position): - leaf = module.get_leaf_for_position(position, include_prefixes=True) - if leaf == ')': - if leaf.end_pos == position: - leaf = leaf.get_next_leaf() - # Now that we know where we are in the syntax tree, we start to look at - # parents for possible function definitions. - node = leaf.parent - while node is not None: - if node.type in ('funcdef', 'classdef'): - # Don't show call signatures if there's stuff before it that just - # makes it feel strange to have a call signature. - return None - - for n in node.children[::-1]: - if n.start_pos < position and n.type == 'error_node': - result = _get_call_signature_details_from_error_node(n, position) - if result is not None: - return result - - if node.type == 'trailer' and node.children[0] == '(': - leaf = node.get_previous_leaf() - return CallSignatureDetails( - node.children[0], *_get_index_and_key(node.children, position)) - - node = node.parent - - return None - - -@time_cache("call_signatures_validity") -def cache_call_signatures(evaluator, bracket_leaf, code_lines, user_pos): - """This function calculates the cache key.""" - index = user_pos[0] - 1 - - before_cursor = code_lines[index][:user_pos[1]] - other_lines = code_lines[bracket_leaf.start_pos[0]:index] - whole = '\n'.join(other_lines + [before_cursor]) - before_bracket = re.match(r'.*\(', whole, re.DOTALL) - - module_path = bracket_leaf.get_parent_until().path - if module_path is None: - yield None # Don't cache! - else: - yield (module_path, before_bracket, bracket_leaf.start_pos) - yield evaluate_goto_definition( - evaluator, - bracket_leaf.get_previous_leaf() - ) diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/api/interpreter.py b/vim-plugins/bundle/jedi-vim/jedi/jedi/api/interpreter.py deleted file mode 100644 index a6778a6..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/api/interpreter.py +++ /dev/null @@ -1,67 +0,0 @@ -""" -TODO Some parts of this module are still not well documented. -""" -import copy - -from jedi.cache import underscore_memoization -from jedi.evaluate import helpers -from jedi.evaluate.representation import ModuleWrapper -from jedi.evaluate.compiled import mixed - - -class MixedModule(object): - resets_positions = True - type = 'mixed_module' - - def __init__(self, evaluator, parser_module, namespaces): - self._evaluator = evaluator - self._namespaces = namespaces - - self._namespace_objects = [type('jedi_namespace', (), n) for n in namespaces] - self._wrapped_module = ModuleWrapper(evaluator, parser_module) - # Usually we are dealing with very small code sizes when it comes to - # interpreter modules. In this case we just copy the whole syntax tree - # to be able to modify it. - self._parser_module = copy.deepcopy(parser_module) - - for child in self._parser_module.children: - child.parent = self - - def names_dicts(self, search_global): - for names_dict in self._wrapped_module.names_dicts(search_global): - yield names_dict - - for namespace_obj in self._namespace_objects: - m = mixed.MixedObject(self._evaluator, namespace_obj, self._parser_module.name) - for names_dict in m.names_dicts(False): - yield names_dict - - def __getattr__(self, name): - return getattr(self._parser_module, name) - - -class LazyName(helpers.FakeName): - def __init__(self, evaluator, module, name, value): - super(LazyName, self).__init__(name) - self._module = module - self._evaluator = evaluator - self._value = value - self._name = name - - def is_definition(self): - return True - - @property - @underscore_memoization - def parent(self): - """ - Creating fake statements for the interpreter. - - Here we are trying to link back to Python code, if possible. This means - we try to find the python module for a name (not the builtin). - """ - return mixed.create(self._evaluator, self._value) - - @parent.setter - def parent(self, value): - """Needed because the super class tries to set parent.""" diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/api/keywords.py b/vim-plugins/bundle/jedi-vim/jedi/jedi/api/keywords.py deleted file mode 100644 index d6a72b1..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/api/keywords.py +++ /dev/null @@ -1,132 +0,0 @@ -import pydoc -import keyword - -from jedi._compatibility import is_py3, is_py35 -from jedi import common -from jedi.evaluate.helpers import FakeName -from jedi.parser.tree import Leaf -try: - from pydoc_data import topics as pydoc_topics -except ImportError: - # Python 2 - try: - import pydoc_topics - except ImportError: - # This is for Python 3 embeddable version, which dont have - # pydoc_data module in its file python3x.zip. - pydoc_topics = None - -if is_py3: - if is_py35: - # in python 3.5 async and await are not proper keywords, but for - # completion pursposes should as as though they are - keys = keyword.kwlist + ["async", "await"] - else: - keys = keyword.kwlist -else: - keys = keyword.kwlist + ['None', 'False', 'True'] - - -def has_inappropriate_leaf_keyword(pos, module): - relevant_errors = filter( - lambda error: error.first_pos[0] == pos[0], - module.error_statement_stacks) - - for error in relevant_errors: - if error.next_token in keys: - return True - - return False - - -def completion_names(evaluator, stmt, pos, module): - keyword_list = all_keywords(evaluator) - - if not isinstance(stmt, Leaf) or has_inappropriate_leaf_keyword(pos, module): - keyword_list = filter( - lambda keyword: not keyword.only_valid_as_leaf, - keyword_list - ) - return [keyword.name for keyword in keyword_list] - - -def all_keywords(evaluator, pos=(0, 0)): - return set([Keyword(evaluator, k, pos) for k in keys]) - - -def keyword(evaluator, string, pos=(0, 0)): - if string in keys: - return Keyword(evaluator, string, pos) - else: - return None - - -def get_operator(evaluator, string, pos): - return Keyword(evaluator, string, pos) - - -keywords_only_valid_as_leaf = ( - 'continue', - 'break', -) - - -class Keyword(object): - type = 'completion_keyword' - - def __init__(self, evaluator, name, pos): - self.name = FakeName(name, self, pos) - self.start_pos = pos - self.parent = evaluator.BUILTINS - - def get_parent_until(self): - return self.parent - - @property - def only_valid_as_leaf(self): - return self.name.value in keywords_only_valid_as_leaf - - @property - def names(self): - """ For a `parsing.Name` like comparision """ - return [self.name] - - @property - def docstr(self): - return imitate_pydoc(self.name) - - def __repr__(self): - return '<%s: %s>' % (type(self).__name__, self.name) - - -def imitate_pydoc(string): - """ - It's not possible to get the pydoc's without starting the annoying pager - stuff. - """ - if pydoc_topics is None: - return '' - - # str needed because of possible unicode stuff in py2k (pydoc doesn't work - # with unicode strings) - string = str(string) - h = pydoc.help - with common.ignored(KeyError): - # try to access symbols - string = h.symbols[string] - string, _, related = string.partition(' ') - - get_target = lambda s: h.topics.get(s, h.keywords.get(s)) - while isinstance(string, str): - string = get_target(string) - - try: - # is a tuple now - label, related = string - except TypeError: - return '' - - try: - return pydoc_topics.topics[label] if pydoc_topics else '' - except KeyError: - return '' diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/api/replstartup.py b/vim-plugins/bundle/jedi-vim/jedi/jedi/api/replstartup.py deleted file mode 100644 index 5bfcc8c..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/api/replstartup.py +++ /dev/null @@ -1,27 +0,0 @@ -""" -To use Jedi completion in Python interpreter, add the following in your shell -setup (e.g., ``.bashrc``):: - - export PYTHONSTARTUP="$(python -m jedi repl)" - -Then you will be able to use Jedi completer in your Python interpreter:: - - $ python - Python 2.7.2+ (default, Jul 20 2012, 22:15:08) - [GCC 4.6.1] on linux2 - Type "help", "copyright", "credits" or "license" for more information. - >>> import os - >>> os.path.join().split().in # doctest: +SKIP - os.path.join().split().index os.path.join().split().insert - -""" -import jedi.utils -from jedi import __version__ as __jedi_version__ - -print('REPL completion using Jedi %s' % __jedi_version__) -jedi.utils.setup_readline() - -del jedi - -# Note: try not to do many things here, as it will contaminate global -# namespace of the interpreter. diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/api/usages.py b/vim-plugins/bundle/jedi-vim/jedi/jedi/api/usages.py deleted file mode 100644 index ecb8856..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/api/usages.py +++ /dev/null @@ -1,49 +0,0 @@ -from jedi._compatibility import unicode -from jedi.api import classes -from jedi.parser import tree -from jedi.evaluate import imports - - -def usages(evaluator, definition_names, mods): - """ - :param definitions: list of Name - """ - def compare_array(definitions): - """ `definitions` are being compared by module/start_pos, because - sometimes the id's of the objects change (e.g. executions). - """ - result = [] - for d in definitions: - module = d.get_parent_until() - result.append((module, d.start_pos)) - return result - - search_name = unicode(list(definition_names)[0]) - compare_definitions = compare_array(definition_names) - mods |= set([d.get_parent_until() for d in definition_names]) - definitions = [] - for m in imports.get_modules_containing_name(evaluator, mods, search_name): - try: - check_names = m.used_names[search_name] - except KeyError: - continue - for name in check_names: - - result = evaluator.goto(name) - if [c for c in compare_array(result) if c in compare_definitions]: - definitions.append(classes.Definition(evaluator, name)) - # Previous definitions might be imports, so include them - # (because goto might return that import name). - compare_definitions += compare_array([name]) - return definitions - - -def usages_add_import_modules(evaluator, definitions): - """ Adds the modules of the imports """ - new = set() - for d in definitions: - imp_or_stmt = d.get_definition() - if isinstance(imp_or_stmt, tree.Import): - s = imports.ImportWrapper(evaluator, d) - new |= set(s.follow(is_goto=True)) - return set(definitions) | new diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/cache.py b/vim-plugins/bundle/jedi-vim/jedi/jedi/cache.py deleted file mode 100644 index 8dc8254..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/cache.py +++ /dev/null @@ -1,127 +0,0 @@ -""" -This caching is very important for speed and memory optimizations. There's -nothing really spectacular, just some decorators. The following cache types are -available: - -- module caching (`load_parser` and `save_parser`), which uses pickle and is - really important to assure low load times of modules like ``numpy``. -- ``time_cache`` can be used to cache something for just a limited time span, - which can be useful if there's user interaction and the user cannot react - faster than a certain time. - -This module is one of the reasons why |jedi| is not thread-safe. As you can see -there are global variables, which are holding the cache information. Some of -these variables are being cleaned after every API usage. -""" -import time - -from jedi import settings -from jedi.parser.utils import parser_cache -from jedi.parser.utils import underscore_memoization - -_time_caches = {} - - -def clear_time_caches(delete_all=False): - """ Jedi caches many things, that should be completed after each completion - finishes. - - :param delete_all: Deletes also the cache that is normally not deleted, - like parser cache, which is important for faster parsing. - """ - global _time_caches - - if delete_all: - for cache in _time_caches.values(): - cache.clear() - parser_cache.clear() - else: - # normally just kill the expired entries, not all - for tc in _time_caches.values(): - # check time_cache for expired entries - for key, (t, value) in list(tc.items()): - if t < time.time(): - # delete expired entries - del tc[key] - - -def time_cache(time_add_setting): - """ - This decorator works as follows: Call it with a setting and after that - use the function with a callable that returns the key. - But: This function is only called if the key is not available. After a - certain amount of time (`time_add_setting`) the cache is invalid. - - If the given key is None, the function will not be cached. - """ - def _temp(key_func): - dct = {} - _time_caches[time_add_setting] = dct - - def wrapper(*args, **kwargs): - generator = key_func(*args, **kwargs) - key = next(generator) - try: - expiry, value = dct[key] - if expiry > time.time(): - return value - except KeyError: - pass - - value = next(generator) - time_add = getattr(settings, time_add_setting) - if key is not None: - dct[key] = time.time() + time_add, value - return value - return wrapper - return _temp - - -def memoize_method(method): - """A normal memoize function.""" - def wrapper(self, *args, **kwargs): - dct = self.__dict__.setdefault('_memoize_method_dct', {}) - key = (args, frozenset(kwargs.items())) - try: - return dct[key] - except KeyError: - result = method(self, *args, **kwargs) - dct[key] = result - return result - return wrapper - - -def cache_star_import(func): - @time_cache("star_import_cache_validity") - def wrapper(self): - yield self.base # The cache key - yield func(self) - return wrapper - - -def _invalidate_star_import_cache_module(module, only_main=False): - """ Important if some new modules are being reparsed """ - try: - t, modules = _time_caches['star_import_cache_validity'][module] - except KeyError: - pass - else: - del _time_caches['star_import_cache_validity'][module] - - # This stuff was part of load_parser. However since we're most likely - # not going to use star import caching anymore, just ignore it. - #else: - # In case there is already a module cached and this module - # has to be reparsed, we also need to invalidate the import - # caches. - # _invalidate_star_import_cache_module(parser_cache_item.parser.module) - - -def invalidate_star_import_cache(path): - """On success returns True.""" - try: - parser_cache_item = parser_cache[path] - except KeyError: - pass - else: - _invalidate_star_import_cache_module(parser_cache_item.parser.module) diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/common.py b/vim-plugins/bundle/jedi-vim/jedi/jedi/common.py deleted file mode 100644 index ae10f42..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/common.py +++ /dev/null @@ -1,169 +0,0 @@ -""" A universal module with functions / classes without dependencies. """ -import sys -import contextlib -import functools -import re -from itertools import chain -from ast import literal_eval - -from jedi._compatibility import unicode, reraise -from jedi import settings - - -class UncaughtAttributeError(Exception): - """ - Important, because `__getattr__` and `hasattr` catch AttributeErrors - implicitly. This is really evil (mainly because of `__getattr__`). - `hasattr` in Python 2 is even more evil, because it catches ALL exceptions. - Therefore this class originally had to be derived from `BaseException` - instead of `Exception`. But because I removed relevant `hasattr` from - the code base, we can now switch back to `Exception`. - - :param base: return values of sys.exc_info(). - """ - - -def safe_property(func): - return property(reraise_uncaught(func)) - - -def reraise_uncaught(func): - """ - Re-throw uncaught `AttributeError`. - - Usage: Put ``@rethrow_uncaught`` in front of the function - which does **not** suppose to raise `AttributeError`. - - AttributeError is easily get caught by `hasattr` and another - ``except AttributeError`` clause. This becomes problem when you use - a lot of "dynamic" attributes (e.g., using ``@property``) because you - can't distinguish if the property does not exist for real or some code - inside of the "dynamic" attribute through that error. In a well - written code, such error should not exist but getting there is very - difficult. This decorator is to help us getting there by changing - `AttributeError` to `UncaughtAttributeError` to avoid unexpected catch. - This helps us noticing bugs earlier and facilitates debugging. - - .. note:: Treating StopIteration here is easy. - Add that feature when needed. - """ - @functools.wraps(func) - def wrapper(*args, **kwds): - try: - return func(*args, **kwds) - except AttributeError: - exc_info = sys.exc_info() - reraise(UncaughtAttributeError(exc_info[1]), exc_info[2]) - return wrapper - - -class PushBackIterator(object): - def __init__(self, iterator): - self.pushes = [] - self.iterator = iterator - self.current = None - - def push_back(self, value): - self.pushes.append(value) - - def __iter__(self): - return self - - def next(self): - """ Python 2 Compatibility """ - return self.__next__() - - def __next__(self): - if self.pushes: - self.current = self.pushes.pop() - else: - self.current = next(self.iterator) - return self.current - - -@contextlib.contextmanager -def scale_speed_settings(factor): - a = settings.max_executions - b = settings.max_until_execution_unique - settings.max_executions *= factor - settings.max_until_execution_unique *= factor - try: - yield - finally: - settings.max_executions = a - settings.max_until_execution_unique = b - - -def indent_block(text, indention=' '): - """This function indents a text block with a default of four spaces.""" - temp = '' - while text and text[-1] == '\n': - temp += text[-1] - text = text[:-1] - lines = text.split('\n') - return '\n'.join(map(lambda s: indention + s, lines)) + temp - - -@contextlib.contextmanager -def ignored(*exceptions): - """ - Context manager that ignores all of the specified exceptions. This will - be in the standard library starting with Python 3.4. - """ - try: - yield - except exceptions: - pass - - -def source_to_unicode(source, encoding=None): - def detect_encoding(): - """ - For the implementation of encoding definitions in Python, look at: - - http://www.python.org/dev/peps/pep-0263/ - - http://docs.python.org/2/reference/lexical_analysis.html#encoding-declarations - """ - byte_mark = literal_eval(r"b'\xef\xbb\xbf'") - if source.startswith(byte_mark): - # UTF-8 byte-order mark - return 'utf-8' - - first_two_lines = re.match(br'(?:[^\n]*\n){0,2}', source).group(0) - possible_encoding = re.search(br"coding[=:]\s*([-\w.]+)", - first_two_lines) - if possible_encoding: - return possible_encoding.group(1) - else: - # the default if nothing else has been set -> PEP 263 - return encoding if encoding is not None else 'utf-8' - - if isinstance(source, unicode): - # only cast str/bytes - return source - - encoding = detect_encoding() - if not isinstance(encoding, unicode): - encoding = unicode(encoding, 'utf-8', 'replace') - # cast to unicode by default - return unicode(source, encoding, 'replace') - - -def splitlines(string): - """ - A splitlines for Python code. In contrast to Python's ``str.splitlines``, - looks at form feeds and other special characters as normal text. Just - splits ``\n`` and ``\r\n``. - Also different: Returns ``['']`` for an empty string input. - """ - return re.split('\n|\r\n', string) - - -def unite(iterable): - """Turns a two dimensional array into a one dimensional.""" - return set(chain.from_iterable(iterable)) - - -def to_list(func): - def wrapper(*args, **kwargs): - return list(func(*args, **kwargs)) - return wrapper diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/debug.py b/vim-plugins/bundle/jedi-vim/jedi/jedi/debug.py deleted file mode 100644 index 692f9c8..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/debug.py +++ /dev/null @@ -1,133 +0,0 @@ -from jedi._compatibility import encoding, is_py3, u -import inspect -import os -import time - -def _lazy_colorama_init(): - """ - Lazily init colorama if necessary, not to screw up stdout is debug not - enabled. - - This version of the function does nothing. - """ - pass - -_inited=False - -try: - if os.name == 'nt': - # Does not work on Windows, as pyreadline and colorama interfere - raise ImportError - else: - # Use colorama for nicer console output. - from colorama import Fore, init - from colorama import initialise - def _lazy_colorama_init(): - """ - Lazily init colorama if necessary, not to screw up stdout is - debug not enabled. - - This version of the function does init colorama. - """ - global _inited - if not _inited: - # pytest resets the stream at the end - causes troubles. Since - # after every output the stream is reset automatically we don't - # need this. - initialise.atexit_done = True - try: - init() - except Exception: - # Colorama fails with initializing under vim and is buggy in - # version 0.3.6. - pass - _inited = True - -except ImportError: - class Fore(object): - RED = '' - GREEN = '' - YELLOW = '' - MAGENTA = '' - RESET = '' - -NOTICE = object() -WARNING = object() -SPEED = object() - -enable_speed = False -enable_warning = False -enable_notice = False - -# callback, interface: level, str -debug_function = None -ignored_modules = ['jedi.parser'] -_debug_indent = 0 -_start_time = time.time() - - -def reset_time(): - global _start_time, _debug_indent - _start_time = time.time() - _debug_indent = 0 - - -def increase_indent(func): - """Decorator for makin """ - def wrapper(*args, **kwargs): - global _debug_indent - _debug_indent += 1 - try: - return func(*args, **kwargs) - finally: - _debug_indent -= 1 - return wrapper - - -def dbg(message, *args, **kwargs): - """ Looks at the stack, to see if a debug message should be printed. """ - # Python 2 compatibility, because it doesn't understand default args - color = kwargs.pop('color', 'GREEN') - assert color - - if debug_function and enable_notice: - frm = inspect.stack()[1] - mod = inspect.getmodule(frm[0]) - if not (mod.__name__ in ignored_modules): - i = ' ' * _debug_indent - _lazy_colorama_init() - debug_function(color, i + 'dbg: ' + message % tuple(u(repr(a)) for a in args)) - - -def warning(message, *args, **kwargs): - format = kwargs.pop('format', True) - assert not kwargs - - if debug_function and enable_warning: - i = ' ' * _debug_indent - if format: - message = message % tuple(u(repr(a)) for a in args) - debug_function('RED', i + 'warning: ' + message) - - -def speed(name): - if debug_function and enable_speed: - now = time.time() - i = ' ' * _debug_indent - debug_function('YELLOW', i + 'speed: ' + '%s %s' % (name, now - _start_time)) - - -def print_to_stdout(color, str_out): - """ - The default debug function that prints to standard out. - - :param str color: A string that is an attribute of ``colorama.Fore``. - """ - col = getattr(Fore, color) - _lazy_colorama_init() - if not is_py3: - str_out = str_out.encode(encoding, 'replace') - print(col + str_out + Fore.RESET) - - -# debug_function = print_to_stdout diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/.sys_path.py.un~ b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/.sys_path.py.un~ deleted file mode 100644 index 397417e..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/.sys_path.py.un~ and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__init__.py b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__init__.py deleted file mode 100644 index 9a6ad64..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__init__.py +++ /dev/null @@ -1,534 +0,0 @@ -""" -Evaluation of Python code in |jedi| is based on three assumptions: - -* The code uses as least side effects as possible. Jedi understands certain - list/tuple/set modifications, but there's no guarantee that Jedi detects - everything (list.append in different modules for example). -* No magic is being used: - - - metaclasses - - ``setattr()`` / ``__import__()`` - - writing to ``globals()``, ``locals()``, ``object.__dict__`` -* The programmer is not a total dick, e.g. like `this - `_ :-) - -The actual algorithm is based on a principle called lazy evaluation. If you -don't know about it, google it. That said, the typical entry point for static -analysis is calling ``eval_statement``. There's separate logic for -autocompletion in the API, the evaluator is all about evaluating an expression. - -Now you need to understand what follows after ``eval_statement``. Let's -make an example:: - - import datetime - datetime.date.toda# <-- cursor here - -First of all, this module doesn't care about completion. It really just cares -about ``datetime.date``. At the end of the procedure ``eval_statement`` will -return the ``date`` class. - -To *visualize* this (simplified): - -- ``Evaluator.eval_statement`` doesn't do much, because there's no assignment. -- ``Evaluator.eval_element`` cares for resolving the dotted path -- ``Evaluator.find_types`` searches for global definitions of datetime, which - it finds in the definition of an import, by scanning the syntax tree. -- Using the import logic, the datetime module is found. -- Now ``find_types`` is called again by ``eval_element`` to find ``date`` - inside the datetime module. - -Now what would happen if we wanted ``datetime.date.foo.bar``? Two more -calls to ``find_types``. However the second call would be ignored, because the -first one would return nothing (there's no foo attribute in ``date``). - -What if the import would contain another ``ExprStmt`` like this:: - - from foo import bar - Date = bar.baz - -Well... You get it. Just another ``eval_statement`` recursion. It's really -easy. Python can obviously get way more complicated then this. To understand -tuple assignments, list comprehensions and everything else, a lot more code had -to be written. - -Jedi has been tested very well, so you can just start modifying code. It's best -to write your own test first for your "new" feature. Don't be scared of -breaking stuff. As long as the tests pass, you're most likely to be fine. - -I need to mention now that lazy evaluation is really good because it -only *evaluates* what needs to be *evaluated*. All the statements and modules -that are not used are just being ignored. -""" - -import copy -import sys -from itertools import chain - -from jedi.parser import tree -from jedi import debug -from jedi.evaluate import representation as er -from jedi.evaluate import imports -from jedi.evaluate import recursion -from jedi.evaluate import iterable -from jedi.evaluate.cache import memoize_default -from jedi.evaluate import stdlib -from jedi.evaluate import finder -from jedi.evaluate import compiled -from jedi.evaluate import precedence -from jedi.evaluate import param -from jedi.evaluate import helpers - - -class Evaluator(object): - def __init__(self, grammar, sys_path=None): - self.grammar = grammar - self.memoize_cache = {} # for memoize decorators - # To memorize modules -> equals `sys.modules`. - self.modules = {} # like `sys.modules`. - self.compiled_cache = {} # see `evaluate.compiled.create()` - self.mixed_cache = {} # see `evaluate.compiled.mixed.create()` - self.analysis = [] - self.predefined_if_name_dict_dict = {} - self.dynamic_params_depth = 0 - self.is_analysis = False - - if sys_path is None: - sys_path = sys.path - self.sys_path = copy.copy(sys_path) - try: - self.sys_path.remove('') - except ValueError: - pass - - self.reset_recursion_limitations() - - # Constants - self.BUILTINS = compiled.get_special_object(self, 'BUILTINS') - - def reset_recursion_limitations(self): - self.recursion_detector = recursion.RecursionDetector(self) - self.execution_recursion_detector = recursion.ExecutionRecursionDetector(self) - - def wrap(self, element): - if isinstance(element, (er.Wrapper, er.InstanceElement, - er.ModuleWrapper, er.FunctionExecution, er.Instance, compiled.CompiledObject)) or element is None: - # TODO this is so ugly, please refactor. - return element - - if element.type == 'classdef': - return er.Class(self, element) - elif element.type == 'funcdef': - return er.Function(self, element) - elif element.type == 'lambda': - return er.LambdaWrapper(self, element) - elif element.type == 'file_input': - return er.ModuleWrapper(self, element) - else: - return element - - def find_types(self, scope, name_str, position=None, search_global=False, - is_goto=False): - """ - This is the search function. The most important part to debug. - `remove_statements` and `filter_statements` really are the core part of - this completion. - - :param position: Position of the last statement -> tuple of line, column - :return: List of Names. Their parents are the types. - """ - f = finder.NameFinder(self, scope, name_str, position) - scopes = f.scopes(search_global) - if is_goto: - return f.filter_name(scopes) - return f.find(scopes, attribute_lookup=not search_global) - - #@memoize_default(default=[], evaluator_is_first_arg=True) - #@recursion.recursion_decorator - @debug.increase_indent - def eval_statement(self, stmt, seek_name=None): - """ - The starting point of the completion. A statement always owns a call - list, which are the calls, that a statement does. In case multiple - names are defined in the statement, `seek_name` returns the result for - this name. - - :param stmt: A `tree.ExprStmt`. - """ - debug.dbg('eval_statement %s (%s)', stmt, seek_name) - rhs = stmt.get_rhs() - types = self.eval_element(rhs) - - if seek_name: - types = finder.check_tuple_assignments(self, types, seek_name) - - first_operation = stmt.first_operation() - if first_operation not in ('=', None) and not isinstance(stmt, er.InstanceElement): # TODO don't check for this. - # `=` is always the last character in aug assignments -> -1 - operator = copy.copy(first_operation) - operator.value = operator.value[:-1] - name = str(stmt.get_defined_names()[0]) - parent = self.wrap(stmt.get_parent_scope()) - left = self.find_types(parent, name, stmt.start_pos, search_global=True) - - for_stmt = stmt.get_parent_until(tree.ForStmt) - if isinstance(for_stmt, tree.ForStmt) and types \ - and for_stmt.defines_one_name(): - # Iterate through result and add the values, that's possible - # only in for loops without clutter, because they are - # predictable. Also only do it, if the variable is not a tuple. - node = for_stmt.get_input_node() - for_iterables = self.eval_element(node) - ordered = list(iterable.py__iter__(self, for_iterables, node)) - - for index_types in ordered: - dct = {str(for_stmt.children[1]): index_types} - self.predefined_if_name_dict_dict[for_stmt] = dct - t = self.eval_element(rhs) - left = precedence.calculate(self, left, operator, t) - types = left - if ordered: - # If there are no for entries, we cannot iterate and the - # types are defined by += entries. Therefore the for loop - # is never called. - del self.predefined_if_name_dict_dict[for_stmt] - else: - types = precedence.calculate(self, left, operator, types) - debug.dbg('eval_statement result %s', types) - return types - - def eval_element(self, element): - if isinstance(element, iterable.AlreadyEvaluated): - return set(element) - elif isinstance(element, iterable.MergedNodes): - return iterable.unite(self.eval_element(e) for e in element) - - if_stmt = element.get_parent_until((tree.IfStmt, tree.ForStmt, tree.IsScope)) - predefined_if_name_dict = self.predefined_if_name_dict_dict.get(if_stmt) - if predefined_if_name_dict is None and isinstance(if_stmt, tree.IfStmt): - if_stmt_test = if_stmt.children[1] - name_dicts = [{}] - # If we already did a check, we don't want to do it again -> If - # predefined_if_name_dict_dict is filled, we stop. - # We don't want to check the if stmt itself, it's just about - # the content. - if element.start_pos > if_stmt_test.end_pos: - # Now we need to check if the names in the if_stmt match the - # names in the suite. - if_names = helpers.get_names_of_node(if_stmt_test) - element_names = helpers.get_names_of_node(element) - str_element_names = [str(e) for e in element_names] - if any(str(i) in str_element_names for i in if_names): - for if_name in if_names: - definitions = self.goto_definitions(if_name) - # Every name that has multiple different definitions - # causes the complexity to rise. The complexity should - # never fall below 1. - if len(definitions) > 1: - if len(name_dicts) * len(definitions) > 16: - debug.dbg('Too many options for if branch evaluation %s.', if_stmt) - # There's only a certain amount of branches - # Jedi can evaluate, otherwise it will take to - # long. - name_dicts = [{}] - break - - original_name_dicts = list(name_dicts) - name_dicts = [] - for definition in definitions: - new_name_dicts = list(original_name_dicts) - for i, name_dict in enumerate(new_name_dicts): - new_name_dicts[i] = name_dict.copy() - new_name_dicts[i][str(if_name)] = [definition] - - name_dicts += new_name_dicts - else: - for name_dict in name_dicts: - name_dict[str(if_name)] = definitions - if len(name_dicts) > 1: - result = set() - for name_dict in name_dicts: - self.predefined_if_name_dict_dict[if_stmt] = name_dict - try: - result |= self._eval_element_not_cached(element) - finally: - del self.predefined_if_name_dict_dict[if_stmt] - return result - else: - return self._eval_element_if_evaluated(element) - return self._eval_element_cached(element) - else: - if predefined_if_name_dict: - return self._eval_element_not_cached(element) - else: - return self._eval_element_if_evaluated(element) - return self._eval_element_cached(element) - - def _eval_element_if_evaluated(self, element): - """ - TODO This function is temporary: Merge with eval_element. - """ - parent = element - while parent is not None: - parent = parent.parent - predefined_if_name_dict = self.predefined_if_name_dict_dict.get(parent) - if predefined_if_name_dict is not None: - return self._eval_element_not_cached(element) - return self._eval_element_cached(element) - - @memoize_default(default=set(), evaluator_is_first_arg=True) - def _eval_element_cached(self, element): - return self._eval_element_not_cached(element) - - @debug.increase_indent - def _eval_element_not_cached(self, element): - debug.dbg('eval_element %s@%s', element, element.start_pos) - types = set() - if isinstance(element, (tree.Name, tree.Literal)) or tree.is_node(element, 'atom'): - types = self._eval_atom(element) - elif isinstance(element, tree.Keyword): - # For False/True/None - if element.value in ('False', 'True', 'None'): - types.add(compiled.builtin_from_name(self, element.value)) - # else: print e.g. could be evaluated like this in Python 2.7 - elif element.isinstance(tree.Lambda): - types = set([er.LambdaWrapper(self, element)]) - elif element.isinstance(er.LambdaWrapper): - types = set([element]) # TODO this is no real evaluation. - elif element.type == 'expr_stmt': - types = self.eval_statement(element) - elif element.type in ('power', 'atom_expr'): - types = self._eval_atom(element.children[0]) - for trailer in element.children[1:]: - if trailer == '**': # has a power operation. - right = self.eval_element(element.children[2]) - types = set(precedence.calculate(self, types, trailer, right)) - break - types = self.eval_trailer(types, trailer) - elif element.type in ('testlist_star_expr', 'testlist',): - # The implicit tuple in statements. - types = set([iterable.ImplicitTuple(self, element)]) - elif element.type in ('not_test', 'factor'): - types = self.eval_element(element.children[-1]) - for operator in element.children[:-1]: - types = set(precedence.factor_calculate(self, types, operator)) - elif element.type == 'test': - # `x if foo else y` case. - types = (self.eval_element(element.children[0]) | - self.eval_element(element.children[-1])) - elif element.type == 'operator': - # Must be an ellipsis, other operators are not evaluated. - assert element.value == '...' - types = set([compiled.create(self, Ellipsis)]) - elif element.type == 'dotted_name': - types = self._eval_atom(element.children[0]) - for next_name in element.children[2::2]: - types = set(chain.from_iterable(self.find_types(typ, next_name) - for typ in types)) - types = types - elif element.type == 'eval_input': - types = self._eval_element_not_cached(element.children[0]) - else: - types = precedence.calculate_children(self, element.children) - debug.dbg('eval_element result %s', types) - return types - - def _eval_atom(self, atom): - """ - Basically to process ``atom`` nodes. The parser sometimes doesn't - generate the node (because it has just one child). In that case an atom - might be a name or a literal as well. - """ - if isinstance(atom, tree.Name): - # This is the first global lookup. - stmt = atom.get_definition() - scope = stmt.get_parent_until(tree.IsScope, include_current=True) - if isinstance(scope, (tree.Function, er.FunctionExecution)): - # Adjust scope: If the name is not in the suite, it's a param - # default or annotation and will be resolved as part of the - # parent scope. - colon = scope.children.index(':') - if atom.start_pos < scope.children[colon + 1].start_pos: - scope = scope.get_parent_scope() - if isinstance(stmt, tree.CompFor): - stmt = stmt.get_parent_until((tree.ClassOrFunc, tree.ExprStmt)) - if stmt.type != 'expr_stmt': - # We only need to adjust the start_pos for statements, because - # there the name cannot be used. - stmt = atom - return self.find_types(scope, atom, stmt.start_pos, search_global=True) - elif isinstance(atom, tree.Literal): - return set([compiled.create(self, atom.eval())]) - else: - c = atom.children - if c[0].type == 'string': - # Will be one string. - types = self._eval_atom(c[0]) - for string in c[1:]: - right = self._eval_atom(string) - types = precedence.calculate(self, types, '+', right) - return types - # Parentheses without commas are not tuples. - elif c[0] == '(' and not len(c) == 2 \ - and not(tree.is_node(c[1], 'testlist_comp') - and len(c[1].children) > 1): - return self.eval_element(c[1]) - - try: - comp_for = c[1].children[1] - except (IndexError, AttributeError): - pass - else: - if comp_for == ':': - # Dict comprehensions have a colon at the 3rd index. - try: - comp_for = c[1].children[3] - except IndexError: - pass - - if comp_for.type == 'comp_for': - return set([iterable.Comprehension.from_atom(self, atom)]) - return set([iterable.Array(self, atom)]) - - def eval_trailer(self, types, trailer): - trailer_op, node = trailer.children[:2] - if node == ')': # `arglist` is optional. - node = () - - new_types = set() - if trailer_op == '[': - new_types |= iterable.py__getitem__(self, types, trailer) - else: - for typ in types: - debug.dbg('eval_trailer: %s in scope %s', trailer, typ) - if trailer_op == '.': - new_types |= self.find_types(typ, node) - elif trailer_op == '(': - new_types |= self.execute(typ, node, trailer) - return new_types - - def execute_evaluated(self, obj, *args): - """ - Execute a function with already executed arguments. - """ - args = [iterable.AlreadyEvaluated([arg]) for arg in args] - return self.execute(obj, args) - - @debug.increase_indent - def execute(self, obj, arguments=(), trailer=None): - if not isinstance(arguments, param.Arguments): - arguments = param.Arguments(self, arguments, trailer) - - if self.is_analysis: - arguments.eval_all() - - if obj.isinstance(er.Function): - obj = obj.get_decorated_func() - - debug.dbg('execute: %s %s', obj, arguments) - try: - # Some stdlib functions like super(), namedtuple(), etc. have been - # hard-coded in Jedi to support them. - return stdlib.execute(self, obj, arguments) - except stdlib.NotInStdLib: - pass - - try: - func = obj.py__call__ - except AttributeError: - debug.warning("no execution possible %s", obj) - return set() - else: - types = func(arguments) - debug.dbg('execute result: %s in %s', types, obj) - return types - - def goto_definitions(self, name): - def_ = name.get_definition() - is_simple_name = name.parent.type not in ('power', 'trailer') - if is_simple_name: - if name.parent.type == 'classdef' and name.parent.name == name: - return [self.wrap(name.parent)] - if name.parent.type in ('file_input', 'funcdef'): - return [self.wrap(name.parent)] - if def_.type == 'expr_stmt' and name in def_.get_defined_names(): - return self.eval_statement(def_, name) - elif def_.type == 'for_stmt': - container_types = self.eval_element(def_.children[3]) - for_types = iterable.py__iter__types(self, container_types, def_.children[3]) - return finder.check_tuple_assignments(self, for_types, name) - elif def_.type in ('import_from', 'import_name'): - return imports.ImportWrapper(self, name).follow() - - call = helpers.call_of_leaf(name) - return self.eval_element(call) - - def goto(self, name): - def resolve_implicit_imports(names): - for name in names: - if isinstance(name.parent, helpers.FakeImport): - # Those are implicit imports. - s = imports.ImportWrapper(self, name) - for n in s.follow(is_goto=True): - yield n - else: - yield name - - stmt = name.get_definition() - par = name.parent - if par.type == 'argument' and par.children[1] == '=' and par.children[0] == name: - # Named param goto. - trailer = par.parent - if trailer.type == 'arglist': - trailer = trailer.parent - if trailer.type != 'classdef': - if trailer.type == 'decorator': - types = self.eval_element(trailer.children[1]) - else: - i = trailer.parent.children.index(trailer) - to_evaluate = trailer.parent.children[:i] - types = self.eval_element(to_evaluate[0]) - for trailer in to_evaluate[1:]: - types = self.eval_trailer(types, trailer) - param_names = [] - for typ in types: - try: - params = typ.params - except AttributeError: - pass - else: - param_names += [param.name for param in params - if param.name.value == name.value] - return param_names - elif isinstance(par, tree.ExprStmt) and name in par.get_defined_names(): - # Only take the parent, because if it's more complicated than just - # a name it's something you can "goto" again. - return [name] - elif isinstance(par, (tree.Param, tree.Function, tree.Class)) and par.name is name: - return [name] - elif isinstance(stmt, tree.Import): - modules = imports.ImportWrapper(self, name).follow(is_goto=True) - return list(resolve_implicit_imports(modules)) - elif par.type == 'dotted_name': # Is a decorator. - index = par.children.index(name) - if index > 0: - new_dotted = helpers.deep_ast_copy(par) - new_dotted.children[index - 1:] = [] - types = self.eval_element(new_dotted) - return resolve_implicit_imports(iterable.unite( - self.find_types(typ, name, is_goto=True) for typ in types - )) - - scope = name.get_parent_scope() - if tree.is_node(par, 'trailer') and par.children[0] == '.': - call = helpers.call_of_leaf(name, cut_own_trailer=True) - types = self.eval_element(call) - return resolve_implicit_imports(iterable.unite( - self.find_types(typ, name, is_goto=True) for typ in types - )) - else: - if stmt.type != 'expr_stmt': - # We only need to adjust the start_pos for statements, because - # there the name cannot be used. - stmt = name - return self.find_types(scope, name, stmt.start_pos, - search_global=True, is_goto=True) diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/__init__.cpython-35.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/__init__.cpython-35.pyc deleted file mode 100644 index 71527fe..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/__init__.cpython-35.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/__init__.cpython-36.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/__init__.cpython-36.pyc deleted file mode 100644 index 70a7c80..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/__init__.cpython-36.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/analysis.cpython-35.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/analysis.cpython-35.pyc deleted file mode 100644 index accd8dd..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/analysis.cpython-35.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/analysis.cpython-36.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/analysis.cpython-36.pyc deleted file mode 100644 index 8727a93..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/analysis.cpython-36.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/cache.cpython-35.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/cache.cpython-35.pyc deleted file mode 100644 index e4f1aec..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/cache.cpython-35.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/cache.cpython-36.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/cache.cpython-36.pyc deleted file mode 100644 index c886def..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/cache.cpython-36.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/docstrings.cpython-35.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/docstrings.cpython-35.pyc deleted file mode 100644 index 04df343..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/docstrings.cpython-35.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/docstrings.cpython-36.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/docstrings.cpython-36.pyc deleted file mode 100644 index 4853346..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/docstrings.cpython-36.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/dynamic.cpython-35.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/dynamic.cpython-35.pyc deleted file mode 100644 index 7028f2d..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/dynamic.cpython-35.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/dynamic.cpython-36.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/dynamic.cpython-36.pyc deleted file mode 100644 index 4748923..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/dynamic.cpython-36.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/finder.cpython-35.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/finder.cpython-35.pyc deleted file mode 100644 index 00b939c..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/finder.cpython-35.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/finder.cpython-36.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/finder.cpython-36.pyc deleted file mode 100644 index 6105f52..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/finder.cpython-36.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/flow_analysis.cpython-35.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/flow_analysis.cpython-35.pyc deleted file mode 100644 index 1988e03..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/flow_analysis.cpython-35.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/flow_analysis.cpython-36.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/flow_analysis.cpython-36.pyc deleted file mode 100644 index 28e1ffc..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/flow_analysis.cpython-36.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/helpers.cpython-35.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/helpers.cpython-35.pyc deleted file mode 100644 index 10971fc..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/helpers.cpython-35.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/helpers.cpython-36.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/helpers.cpython-36.pyc deleted file mode 100644 index d8cda15..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/helpers.cpython-36.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/imports.cpython-35.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/imports.cpython-35.pyc deleted file mode 100644 index a7dd086..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/imports.cpython-35.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/imports.cpython-36.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/imports.cpython-36.pyc deleted file mode 100644 index 324e015..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/imports.cpython-36.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/iterable.cpython-35.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/iterable.cpython-35.pyc deleted file mode 100644 index a803249..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/iterable.cpython-35.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/iterable.cpython-36.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/iterable.cpython-36.pyc deleted file mode 100644 index e6769c4..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/iterable.cpython-36.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/param.cpython-35.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/param.cpython-35.pyc deleted file mode 100644 index 032eeed..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/param.cpython-35.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/param.cpython-36.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/param.cpython-36.pyc deleted file mode 100644 index d8c12a5..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/param.cpython-36.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/pep0484.cpython-35.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/pep0484.cpython-35.pyc deleted file mode 100644 index e87c5d1..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/pep0484.cpython-35.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/pep0484.cpython-36.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/pep0484.cpython-36.pyc deleted file mode 100644 index 54b4750..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/pep0484.cpython-36.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/precedence.cpython-35.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/precedence.cpython-35.pyc deleted file mode 100644 index 477fae2..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/precedence.cpython-35.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/precedence.cpython-36.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/precedence.cpython-36.pyc deleted file mode 100644 index 242ac91..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/precedence.cpython-36.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/recursion.cpython-35.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/recursion.cpython-35.pyc deleted file mode 100644 index 262d192..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/recursion.cpython-35.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/recursion.cpython-36.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/recursion.cpython-36.pyc deleted file mode 100644 index 86931ab..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/recursion.cpython-36.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/representation.cpython-35.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/representation.cpython-35.pyc deleted file mode 100644 index 290f6a4..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/representation.cpython-35.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/representation.cpython-36.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/representation.cpython-36.pyc deleted file mode 100644 index 9eeaa41..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/representation.cpython-36.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/site.cpython-35.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/site.cpython-35.pyc deleted file mode 100644 index 7fbf42e..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/site.cpython-35.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/site.cpython-36.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/site.cpython-36.pyc deleted file mode 100644 index e8d4362..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/site.cpython-36.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/stdlib.cpython-35.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/stdlib.cpython-35.pyc deleted file mode 100644 index 6283ff9..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/stdlib.cpython-35.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/stdlib.cpython-36.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/stdlib.cpython-36.pyc deleted file mode 100644 index d87ddc8..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/stdlib.cpython-36.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/sys_path.cpython-35.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/sys_path.cpython-35.pyc deleted file mode 100644 index 9f2213d..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/sys_path.cpython-35.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/sys_path.cpython-36.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/sys_path.cpython-36.pyc deleted file mode 100644 index e6c9ae9..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/__pycache__/sys_path.cpython-36.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/analysis.py b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/analysis.py deleted file mode 100644 index 407bc7d..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/analysis.py +++ /dev/null @@ -1,216 +0,0 @@ -""" -Module for statical analysis. -""" -from jedi import debug -from jedi.parser import tree -from jedi.evaluate.compiled import CompiledObject - -from jedi.common import unite - - -CODES = { - 'attribute-error': (1, AttributeError, 'Potential AttributeError.'), - 'name-error': (2, NameError, 'Potential NameError.'), - 'import-error': (3, ImportError, 'Potential ImportError.'), - 'type-error-too-many-arguments': (4, TypeError, None), - 'type-error-too-few-arguments': (5, TypeError, None), - 'type-error-keyword-argument': (6, TypeError, None), - 'type-error-multiple-values': (7, TypeError, None), - 'type-error-star-star': (8, TypeError, None), - 'type-error-star': (9, TypeError, None), - 'type-error-operation': (10, TypeError, None), - 'type-error-not-iterable': (11, TypeError, None), - 'type-error-isinstance': (12, TypeError, None), - 'type-error-not-subscriptable': (13, TypeError, None), - 'value-error-too-many-values': (14, ValueError, None), - 'value-error-too-few-values': (15, ValueError, None), -} - - -class Error(object): - def __init__(self, name, module_path, start_pos, message=None): - self.path = module_path - self._start_pos = start_pos - self.name = name - if message is None: - message = CODES[self.name][2] - self.message = message - - @property - def line(self): - return self._start_pos[0] - - @property - def column(self): - return self._start_pos[1] - - @property - def code(self): - # The class name start - first = self.__class__.__name__[0] - return first + str(CODES[self.name][0]) - - def __unicode__(self): - return '%s:%s:%s: %s %s' % (self.path, self.line, self.column, - self.code, self.message) - - def __str__(self): - return self.__unicode__() - - def __eq__(self, other): - return (self.path == other.path and self.name == other.name - and self._start_pos == other._start_pos) - - def __ne__(self, other): - return not self.__eq__(other) - - def __hash__(self): - return hash((self.path, self._start_pos, self.name)) - - def __repr__(self): - return '<%s %s: %s@%s,%s>' % (self.__class__.__name__, - self.name, self.path, - self._start_pos[0], self._start_pos[1]) - - -class Warning(Error): - pass - - -def add(evaluator, name, jedi_obj, message=None, typ=Error, payload=None): - from jedi.evaluate.iterable import MergedNodes - while isinstance(jedi_obj, MergedNodes): - if len(jedi_obj) != 1: - # TODO is this kosher? - return - jedi_obj = list(jedi_obj)[0] - - exception = CODES[name][1] - if _check_for_exception_catch(evaluator, jedi_obj, exception, payload): - return - - module_path = jedi_obj.get_parent_until().path - instance = typ(name, module_path, jedi_obj.start_pos, message) - debug.warning(str(instance), format=False) - evaluator.analysis.append(instance) - - -def _check_for_setattr(instance): - """ - Check if there's any setattr method inside an instance. If so, return True. - """ - module = instance.get_parent_until() - try: - stmts = module.used_names['setattr'] - except KeyError: - return False - - return any(instance.start_pos < stmt.start_pos < instance.end_pos - for stmt in stmts) - - -def add_attribute_error(evaluator, scope, name): - message = ('AttributeError: %s has no attribute %s.' % (scope, name)) - from jedi.evaluate.representation import Instance - # Check for __getattr__/__getattribute__ existance and issue a warning - # instead of an error, if that happens. - if isinstance(scope, Instance): - typ = Warning - try: - scope.get_subscope_by_name('__getattr__') - except KeyError: - try: - scope.get_subscope_by_name('__getattribute__') - except KeyError: - if not _check_for_setattr(scope): - typ = Error - else: - typ = Error - - payload = scope, name - add(evaluator, 'attribute-error', name, message, typ, payload) - - -def _check_for_exception_catch(evaluator, jedi_obj, exception, payload=None): - """ - Checks if a jedi object (e.g. `Statement`) sits inside a try/catch and - doesn't count as an error (if equal to `exception`). - Also checks `hasattr` for AttributeErrors and uses the `payload` to compare - it. - Returns True if the exception was catched. - """ - def check_match(cls, exception): - try: - return isinstance(cls, CompiledObject) and issubclass(exception, cls.obj) - except TypeError: - return False - - def check_try_for_except(obj, exception): - # Only nodes in try - iterator = iter(obj.children) - for branch_type in iterator: - colon = next(iterator) - suite = next(iterator) - if branch_type == 'try' \ - and not (branch_type.start_pos < jedi_obj.start_pos <= suite.end_pos): - return False - - for node in obj.except_clauses(): - if node is None: - return True # An exception block that catches everything. - else: - except_classes = evaluator.eval_element(node) - for cls in except_classes: - from jedi.evaluate import iterable - if isinstance(cls, iterable.Array) and cls.type == 'tuple': - # multiple exceptions - for typ in unite(cls.py__iter__()): - if check_match(typ, exception): - return True - else: - if check_match(cls, exception): - return True - - def check_hasattr(node, suite): - try: - assert suite.start_pos <= jedi_obj.start_pos < suite.end_pos - assert node.type in ('power', 'atom_expr') - base = node.children[0] - assert base.type == 'name' and base.value == 'hasattr' - trailer = node.children[1] - assert trailer.type == 'trailer' - arglist = trailer.children[1] - assert arglist.type == 'arglist' - from jedi.evaluate.param import Arguments - args = list(Arguments(evaluator, arglist).unpack()) - # Arguments should be very simple - assert len(args) == 2 - - # Check name - key, values = args[1] - assert len(values) == 1 - names = list(evaluator.eval_element(values[0])) - assert len(names) == 1 and isinstance(names[0], CompiledObject) - assert names[0].obj == str(payload[1]) - - # Check objects - key, values = args[0] - assert len(values) == 1 - objects = evaluator.eval_element(values[0]) - return payload[0] in objects - except AssertionError: - return False - - obj = jedi_obj - while obj is not None and not obj.isinstance(tree.Function, tree.Class): - if obj.isinstance(tree.Flow): - # try/except catch check - if obj.isinstance(tree.TryStmt) and check_try_for_except(obj, exception): - return True - # hasattr check - if exception == AttributeError and obj.isinstance(tree.IfStmt, tree.WhileStmt): - if check_hasattr(obj.children[1], obj.children[3]): - return True - obj = obj.parent - - return False diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/cache.py b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/cache.py deleted file mode 100644 index b44f812..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/cache.py +++ /dev/null @@ -1,58 +0,0 @@ -""" -- the popular ``memoize_default`` works like a typical memoize and returns the - default otherwise. -- ``CachedMetaClass`` uses ``memoize_default`` to do the same with classes. -""" - -import inspect - -NO_DEFAULT = object() - - -def memoize_default(default=NO_DEFAULT, evaluator_is_first_arg=False, second_arg_is_evaluator=False): - """ This is a typical memoization decorator, BUT there is one difference: - To prevent recursion it sets defaults. - - Preventing recursion is in this case the much bigger use than speed. I - don't think, that there is a big speed difference, but there are many cases - where recursion could happen (think about a = b; b = a). - """ - def func(function): - def wrapper(obj, *args, **kwargs): - if evaluator_is_first_arg: - cache = obj.memoize_cache - elif second_arg_is_evaluator: # needed for meta classes - cache = args[0].memoize_cache - else: - cache = obj._evaluator.memoize_cache - - try: - memo = cache[function] - except KeyError: - memo = {} - cache[function] = memo - - key = (obj, args, frozenset(kwargs.items())) - if key in memo: - return memo[key] - else: - if default is not NO_DEFAULT: - memo[key] = default - rv = function(obj, *args, **kwargs) - if inspect.isgenerator(rv): - rv = list(rv) - memo[key] = rv - return rv - return wrapper - return func - - -class CachedMetaClass(type): - """ - This is basically almost the same than the decorator above, it just caches - class initializations. Either you do it this way or with decorators, but - with decorators you lose class access (isinstance, etc). - """ - @memoize_default(None, second_arg_is_evaluator=True) - def __call__(self, *args, **kwargs): - return super(CachedMetaClass, self).__call__(*args, **kwargs) diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/compiled/__init__.py b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/compiled/__init__.py deleted file mode 100644 index f004a14..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/compiled/__init__.py +++ /dev/null @@ -1,544 +0,0 @@ -""" -Imitate the parser representation. -""" -import inspect -import re -import sys -import os -from functools import partial - -from jedi._compatibility import builtins as _builtins, unicode -from jedi import debug -from jedi.cache import underscore_memoization, memoize_method -from jedi.parser.tree import Param, Base, Operator, zero_position_modifier -from jedi.evaluate.helpers import FakeName -from . import fake - - -_sep = os.path.sep -if os.path.altsep is not None: - _sep += os.path.altsep -_path_re = re.compile('(?:\.[^{0}]+|[{0}]__init__\.py)$'.format(re.escape(_sep))) -del _sep - - -class CheckAttribute(object): - """Raises an AttributeError if the attribute X isn't available.""" - def __init__(self, func): - self.func = func - # Remove the py in front of e.g. py__call__. - self.check_name = func.__name__[2:] - - def __get__(self, instance, owner): - # This might raise an AttributeError. That's wanted. - getattr(instance.obj, self.check_name) - return partial(self.func, instance) - - -class CompiledObject(Base): - # comply with the parser - start_pos = 0, 0 - path = None # modules have this attribute - set it to None. - used_names = {} # To be consistent with modules. - - def __init__(self, evaluator, obj, parent=None): - self._evaluator = evaluator - self.obj = obj - self.parent = parent - - @CheckAttribute - def py__call__(self, params): - if inspect.isclass(self.obj): - from jedi.evaluate.representation import Instance - return set([Instance(self._evaluator, self, params)]) - else: - return set(self._execute_function(params)) - - @CheckAttribute - def py__class__(self): - return create(self._evaluator, self.obj.__class__) - - @CheckAttribute - def py__mro__(self): - return tuple(create(self._evaluator, cls) for cls in self.obj.__mro__) - - @CheckAttribute - def py__bases__(self): - return tuple(create(self._evaluator, cls) for cls in self.obj.__bases__) - - def py__bool__(self): - return bool(self.obj) - - def py__file__(self): - return self.obj.__file__ - - def is_class(self): - return inspect.isclass(self.obj) - - @property - def doc(self): - return inspect.getdoc(self.obj) or '' - - @property - def params(self): - params_str, ret = self._parse_function_doc() - tokens = params_str.split(',') - if inspect.ismethoddescriptor(self.obj): - tokens.insert(0, 'self') - params = [] - for p in tokens: - parts = [FakeName(part) for part in p.strip().split('=')] - if len(parts) > 1: - parts.insert(1, Operator(zero_position_modifier, '=', (0, 0))) - params.append(Param(parts, self)) - return params - - def __repr__(self): - return '<%s: %s>' % (type(self).__name__, repr(self.obj)) - - @underscore_memoization - def _parse_function_doc(self): - if self.doc is None: - return '', '' - - return _parse_function_doc(self.doc) - - def api_type(self): - obj = self.obj - if inspect.isclass(obj): - return 'class' - elif inspect.ismodule(obj): - return 'module' - elif inspect.isbuiltin(obj) or inspect.ismethod(obj) \ - or inspect.ismethoddescriptor(obj) or inspect.isfunction(obj): - return 'function' - # Everything else... - return 'instance' - - @property - def type(self): - """Imitate the tree.Node.type values.""" - cls = self._get_class() - if inspect.isclass(cls): - return 'classdef' - elif inspect.ismodule(cls): - return 'file_input' - elif inspect.isbuiltin(cls) or inspect.ismethod(cls) or \ - inspect.ismethoddescriptor(cls): - return 'funcdef' - - @underscore_memoization - def _cls(self): - """ - We used to limit the lookups for instantiated objects like list(), but - this is not the case anymore. Python itself - """ - # Ensures that a CompiledObject is returned that is not an instance (like list) - return self - - def _get_class(self): - if not fake.is_class_instance(self.obj) or \ - inspect.ismethoddescriptor(self.obj): # slots - return self.obj - - try: - return self.obj.__class__ - except AttributeError: - # happens with numpy.core.umath._UFUNC_API (you get it - # automatically by doing `import numpy`. - return type - - @property - def names_dict(self): - # For compatibility with `representation.Class`. - return self.names_dicts(False)[0] - - def names_dicts(self, search_global, is_instance=False): - return self._names_dict_ensure_one_dict(is_instance) - - @memoize_method - def _names_dict_ensure_one_dict(self, is_instance): - """ - search_global shouldn't change the fact that there's one dict, this way - there's only one `object`. - """ - return [LazyNamesDict(self._evaluator, self, is_instance)] - - def get_subscope_by_name(self, name): - if name in dir(self.obj): - return CompiledName(self._evaluator, self, name).parent - else: - raise KeyError("CompiledObject doesn't have an attribute '%s'." % name) - - @CheckAttribute - def py__getitem__(self, index): - if type(self.obj) not in (str, list, tuple, unicode, bytes, bytearray, dict): - # Get rid of side effects, we won't call custom `__getitem__`s. - return set() - - return set([create(self._evaluator, self.obj[index])]) - - @CheckAttribute - def py__iter__(self): - if type(self.obj) not in (str, list, tuple, unicode, bytes, bytearray, dict): - # Get rid of side effects, we won't call custom `__getitem__`s. - return - - for part in self.obj: - yield set([create(self._evaluator, part)]) - - @property - def name(self): - try: - name = self._get_class().__name__ - except AttributeError: - name = repr(self.obj) - return FakeName(name, self) - - def _execute_function(self, params): - if self.type != 'funcdef': - return - - for name in self._parse_function_doc()[1].split(): - try: - bltn_obj = getattr(_builtins, name) - except AttributeError: - continue - else: - if bltn_obj is None: - # We want to evaluate everything except None. - # TODO do we? - continue - bltn_obj = create(self._evaluator, bltn_obj) - for result in self._evaluator.execute(bltn_obj, params): - yield result - - @property - @underscore_memoization - def subscopes(self): - """ - Returns only the faked scopes - the other ones are not important for - internal analysis. - """ - module = self.get_parent_until() - faked_subscopes = [] - for name in dir(self.obj): - try: - faked_subscopes.append( - fake.get_faked(module.obj, self.obj, parent=self, name=name) - ) - except fake.FakeDoesNotExist: - pass - return faked_subscopes - - def is_scope(self): - return True - - def get_self_attributes(self): - return [] # Instance compatibility - - def get_imports(self): - return [] # Builtins don't have imports - - -class CompiledName(FakeName): - def __init__(self, evaluator, compiled_obj, name): - super(CompiledName, self).__init__(name) - self._evaluator = evaluator - self._compiled_obj = compiled_obj - self.name = name - - def __repr__(self): - try: - name = self._compiled_obj.name # __name__ is not defined all the time - except AttributeError: - name = None - return '<%s: (%s).%s>' % (type(self).__name__, name, self.name) - - def is_definition(self): - return True - - @property - @underscore_memoization - def parent(self): - module = self._compiled_obj.get_parent_until() - return _create_from_name(self._evaluator, module, self._compiled_obj, self.name) - - @parent.setter - def parent(self, value): - pass # Just ignore this, FakeName tries to overwrite the parent attribute. - - -class LazyNamesDict(object): - """ - A names_dict instance for compiled objects, resembles the parser.tree. - """ - name_class = CompiledName - - def __init__(self, evaluator, compiled_obj, is_instance=False): - self._evaluator = evaluator - self._compiled_obj = compiled_obj - self._is_instance = is_instance - - def __iter__(self): - return (v[0].value for v in self.values()) - - @memoize_method - def __getitem__(self, name): - try: - getattr(self._compiled_obj.obj, name) - except AttributeError: - raise KeyError('%s in %s not found.' % (name, self._compiled_obj)) - except Exception: - # This is a bit ugly. We're basically returning this to make - # lookups possible without having the actual attribute. However - # this makes proper completion possible. - return [FakeName(name, create(self._evaluator, None), is_definition=True)] - return [self.name_class(self._evaluator, self._compiled_obj, name)] - - def values(self): - obj = self._compiled_obj.obj - - values = [] - for name in dir(obj): - try: - values.append(self[name]) - except KeyError: - # The dir function can be wrong. - pass - - is_instance = self._is_instance or fake.is_class_instance(obj) - # ``dir`` doesn't include the type names. - if not inspect.ismodule(obj) and obj != type and not is_instance: - values += create(self._evaluator, type).names_dict.values() - return values - - -def dotted_from_fs_path(fs_path, sys_path): - """ - Changes `/usr/lib/python3.4/email/utils.py` to `email.utils`. I.e. - compares the path with sys.path and then returns the dotted_path. If the - path is not in the sys.path, just returns None. - """ - if os.path.basename(fs_path).startswith('__init__.'): - # We are calculating the path. __init__ files are not interesting. - fs_path = os.path.dirname(fs_path) - - # prefer - # - UNIX - # /path/to/pythonX.Y/lib-dynload - # /path/to/pythonX.Y/site-packages - # - Windows - # C:\path\to\DLLs - # C:\path\to\Lib\site-packages - # over - # - UNIX - # /path/to/pythonX.Y - # - Windows - # C:\path\to\Lib - path = '' - for s in sys_path: - if (fs_path.startswith(s) and len(path) < len(s)): - path = s - - # - Window - # X:\path\to\lib-dynload/datetime.pyd => datetime - module_path = fs_path[len(path):].lstrip(os.path.sep).lstrip('/') - # - Window - # Replace like X:\path\to\something/foo/bar.py - return _path_re.sub('', module_path).replace(os.path.sep, '.').replace('/', '.') - - -def load_module(evaluator, path=None, name=None): - sys_path = evaluator.sys_path - if path is not None: - dotted_path = dotted_from_fs_path(path, sys_path=sys_path) - else: - dotted_path = name - - if dotted_path is None: - p, _, dotted_path = path.partition(os.path.sep) - sys_path.insert(0, p) - - temp, sys.path = sys.path, sys_path - try: - __import__(dotted_path) - except RuntimeError: - if 'PySide' in dotted_path or 'PyQt' in dotted_path: - # RuntimeError: the PyQt4.QtCore and PyQt5.QtCore modules both wrap - # the QObject class. - # See https://github.com/davidhalter/jedi/pull/483 - return None - raise - except ImportError: - # If a module is "corrupt" or not really a Python module or whatever. - debug.warning('Module %s not importable.', path) - return None - finally: - sys.path = temp - - # Just access the cache after import, because of #59 as well as the very - # complicated import structure of Python. - module = sys.modules[dotted_path] - - return create(evaluator, module) - - -docstr_defaults = { - 'floating point number': 'float', - 'character': 'str', - 'integer': 'int', - 'dictionary': 'dict', - 'string': 'str', -} - - -def _parse_function_doc(doc): - """ - Takes a function and returns the params and return value as a tuple. - This is nothing more than a docstring parser. - - TODO docstrings like utime(path, (atime, mtime)) and a(b [, b]) -> None - TODO docstrings like 'tuple of integers' - """ - # parse round parentheses: def func(a, (b,c)) - try: - count = 0 - start = doc.index('(') - for i, s in enumerate(doc[start:]): - if s == '(': - count += 1 - elif s == ')': - count -= 1 - if count == 0: - end = start + i - break - param_str = doc[start + 1:end] - except (ValueError, UnboundLocalError): - # ValueError for doc.index - # UnboundLocalError for undefined end in last line - debug.dbg('no brackets found - no param') - end = 0 - param_str = '' - else: - # remove square brackets, that show an optional param ( = None) - def change_options(m): - args = m.group(1).split(',') - for i, a in enumerate(args): - if a and '=' not in a: - args[i] += '=None' - return ','.join(args) - - while True: - param_str, changes = re.subn(r' ?\[([^\[\]]+)\]', - change_options, param_str) - if changes == 0: - break - param_str = param_str.replace('-', '_') # see: isinstance.__doc__ - - # parse return value - r = re.search('-[>-]* ', doc[end:end + 7]) - if r is None: - ret = '' - else: - index = end + r.end() - # get result type, which can contain newlines - pattern = re.compile(r'(,\n|[^\n-])+') - ret_str = pattern.match(doc, index).group(0).strip() - # New object -> object() - ret_str = re.sub(r'[nN]ew (.*)', r'\1()', ret_str) - - ret = docstr_defaults.get(ret_str, ret_str) - - return param_str, ret - - -def _create_from_name(evaluator, module, parent, name): - try: - return fake.get_faked(module.obj, parent.obj, parent=parent, name=name) - except fake.FakeDoesNotExist: - pass - - try: - obj = getattr(parent.obj, name) - except AttributeError: - # Happens e.g. in properties of - # PyQt4.QtGui.QStyleOptionComboBox.currentText - # -> just set it to None - obj = None - return create(evaluator, obj, parent) - - -def builtin_from_name(evaluator, string): - bltn_obj = getattr(_builtins, string) - return create(evaluator, bltn_obj) - - -def _a_generator(foo): - """Used to have an object to return for generators.""" - yield 42 - yield foo - - -_SPECIAL_OBJECTS = { - 'FUNCTION_CLASS': type(load_module), - 'METHOD_CLASS': type(CompiledObject.is_class), - 'MODULE_CLASS': type(os), - 'GENERATOR_OBJECT': _a_generator(1.0), - 'BUILTINS': _builtins, -} - - -def get_special_object(evaluator, identifier): - obj = _SPECIAL_OBJECTS[identifier] - return create(evaluator, obj, parent=create(evaluator, _builtins)) - - -def compiled_objects_cache(attribute_name): - def decorator(func): - """ - This decorator caches just the ids, oopposed to caching the object itself. - Caching the id has the advantage that an object doesn't need to be - hashable. - """ - def wrapper(evaluator, obj, parent=None, module=None): - cache = getattr(evaluator, attribute_name) - # Do a very cheap form of caching here. - key = id(obj), id(parent) - try: - return cache[key][0] - except KeyError: - # TODO this whole decorator looks way too ugly and this if - # doesn't make it better. Find a more generic solution. - if parent or module: - result = func(evaluator, obj, parent, module) - else: - result = func(evaluator, obj) - # Need to cache all of them, otherwise the id could be overwritten. - cache[key] = result, obj, parent, module - return result - return wrapper - - return decorator - - -@compiled_objects_cache('compiled_cache') -def create(evaluator, obj, parent=None, module=None): - """ - A very weird interface class to this module. The more options provided the - more acurate loading compiled objects is. - """ - if inspect.ismodule(obj): - if parent is not None: - # Modules don't have parents, be careful with caching: recurse. - return create(evaluator, obj) - else: - if parent is None and obj != _builtins: - return create(evaluator, obj, create(evaluator, _builtins)) - - try: - return fake.get_faked(module and module.obj, obj, parent=parent) - except fake.FakeDoesNotExist: - pass - - return CompiledObject(evaluator, obj, parent) diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/compiled/__pycache__/__init__.cpython-35.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/compiled/__pycache__/__init__.cpython-35.pyc deleted file mode 100644 index f55a9d3..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/compiled/__pycache__/__init__.cpython-35.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/compiled/__pycache__/__init__.cpython-36.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/compiled/__pycache__/__init__.cpython-36.pyc deleted file mode 100644 index fab7ced..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/compiled/__pycache__/__init__.cpython-36.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/compiled/__pycache__/fake.cpython-35.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/compiled/__pycache__/fake.cpython-35.pyc deleted file mode 100644 index 0b2418d..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/compiled/__pycache__/fake.cpython-35.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/compiled/__pycache__/fake.cpython-36.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/compiled/__pycache__/fake.cpython-36.pyc deleted file mode 100644 index 53a70e9..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/compiled/__pycache__/fake.cpython-36.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/compiled/__pycache__/mixed.cpython-35.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/compiled/__pycache__/mixed.cpython-35.pyc deleted file mode 100644 index 2b16d57..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/compiled/__pycache__/mixed.cpython-35.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/compiled/__pycache__/mixed.cpython-36.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/compiled/__pycache__/mixed.cpython-36.pyc deleted file mode 100644 index ff5bca9..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/compiled/__pycache__/mixed.cpython-36.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/compiled/fake.py b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/compiled/fake.py deleted file mode 100644 index 0338b96..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/compiled/fake.py +++ /dev/null @@ -1,203 +0,0 @@ -""" -Loads functions that are mixed in to the standard library. E.g. builtins are -written in C (binaries), but my autocompletion only understands Python code. By -mixing in Python code, the autocompletion should work much better for builtins. -""" - -import os -import inspect -import types - -from jedi._compatibility import is_py3, builtins, unicode, is_py34 -from jedi.parser import ParserWithRecovery, load_grammar -from jedi.parser import tree as pt -from jedi.evaluate.helpers import FakeName - -modules = {} - - -MethodDescriptorType = type(str.replace) -# These are not considered classes and access is granted even though they have -# a __class__ attribute. -NOT_CLASS_TYPES = ( - types.BuiltinFunctionType, - types.CodeType, - types.FrameType, - types.FunctionType, - types.GeneratorType, - types.GetSetDescriptorType, - types.LambdaType, - types.MemberDescriptorType, - types.MethodType, - types.ModuleType, - types.TracebackType, - MethodDescriptorType -) - -if is_py3: - NOT_CLASS_TYPES += ( - types.MappingProxyType, - types.SimpleNamespace - ) - if is_py34: - NOT_CLASS_TYPES += (types.DynamicClassAttribute,) - - -class FakeDoesNotExist(Exception): - pass - - -def _load_faked_module(module): - module_name = module.__name__ - if module_name == '__builtin__' and not is_py3: - module_name = 'builtins' - - try: - return modules[module_name] - except KeyError: - path = os.path.dirname(os.path.abspath(__file__)) - try: - with open(os.path.join(path, 'fake', module_name) + '.pym') as f: - source = f.read() - except IOError: - modules[module_name] = None - return - grammar = load_grammar(version='3.4') - module = ParserWithRecovery(grammar, unicode(source), module_name).module - modules[module_name] = module - - if module_name == 'builtins' and not is_py3: - # There are two implementations of `open` for either python 2/3. - # -> Rename the python2 version (`look at fake/builtins.pym`). - open_func = search_scope(module, 'open') - open_func.children[1] = FakeName('open_python3') - open_func = search_scope(module, 'open_python2') - open_func.children[1] = FakeName('open') - return module - - -def search_scope(scope, obj_name): - for s in scope.subscopes: - if str(s.name) == obj_name: - return s - - -def get_module(obj): - if inspect.ismodule(obj): - return obj - try: - obj = obj.__objclass__ - except AttributeError: - pass - - try: - imp_plz = obj.__module__ - except AttributeError: - # Unfortunately in some cases like `int` there's no __module__ - return builtins - else: - if imp_plz is None: - # Happens for example in `(_ for _ in []).send.__module__`. - return builtins - else: - try: - return __import__(imp_plz) - except ImportError: - # __module__ can be something arbitrary that doesn't exist. - return builtins - - -def _faked(module, obj, name): - # Crazy underscore actions to try to escape all the internal madness. - if module is None: - module = get_module(obj) - - faked_mod = _load_faked_module(module) - if faked_mod is None: - return None - - # Having the module as a `parser.representation.module`, we need to scan - # for methods. - if name is None: - if inspect.isbuiltin(obj): - return search_scope(faked_mod, obj.__name__) - elif not inspect.isclass(obj): - # object is a method or descriptor - try: - objclass = obj.__objclass__ - except AttributeError: - return None - else: - cls = search_scope(faked_mod, objclass.__name__) - if cls is None: - return None - return search_scope(cls, obj.__name__) - else: - if obj == module: - return search_scope(faked_mod, name) - else: - try: - cls_name = obj.__name__ - except AttributeError: - return None - cls = search_scope(faked_mod, cls_name) - if cls is None: - return None - return search_scope(cls, name) - - -def memoize_faked(obj): - """ - A typical memoize function that ignores issues with non hashable results. - """ - cache = obj.cache = {} - - def memoizer(*args, **kwargs): - key = (obj, args, frozenset(kwargs.items())) - try: - result = cache[key] - except TypeError: - return obj(*args, **kwargs) - except KeyError: - result = obj(*args, **kwargs) - if result is not None: - cache[key] = obj(*args, **kwargs) - return result - else: - return result - return memoizer - - -@memoize_faked -def _get_faked(module, obj, name=None): - obj = type(obj) if is_class_instance(obj) else obj - result = _faked(module, obj, name) - if result is None or isinstance(result, pt.Class): - # We're not interested in classes. What we want is functions. - raise FakeDoesNotExist - else: - # Set the docstr which was previously not set (faked modules don't - # contain it). - doc = '"""%s"""' % obj.__doc__ # TODO need escapes. - suite = result.children[-1] - string = pt.String(pt.zero_position_modifier, doc, (0, 0), '') - new_line = pt.Newline('\n', (0, 0), '') - docstr_node = pt.Node('simple_stmt', [string, new_line]) - suite.children.insert(2, docstr_node) - return result - - -def get_faked(module, obj, name=None, parent=None): - faked = _get_faked(module, obj, name) - faked.parent = parent - return faked - - -def is_class_instance(obj): - """Like inspect.* methods.""" - try: - cls = obj.__class__ - except AttributeError: - return False - else: - return cls != type and not issubclass(cls, NOT_CLASS_TYPES) diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/compiled/fake/_functools.pym b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/compiled/fake/_functools.pym deleted file mode 100644 index 909ef03..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/compiled/fake/_functools.pym +++ /dev/null @@ -1,9 +0,0 @@ -class partial(): - def __init__(self, func, *args, **keywords): - self.__func = func - self.__args = args - self.__keywords = keywords - - def __call__(self, *args, **kwargs): - # TODO should be **dict(self.__keywords, **kwargs) - return self.__func(*(self.__args + args), **self.__keywords) diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/compiled/fake/_sqlite3.pym b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/compiled/fake/_sqlite3.pym deleted file mode 100644 index 2151e65..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/compiled/fake/_sqlite3.pym +++ /dev/null @@ -1,26 +0,0 @@ -def connect(database, timeout=None, isolation_level=None, detect_types=None, factory=None): - return Connection() - - -class Connection(): - def cursor(self): - return Cursor() - - -class Cursor(): - def cursor(self): - return Cursor() - - def fetchone(self): - return Row() - - def fetchmany(self, size=cursor.arraysize): - return [self.fetchone()] - - def fetchall(self): - return [self.fetchone()] - - -class Row(): - def keys(self): - return [''] diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/compiled/fake/_sre.pym b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/compiled/fake/_sre.pym deleted file mode 100644 index 217be56..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/compiled/fake/_sre.pym +++ /dev/null @@ -1,99 +0,0 @@ -def compile(): - class SRE_Match(): - endpos = int() - lastgroup = int() - lastindex = int() - pos = int() - string = str() - regs = ((int(), int()),) - - def __init__(self, pattern): - self.re = pattern - - def start(self): - return int() - - def end(self): - return int() - - def span(self): - return int(), int() - - def expand(self): - return str() - - def group(self, nr): - return str() - - def groupdict(self): - return {str(): str()} - - def groups(self): - return (str(),) - - class SRE_Pattern(): - flags = int() - groupindex = {} - groups = int() - pattern = str() - - def findall(self, string, pos=None, endpos=None): - """ - findall(string[, pos[, endpos]]) --> list. - Return a list of all non-overlapping matches of pattern in string. - """ - return [str()] - - def finditer(self, string, pos=None, endpos=None): - """ - finditer(string[, pos[, endpos]]) --> iterator. - Return an iterator over all non-overlapping matches for the - RE pattern in string. For each match, the iterator returns a - match object. - """ - yield SRE_Match(self) - - def match(self, string, pos=None, endpos=None): - """ - match(string[, pos[, endpos]]) --> match object or None. - Matches zero or more characters at the beginning of the string - pattern - """ - return SRE_Match(self) - - def scanner(self, string, pos=None, endpos=None): - pass - - def search(self, string, pos=None, endpos=None): - """ - search(string[, pos[, endpos]]) --> match object or None. - Scan through string looking for a match, and return a corresponding - MatchObject instance. Return None if no position in the string matches. - """ - return SRE_Match(self) - - def split(self, string, maxsplit=0]): - """ - split(string[, maxsplit = 0]) --> list. - Split string by the occurrences of pattern. - """ - return [str()] - - def sub(self, repl, string, count=0): - """ - sub(repl, string[, count = 0]) --> newstring - Return the string obtained by replacing the leftmost non-overlapping - occurrences of pattern in string by the replacement repl. - """ - return str() - - def subn(self, repl, string, count=0): - """ - subn(repl, string[, count = 0]) --> (newstring, number of subs) - Return the tuple (new_string, number_of_subs_made) found by replacing - the leftmost non-overlapping occurrences of pattern with the - replacement repl. - """ - return (str(), int()) - - return SRE_Pattern() diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/compiled/fake/_weakref.pym b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/compiled/fake/_weakref.pym deleted file mode 100644 index 8d21a2c..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/compiled/fake/_weakref.pym +++ /dev/null @@ -1,8 +0,0 @@ -def proxy(object, callback=None): - return object - -class weakref(): - def __init__(self, object, callback=None): - self.__object = object - def __call__(self): - return self.__object diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/compiled/fake/builtins.pym b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/compiled/fake/builtins.pym deleted file mode 100644 index 1d5314b..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/compiled/fake/builtins.pym +++ /dev/null @@ -1,262 +0,0 @@ -""" -Pure Python implementation of some builtins. -This code is not going to be executed anywhere. -These implementations are not always correct, but should work as good as -possible for the auto completion. -""" - - -def next(iterator, default=None): - if random.choice([0, 1]): - if hasattr("next"): - return iterator.next() - else: - return iterator.__next__() - else: - if default is not None: - return default - - -def iter(collection, sentinel=None): - if sentinel: - yield collection() - else: - for c in collection: - yield c - - -def range(start, stop=None, step=1): - return [0] - - -class file(): - def __iter__(self): - yield '' - def next(self): - return '' - - -class xrange(): - # Attention: this function doesn't exist in Py3k (there it is range). - def __iter__(self): - yield 1 - - def count(self): - return 1 - - def index(self): - return 1 - - -def open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True): - import io - return io.TextIOWrapper(file, mode, buffering, encoding, errors, newline, closefd) - - -def open_python2(name, mode=None, buffering=None): - return file(name, mode, buffering) - - -#-------------------------------------------------------- -# descriptors -#-------------------------------------------------------- -class property(): - def __init__(self, fget, fset=None, fdel=None, doc=None): - self.fget = fget - self.fset = fset - self.fdel = fdel - self.__doc__ = doc - - def __get__(self, obj, cls): - return self.fget(obj) - - def __set__(self, obj, value): - self.fset(obj, value) - - def __delete__(self, obj): - self.fdel(obj) - - def setter(self, func): - self.fset = func - return self - - def getter(self, func): - self.fget = func - return self - - def deleter(self, func): - self.fdel = func - return self - - -class staticmethod(): - def __init__(self, func): - self.__func = func - - def __get__(self, obj, cls): - return self.__func - - -class classmethod(): - def __init__(self, func): - self.__func = func - - def __get__(self, obj, cls): - def _method(*args, **kwargs): - return self.__func(cls, *args, **kwargs) - return _method - - -#-------------------------------------------------------- -# array stuff -#-------------------------------------------------------- -class list(): - def __init__(self, iterable=[]): - self.__iterable = [] - for i in iterable: - self.__iterable += [i] - - def __iter__(self): - for i in self.__iterable: - yield i - - def __getitem__(self, y): - return self.__iterable[y] - - def pop(self): - return self.__iterable[int()] - - -class tuple(): - def __init__(self, iterable=[]): - self.__iterable = [] - for i in iterable: - self.__iterable += [i] - - def __iter__(self): - for i in self.__iterable: - yield i - - def __getitem__(self, y): - return self.__iterable[y] - - def index(self): - return 1 - - def count(self): - return 1 - - -class set(): - def __init__(self, iterable=[]): - self.__iterable = iterable - - def __iter__(self): - for i in self.__iterable: - yield i - - def pop(self): - return list(self.__iterable)[-1] - - def copy(self): - return self - - def difference(self, other): - return self - other - - def intersection(self, other): - return self & other - - def symmetric_difference(self, other): - return self ^ other - - def union(self, other): - return self | other - - -class frozenset(): - def __init__(self, iterable=[]): - self.__iterable = iterable - - def __iter__(self): - for i in self.__iterable: - yield i - - def copy(self): - return self - - -class dict(): - def __init__(self, **elements): - self.__elements = elements - - def clear(self): - # has a strange docstr - pass - - def get(self, k, d=None): - # TODO implement - try: - #return self.__elements[k] - pass - except KeyError: - return d - - def values(self): - return self.__elements.values() - - def setdefault(self, k, d): - # TODO maybe also return the content - return d - - -class enumerate(): - def __init__(self, sequence, start=0): - self.__sequence = sequence - - def __iter__(self): - for i in self.__sequence: - yield 1, i - - def __next__(self): - return next(self.__iter__()) - - def next(self): - return next(self.__iter__()) - - -class reversed(): - def __init__(self, sequence): - self.__sequence = sequence - - def __iter__(self): - for i in self.__sequence: - yield i - - def __next__(self): - return next(self.__iter__()) - - def next(self): - return next(self.__iter__()) - - -def sorted(iterable, cmp=None, key=None, reverse=False): - return iterable - - -#-------------------------------------------------------- -# basic types -#-------------------------------------------------------- -class int(): - def __init__(self, x, base=None): - pass - - -class str(): - def __init__(self, obj): - pass - - -class type(): - def mro(): - return [object] diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/compiled/fake/datetime.pym b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/compiled/fake/datetime.pym deleted file mode 100644 index 823ac5b..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/compiled/fake/datetime.pym +++ /dev/null @@ -1,4 +0,0 @@ -class datetime(): - @staticmethod - def now(): - return datetime() diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/compiled/fake/io.pym b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/compiled/fake/io.pym deleted file mode 100644 index 87b02ee..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/compiled/fake/io.pym +++ /dev/null @@ -1,6 +0,0 @@ -class TextIOWrapper(): - def __next__(self): - return str() - - def __iter__(self): - yield str() diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/compiled/fake/posix.pym b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/compiled/fake/posix.pym deleted file mode 100644 index 4417f7c..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/compiled/fake/posix.pym +++ /dev/null @@ -1,5 +0,0 @@ -def getcwd(): - return '' - -def getcwdu(): - return '' diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/compiled/mixed.py b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/compiled/mixed.py deleted file mode 100644 index 69119f1..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/compiled/mixed.py +++ /dev/null @@ -1,158 +0,0 @@ -""" -Used only for REPL Completion. -""" - -import inspect -import os - -from jedi import common -from jedi.parser.fast import FastParser -from jedi.evaluate import compiled -from jedi.cache import underscore_memoization - - -class MixedObject(object): - """ - A ``MixedObject`` is used in two ways: - - 1. It uses the default logic of ``parser.tree`` objects, - 2. except for getattr calls. The names dicts are generated in a fashion - like ``CompiledObject``. - - This combined logic makes it possible to provide more powerful REPL - completion. It allows side effects that are not noticable with the default - parser structure to still be completeable. - - The biggest difference from CompiledObject to MixedObject is that we are - generally dealing with Python code and not with C code. This will generate - fewer special cases, because we in Python you don't have the same freedoms - to modify the runtime. - """ - def __init__(self, evaluator, obj, node_name): - self._evaluator = evaluator - self.obj = obj - self.node_name = node_name - self.definition = node_name.get_definition() - - @property - def names_dict(self): - return LazyMixedNamesDict(self._evaluator, self) - - def names_dicts(self, search_global): - # TODO is this needed? - assert search_global is False - return [self.names_dict] - - def api_type(self): - mappings = { - 'expr_stmt': 'statement', - 'classdef': 'class', - 'funcdef': 'function', - 'file_input': 'module', - } - return mappings[self.definition.type] - - def __repr__(self): - return '<%s: %s>' % (type(self).__name__, repr(self.obj)) - - def __getattr__(self, name): - return getattr(self.definition, name) - - -class MixedName(compiled.CompiledName): - """ - The ``CompiledName._compiled_object`` is our MixedObject. - """ - @property - @underscore_memoization - def parent(self): - return create(self._evaluator, getattr(self._compiled_obj.obj, self.name)) - - @parent.setter - def parent(self, value): - pass # Just ignore this, Name tries to overwrite the parent attribute. - - @property - def start_pos(self): - if isinstance(self.parent, MixedObject): - return self.parent.node_name.start_pos - - # This means a start_pos that doesn't exist (compiled objects). - return (0, 0) - - -class LazyMixedNamesDict(compiled.LazyNamesDict): - name_class = MixedName - - -def parse(grammar, path): - with open(path) as f: - source = f.read() - source = common.source_to_unicode(source) - return FastParser(grammar, source, path) - - -def _load_module(evaluator, path, python_object): - module = parse(evaluator.grammar, path).module - python_module = inspect.getmodule(python_object) - - evaluator.modules[python_module.__name__] = module - return module - - -def find_syntax_node_name(evaluator, python_object): - try: - path = inspect.getsourcefile(python_object) - except TypeError: - # The type might not be known (e.g. class_with_dict.__weakref__) - return None - if path is None or not os.path.exists(path): - # The path might not exist or be e.g. . - return None - - module = _load_module(evaluator, path, python_object) - - if inspect.ismodule(python_object): - # We don't need to check names for modules, because there's not really - # a way to write a module in a module in Python (and also __name__ can - # be something like ``email.utils``). - return module - - name_str = python_object.__name__ - if name_str == '': - return None # It's too hard to find lambdas. - - names = module.used_names[name_str] - names = [n for n in names if n.is_definition()] - - try: - code = python_object.__code__ - # By using the line number of a code object we make the lookup in a - # file pretty easy. There's still a possibility of people defining - # stuff like ``a = 3; foo(a); a = 4`` on the same line, but if people - # do so we just don't care. - line_nr = code.co_firstlineno - except AttributeError: - pass - else: - line_names = [name for name in names if name.start_pos[0] == line_nr] - # There's a chance that the object is not available anymore, because - # the code has changed in the background. - if line_names: - return line_names[-1] - - # It's really hard to actually get the right definition, here as a last - # resort we just return the last one. This chance might lead to odd - # completions at some points but will lead to mostly correct type - # inference, because people tend to define a public name in a module only - # once. - return names[-1] - - -@compiled.compiled_objects_cache('mixed_cache') -def create(evaluator, obj): - name = find_syntax_node_name(evaluator, obj) - if name is None: - return compiled.create(evaluator, obj) - else: - return MixedObject(evaluator, obj, name) diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/docstrings.py b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/docstrings.py deleted file mode 100644 index d2ab34e..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/docstrings.py +++ /dev/null @@ -1,204 +0,0 @@ -""" -Docstrings are another source of information for functions and classes. -:mod:`jedi.evaluate.dynamic` tries to find all executions of functions, while -the docstring parsing is much easier. There are two different types of -docstrings that |jedi| understands: - -- `Sphinx `_ -- `Epydoc `_ - -For example, the sphinx annotation ``:type foo: str`` clearly states that the -type of ``foo`` is ``str``. - -As an addition to parameter searching, this module also provides return -annotations. -""" - -from ast import literal_eval -import re -from itertools import chain -from textwrap import dedent - -from jedi.evaluate.cache import memoize_default -from jedi.parser import ParserWithRecovery, load_grammar -from jedi.parser.tree import Class -from jedi.common import indent_block -from jedi.evaluate.iterable import Array, FakeSequence, AlreadyEvaluated - - -DOCSTRING_PARAM_PATTERNS = [ - r'\s*:type\s+%s:\s*([^\n]+)', # Sphinx - r'\s*:param\s+(\w+)\s+%s:[^\n]+', # Sphinx param with type - r'\s*@type\s+%s:\s*([^\n]+)', # Epydoc -] - -DOCSTRING_RETURN_PATTERNS = [ - re.compile(r'\s*:rtype:\s*([^\n]+)', re.M), # Sphinx - re.compile(r'\s*@rtype:\s*([^\n]+)', re.M), # Epydoc -] - -REST_ROLE_PATTERN = re.compile(r':[^`]+:`([^`]+)`') - - -try: - from numpydoc.docscrape import NumpyDocString -except ImportError: - def _search_param_in_numpydocstr(docstr, param_str): - return [] -else: - def _search_param_in_numpydocstr(docstr, param_str): - """Search `docstr` (in numpydoc format) for type(-s) of `param_str`.""" - params = NumpyDocString(docstr)._parsed_data['Parameters'] - for p_name, p_type, p_descr in params: - if p_name == param_str: - m = re.match('([^,]+(,[^,]+)*?)(,[ ]*optional)?$', p_type) - if m: - p_type = m.group(1) - - if p_type.startswith('{'): - types = set(type(x).__name__ for x in literal_eval(p_type)) - return list(types) - else: - return [p_type] - return [] - - -def _search_param_in_docstr(docstr, param_str): - """ - Search `docstr` for type(-s) of `param_str`. - - >>> _search_param_in_docstr(':type param: int', 'param') - ['int'] - >>> _search_param_in_docstr('@type param: int', 'param') - ['int'] - >>> _search_param_in_docstr( - ... ':type param: :class:`threading.Thread`', 'param') - ['threading.Thread'] - >>> bool(_search_param_in_docstr('no document', 'param')) - False - >>> _search_param_in_docstr(':param int param: some description', 'param') - ['int'] - - """ - # look at #40 to see definitions of those params - patterns = [re.compile(p % re.escape(param_str)) - for p in DOCSTRING_PARAM_PATTERNS] - for pattern in patterns: - match = pattern.search(docstr) - if match: - return [_strip_rst_role(match.group(1))] - - return (_search_param_in_numpydocstr(docstr, param_str) or - []) - - -def _strip_rst_role(type_str): - """ - Strip off the part looks like a ReST role in `type_str`. - - >>> _strip_rst_role(':class:`ClassName`') # strip off :class: - 'ClassName' - >>> _strip_rst_role(':py:obj:`module.Object`') # works with domain - 'module.Object' - >>> _strip_rst_role('ClassName') # do nothing when not ReST role - 'ClassName' - - See also: - http://sphinx-doc.org/domains.html#cross-referencing-python-objects - - """ - match = REST_ROLE_PATTERN.match(type_str) - if match: - return match.group(1) - else: - return type_str - - -def _evaluate_for_statement_string(evaluator, string, module): - code = dedent(""" - def pseudo_docstring_stuff(): - # Create a pseudo function for docstring statements. - %s - """) - if string is None: - return [] - - for element in re.findall('((?:\w+\.)*\w+)\.', string): - # Try to import module part in dotted name. - # (e.g., 'threading' in 'threading.Thread'). - string = 'import %s\n' % element + string - - # Take the default grammar here, if we load the Python 2.7 grammar here, it - # will be impossible to use `...` (Ellipsis) as a token. Docstring types - # don't need to conform with the current grammar. - p = ParserWithRecovery(load_grammar(), code % indent_block(string)) - try: - pseudo_cls = p.module.subscopes[0] - # First pick suite, then simple_stmt (-2 for DEDENT) and then the node, - # which is also not the last item, because there's a newline. - stmt = pseudo_cls.children[-1].children[-2].children[-2] - except (AttributeError, IndexError): - return [] - - # Use the module of the param. - # TODO this module is not the module of the param in case of a function - # call. In that case it's the module of the function call. - # stuffed with content from a function call. - pseudo_cls.parent = module - return list(_execute_types_in_stmt(evaluator, stmt)) - - -def _execute_types_in_stmt(evaluator, stmt): - """ - Executing all types or general elements that we find in a statement. This - doesn't include tuple, list and dict literals, because the stuff they - contain is executed. (Used as type information). - """ - definitions = evaluator.eval_element(stmt) - return chain.from_iterable(_execute_array_values(evaluator, d) for d in definitions) - - -def _execute_array_values(evaluator, array): - """ - Tuples indicate that there's not just one return value, but the listed - ones. `(str, int)` means that it returns a tuple with both types. - """ - if isinstance(array, Array): - values = [] - for types in array.py__iter__(): - objects = set(chain.from_iterable(_execute_array_values(evaluator, typ) for typ in types)) - values.append(AlreadyEvaluated(objects)) - return [FakeSequence(evaluator, values, array.type)] - else: - return evaluator.execute(array) - - -@memoize_default(None, evaluator_is_first_arg=True) -def follow_param(evaluator, param): - def eval_docstring(docstring): - return set( - [p for param_str in _search_param_in_docstr(docstring, str(param.name)) - for p in _evaluate_for_statement_string(evaluator, param_str, module)] - ) - func = param.parent_function - module = param.get_parent_until() - - types = eval_docstring(func.raw_doc) - if func.name.value == '__init__': - cls = func.get_parent_until(Class) - if cls.type == 'classdef': - types |= eval_docstring(cls.raw_doc) - - return types - - -@memoize_default(None, evaluator_is_first_arg=True) -def find_return_types(evaluator, func): - def search_return_in_docstr(code): - for p in DOCSTRING_RETURN_PATTERNS: - match = p.search(code) - if match: - return _strip_rst_role(match.group(1)) - - type_str = search_return_in_docstr(func.raw_doc) - return _evaluate_for_statement_string(evaluator, type_str, func.get_parent_until()) diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/dynamic.py b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/dynamic.py deleted file mode 100644 index d0570b5..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/dynamic.py +++ /dev/null @@ -1,149 +0,0 @@ -""" -One of the really important features of |jedi| is to have an option to -understand code like this:: - - def foo(bar): - bar. # completion here - foo(1) - -There's no doubt wheter bar is an ``int`` or not, but if there's also a call -like ``foo('str')``, what would happen? Well, we'll just show both. Because -that's what a human would expect. - -It works as follows: - -- |Jedi| sees a param -- search for function calls named ``foo`` -- execute these calls and check the input. This work with a ``ParamListener``. -""" -from itertools import chain - -from jedi._compatibility import unicode -from jedi.parser import tree -from jedi import settings -from jedi import debug -from jedi.evaluate.cache import memoize_default -from jedi.evaluate import imports - - -MAX_PARAM_SEARCHES = 20 - - -class ParamListener(object): - """ - This listener is used to get the params for a function. - """ - def __init__(self): - self.param_possibilities = [] - - def execute(self, params): - self.param_possibilities += params - - -@debug.increase_indent -def search_params(evaluator, param): - """ - A dynamic search for param values. If you try to complete a type: - - >>> def func(foo): - ... foo - >>> func(1) - >>> func("") - - It is not known what the type ``foo`` without analysing the whole code. You - have to look for all calls to ``func`` to find out what ``foo`` possibly - is. - """ - if not settings.dynamic_params: - return set() - - evaluator.dynamic_params_depth += 1 - try: - func = param.get_parent_until(tree.Function) - debug.dbg('Dynamic param search for %s in %s.', param, str(func.name), color='MAGENTA') - # Compare the param names. - names = [n for n in search_function_call(evaluator, func) - if n.value == param.name.value] - # Evaluate the ExecutedParams to types. - result = set(chain.from_iterable(n.parent.eval(evaluator) for n in names)) - debug.dbg('Dynamic param result %s', result, color='MAGENTA') - return result - finally: - evaluator.dynamic_params_depth -= 1 - - -@memoize_default([], evaluator_is_first_arg=True) -def search_function_call(evaluator, func): - """ - Returns a list of param names. - """ - from jedi.evaluate import representation as er - - def get_possible_nodes(module, func_name): - try: - names = module.used_names[func_name] - except KeyError: - return - - for name in names: - bracket = name.get_next_leaf() - trailer = bracket.parent - if trailer.type == 'trailer' and bracket == '(': - yield name, trailer - - def undecorate(typ): - # We have to remove decorators, because they are not the - # "original" functions, this way we can easily compare. - # At the same time we also have to remove InstanceElements. - if typ.isinstance(er.Function, er.Instance) \ - and typ.decorates is not None: - return typ.decorates - elif isinstance(typ, er.InstanceElement): - return typ.var - else: - return typ - - current_module = func.get_parent_until() - func_name = unicode(func.name) - compare = func - if func_name == '__init__': - cls = func.get_parent_scope() - if isinstance(cls, tree.Class): - func_name = unicode(cls.name) - compare = cls - - # add the listener - listener = ParamListener() - func.listeners.add(listener) - - try: - result = [] - i = 0 - for mod in imports.get_modules_containing_name(evaluator, [current_module], func_name): - for name, trailer in get_possible_nodes(mod, func_name): - i += 1 - - # This is a simple way to stop Jedi's dynamic param recursion - # from going wild: The deeper Jedi's in the recursin, the less - # code should be evaluated. - if i * evaluator.dynamic_params_depth > MAX_PARAM_SEARCHES: - return listener.param_possibilities - - for typ in evaluator.goto_definitions(name): - undecorated = undecorate(typ) - if evaluator.wrap(compare) == undecorated: - # Only if we have the correct function we execute - # it, otherwise just ignore it. - evaluator.eval_trailer([typ], trailer) - - result = listener.param_possibilities - - # If there are results after processing a module, we're probably - # good to process. - if result: - return result - finally: - # cleanup: remove the listener; important: should not stick. - func.listeners.remove(listener) - - return set() diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/finder.py b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/finder.py deleted file mode 100644 index 2095959..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/finder.py +++ /dev/null @@ -1,632 +0,0 @@ -""" -Searching for names with given scope and name. This is very central in Jedi and -Python. The name resolution is quite complicated with descripter, -``__getattribute__``, ``__getattr__``, ``global``, etc. - -If you want to understand name resolution, please read the first few chapters -in http://blog.ionelmc.ro/2015/02/09/understanding-python-metaclasses/. - -Flow checks -+++++++++++ - -Flow checks are not really mature. There's only a check for ``isinstance``. It -would check whether a flow has the form of ``if isinstance(a, type_or_tuple)``. -Unfortunately every other thing is being ignored (e.g. a == '' would be easy to -check for -> a is a string). There's big potential in these checks. -""" -from itertools import chain - -from jedi._compatibility import unicode -from jedi.parser import tree -from jedi import debug -from jedi import common -from jedi.common import unite -from jedi import settings -from jedi.evaluate import representation as er -from jedi.evaluate import dynamic -from jedi.evaluate import compiled -from jedi.evaluate import docstrings -from jedi.evaluate import pep0484 -from jedi.evaluate import iterable -from jedi.evaluate import imports -from jedi.evaluate import analysis -from jedi.evaluate import flow_analysis -from jedi.evaluate import param -from jedi.evaluate import helpers -from jedi.evaluate.cache import memoize_default - - -def filter_after_position(names, position): - """ - Removes all names after a certain position. If position is None, just - returns the names list. - """ - if position is None: - return names - - names_new = [] - for n in names: - # Filter positions and also allow list comprehensions and lambdas. - if n.start_pos[0] is not None and n.start_pos < position \ - or isinstance(n.get_definition(), (tree.CompFor, tree.Lambda)): - names_new.append(n) - return names_new - - -def filter_definition_names(names, origin, position=None): - """ - Filter names that are actual definitions in a scope. Names that are just - used will be ignored. - """ - if not names: - return [] - - # Just calculate the scope from the first - stmt = names[0].get_definition() - scope = stmt.get_parent_scope() - - if not (isinstance(scope, er.FunctionExecution) and - isinstance(scope.base, er.LambdaWrapper)): - names = filter_after_position(names, position) - names = [name for name in names if name.is_definition()] - - # Private name mangling (compile.c) disallows access on names - # preceeded by two underscores `__` if used outside of the class. Names - # that also end with two underscores (e.g. __id__) are not affected. - for name in list(names): - if name.value.startswith('__') and not name.value.endswith('__'): - if filter_private_variable(scope, origin): - names.remove(name) - return names - - -class NameFinder(object): - def __init__(self, evaluator, scope, name_str, position=None): - self._evaluator = evaluator - # Make sure that it's not just a syntax tree node. - self.scope = evaluator.wrap(scope) - self.name_str = name_str - self.position = position - self._found_predefined_if_name = None - - @debug.increase_indent - def find(self, scopes, attribute_lookup): - """ - :params bool attribute_lookup: Tell to logic if we're accessing the - attribute or the contents of e.g. a function. - """ - # TODO rename scopes to names_dicts - - names = self.filter_name(scopes) - if self._found_predefined_if_name is not None: - return self._found_predefined_if_name - - types = self._names_to_types(names, attribute_lookup) - - if not names and not types \ - and not (isinstance(self.name_str, tree.Name) and - isinstance(self.name_str.parent.parent, tree.Param)): - if not isinstance(self.name_str, (str, unicode)): # TODO Remove? - if attribute_lookup: - analysis.add_attribute_error(self._evaluator, - self.scope, self.name_str) - else: - message = ("NameError: name '%s' is not defined." - % self.name_str) - analysis.add(self._evaluator, 'name-error', self.name_str, - message) - - debug.dbg('finder._names_to_types: %s -> %s', names, types) - return types - - def scopes(self, search_global=False): - if search_global: - return global_names_dict_generator(self._evaluator, self.scope, self.position) - else: - return ((n, None) for n in self.scope.names_dicts(search_global)) - - def names_dict_lookup(self, names_dict, position): - def get_param(scope, el): - if isinstance(el.get_parent_until(tree.Param), tree.Param): - return scope.param_by_name(str(el)) - return el - - search_str = str(self.name_str) - try: - names = names_dict[search_str] - if not names: # We want names, otherwise stop. - return [] - except KeyError: - return [] - - names = filter_definition_names(names, self.name_str, position) - - name_scope = None - # Only the names defined in the last position are valid definitions. - last_names = [] - for name in reversed(sorted(names, key=lambda name: name.start_pos)): - stmt = name.get_definition() - name_scope = self._evaluator.wrap(stmt.get_parent_scope()) - - if isinstance(self.scope, er.Instance) and not isinstance(name_scope, er.Instance): - # Instances should not be checked for positioning, because we - # don't know in which order the functions are called. - last_names.append(name) - continue - - if isinstance(name_scope, compiled.CompiledObject): - # Let's test this. TODO need comment. shouldn't this be - # filtered before? - last_names.append(name) - continue - - if isinstance(stmt, er.ModuleWrapper): - # In case of REPL completion, we can infer modules names that - # don't really have a definition (because they are really just - # namespaces). In this case we can just add it. - last_names.append(name) - continue - - if isinstance(name, compiled.CompiledName) \ - or isinstance(name, er.InstanceName) and isinstance(name._origin_name, compiled.CompiledName): - last_names.append(name) - continue - - if isinstance(self.name_str, tree.Name): - origin_scope = self.name_str.get_parent_until(tree.Scope, reverse=True) - scope = self.name_str - check = None - while True: - scope = scope.parent - if scope.type in ("if_stmt", "for_stmt", "comp_for"): - try: - name_dict = self._evaluator.predefined_if_name_dict_dict[scope] - types = set(name_dict[str(self.name_str)]) - except KeyError: - continue - else: - if self.name_str.start_pos < scope.children[1].end_pos: - # It doesn't make any sense to check if - # statements in the if statement itself, just - # deliver types. - self._found_predefined_if_name = types - else: - check = flow_analysis.break_check(self._evaluator, self.scope, - origin_scope) - if check is flow_analysis.UNREACHABLE: - self._found_predefined_if_name = set() - else: - self._found_predefined_if_name = types - break - if isinstance(scope, tree.IsScope) or scope is None: - break - else: - origin_scope = None - - if isinstance(stmt.parent, compiled.CompiledObject): - # TODO seriously? this is stupid. - continue - check = flow_analysis.break_check(self._evaluator, name_scope, - stmt, origin_scope) - if check is not flow_analysis.UNREACHABLE: - last_names.append(name) - - if check is flow_analysis.REACHABLE: - break - - if isinstance(name_scope, er.FunctionExecution): - # Replace params - return [get_param(name_scope, n) for n in last_names] - return last_names - - def filter_name(self, names_dicts): - """ - Searches names that are defined in a scope (the different - `names_dicts`), until a name fits. - """ - names = [] - for names_dict, position in names_dicts: - names = self.names_dict_lookup(names_dict, position) - if names: - break - - debug.dbg('finder.filter_name "%s" in (%s): %s@%s', self.name_str, - self.scope, names, self.position) - return list(self._clean_names(names)) - - def _clean_names(self, names): - """ - ``NameFinder.filter_name`` should only output names with correct - wrapper parents. We don't want to see AST classes out in the - evaluation, so remove them already here! - """ - for n in names: - definition = n.parent - if isinstance(definition, (compiled.CompiledObject, - iterable.BuiltinMethod)): - # TODO this if should really be removed by changing the type of - # those classes. - yield n - elif definition.type in ('funcdef', 'classdef', 'file_input'): - yield self._evaluator.wrap(definition).name - else: - yield n - - def _check_getattr(self, inst): - """Checks for both __getattr__ and __getattribute__ methods""" - result = set() - # str is important, because it shouldn't be `Name`! - name = compiled.create(self._evaluator, str(self.name_str)) - with common.ignored(KeyError): - result = inst.execute_subscope_by_name('__getattr__', name) - if not result: - # This is a little bit special. `__getattribute__` is in Python - # executed before `__getattr__`. But: I know no use case, where - # this could be practical and where jedi would return wrong types. - # If you ever find something, let me know! - # We are inversing this, because a hand-crafted `__getattribute__` - # could still call another hand-crafted `__getattr__`, but not the - # other way around. - with common.ignored(KeyError): - result = inst.execute_subscope_by_name('__getattribute__', name) - return result - - def _names_to_types(self, names, attribute_lookup): - types = set() - - # Add isinstance and other if/assert knowledge. - if isinstance(self.name_str, tree.Name): - # Ignore FunctionExecution parents for now. - flow_scope = self.name_str - until = flow_scope.get_parent_until(er.FunctionExecution) - while not isinstance(until, er.FunctionExecution): - flow_scope = flow_scope.get_parent_scope(include_flows=True) - if flow_scope is None: - break - # TODO check if result is in scope -> no evaluation necessary - n = check_flow_information(self._evaluator, flow_scope, - self.name_str, self.position) - if n: - return n - - for name in names: - new_types = _name_to_types(self._evaluator, name, self.scope) - if isinstance(self.scope, (er.Class, er.Instance)) and attribute_lookup: - types |= set(self._resolve_descriptors(name, new_types)) - else: - types |= set(new_types) - if not names and isinstance(self.scope, er.Instance): - # handling __getattr__ / __getattribute__ - return self._check_getattr(self.scope) - - return types - - def _resolve_descriptors(self, name, types): - # The name must not be in the dictionary, but part of the class - # definition. __get__ is only called if the descriptor is defined in - # the class dictionary. - name_scope = name.get_definition().get_parent_scope() - if not isinstance(name_scope, (er.Instance, tree.Class)): - return types - - result = set() - for r in types: - try: - desc_return = r.get_descriptor_returns - except AttributeError: - result.add(r) - else: - result |= desc_return(self.scope) - return result - - -def _get_global_stmt_scopes(evaluator, global_stmt, name): - global_stmt_scope = global_stmt.get_parent_scope() - module = global_stmt_scope.get_parent_until() - for used_name in module.used_names[str(name)]: - if used_name.parent.type == 'global_stmt': - yield evaluator.wrap(used_name.get_parent_scope()) - - -@memoize_default(set(), evaluator_is_first_arg=True) -def _name_to_types(evaluator, name, scope): - types = [] - typ = name.get_definition() - if typ.isinstance(tree.ForStmt): - types = pep0484.find_type_from_comment_hint_for(evaluator, typ, name) - if types: - return types - if typ.isinstance(tree.WithStmt): - types = pep0484.find_type_from_comment_hint_with(evaluator, typ, name) - if types: - return types - if typ.isinstance(tree.ForStmt, tree.CompFor): - container_types = evaluator.eval_element(typ.children[3]) - for_types = iterable.py__iter__types(evaluator, container_types, typ.children[3]) - types = check_tuple_assignments(evaluator, for_types, name) - elif isinstance(typ, tree.Param): - types = _eval_param(evaluator, typ, scope) - elif typ.isinstance(tree.ExprStmt): - types = _remove_statements(evaluator, typ, name) - elif typ.isinstance(tree.WithStmt): - types = evaluator.eval_element(typ.node_from_name(name)) - elif isinstance(typ, tree.Import): - types = imports.ImportWrapper(evaluator, name).follow() - elif typ.type == 'global_stmt': - for s in _get_global_stmt_scopes(evaluator, typ, name): - finder = NameFinder(evaluator, s, str(name)) - names_dicts = finder.scopes(search_global=True) - # For global_stmt lookups, we only need the first possible scope, - # which means the function itself. - names_dicts = [next(names_dicts)] - types += finder.find(names_dicts, attribute_lookup=False) - elif isinstance(typ, tree.TryStmt): - # TODO an exception can also be a tuple. Check for those. - # TODO check for types that are not classes and add it to - # the static analysis report. - exceptions = evaluator.eval_element(name.get_previous_sibling().get_previous_sibling()) - types = set(chain.from_iterable(evaluator.execute(t) for t in exceptions)) - else: - if typ.isinstance(er.Function): - typ = typ.get_decorated_func() - types = set([typ]) - return types - - -def _remove_statements(evaluator, stmt, name): - """ - This is the part where statements are being stripped. - - Due to lazy evaluation, statements like a = func; b = a; b() have to be - evaluated. - """ - types = set() - # Remove the statement docstr stuff for now, that has to be - # implemented with the evaluator class. - #if stmt.docstr: - #res_new.append(stmt) - - check_instance = None - if isinstance(stmt, er.InstanceElement) and stmt.is_class_var: - check_instance = stmt.instance - stmt = stmt.var - - pep0484types = \ - pep0484.find_type_from_comment_hint_assign(evaluator, stmt, name) - if pep0484types: - return pep0484types - types |= evaluator.eval_statement(stmt, seek_name=name) - - if check_instance is not None: - # class renames - types = set([er.get_instance_el(evaluator, check_instance, a, True) - if isinstance(a, (er.Function, tree.Function)) - else a for a in types]) - return types - - -def _eval_param(evaluator, param, scope): - res_new = set() - func = param.get_parent_scope() - - cls = func.parent.get_parent_until((tree.Class, tree.Function)) - - from jedi.evaluate.param import ExecutedParam, Arguments - if isinstance(cls, tree.Class) and param.position_nr == 0 \ - and not isinstance(param, ExecutedParam): - # This is where we add self - if it has never been - # instantiated. - if isinstance(scope, er.InstanceElement): - res_new.add(scope.instance) - else: - inst = er.Instance(evaluator, evaluator.wrap(cls), - Arguments(evaluator, ()), is_generated=True) - res_new.add(inst) - return res_new - - # Instances are typically faked, if the instance is not called from - # outside. Here we check it for __init__ functions and return. - if isinstance(func, er.InstanceElement) \ - and func.instance.is_generated and str(func.name) == '__init__': - param = func.var.params[param.position_nr] - - # Add pep0484 and docstring knowledge. - pep0484_hints = pep0484.follow_param(evaluator, param) - doc_params = docstrings.follow_param(evaluator, param) - if pep0484_hints or doc_params: - return list(set(pep0484_hints) | set(doc_params)) - - if isinstance(param, ExecutedParam): - return res_new | param.eval(evaluator) - else: - # Param owns no information itself. - res_new |= dynamic.search_params(evaluator, param) - if not res_new: - if param.stars: - t = 'tuple' if param.stars == 1 else 'dict' - typ = list(evaluator.find_types(evaluator.BUILTINS, t))[0] - res_new = evaluator.execute(typ) - if param.default: - res_new |= evaluator.eval_element(param.default) - return res_new - - -def check_flow_information(evaluator, flow, search_name, pos): - """ Try to find out the type of a variable just with the information that - is given by the flows: e.g. It is also responsible for assert checks.:: - - if isinstance(k, str): - k. # <- completion here - - ensures that `k` is a string. - """ - if not settings.dynamic_flow_information: - return None - - result = set() - if flow.is_scope(): - # Check for asserts. - try: - names = reversed(flow.names_dict[search_name.value]) - except (KeyError, AttributeError): - names = [] - - for name in names: - ass = name.get_parent_until(tree.AssertStmt) - if isinstance(ass, tree.AssertStmt) and pos is not None and ass.start_pos < pos: - result = _check_isinstance_type(evaluator, ass.assertion(), search_name) - if result: - break - - if isinstance(flow, (tree.IfStmt, tree.WhileStmt)): - potential_ifs = [c for c in flow.children[1::4] if c != ':'] - for if_test in reversed(potential_ifs): - if search_name.start_pos > if_test.end_pos: - return _check_isinstance_type(evaluator, if_test, search_name) - return result - - -def _check_isinstance_type(evaluator, element, search_name): - try: - assert element.type in ('power', 'atom_expr') - # this might be removed if we analyze and, etc - assert len(element.children) == 2 - first, trailer = element.children - assert isinstance(first, tree.Name) and first.value == 'isinstance' - assert trailer.type == 'trailer' and trailer.children[0] == '(' - assert len(trailer.children) == 3 - - # arglist stuff - arglist = trailer.children[1] - args = param.Arguments(evaluator, arglist, trailer) - lst = list(args.unpack()) - # Disallow keyword arguments - assert len(lst) == 2 and lst[0][0] is None and lst[1][0] is None - name = lst[0][1][0] # first argument, values, first value - # Do a simple get_code comparison. They should just have the same code, - # and everything will be all right. - classes = lst[1][1][0] - call = helpers.call_of_leaf(search_name) - assert name.get_code(normalized=True) == call.get_code(normalized=True) - except AssertionError: - return set() - - result = set() - for cls_or_tup in evaluator.eval_element(classes): - if isinstance(cls_or_tup, iterable.Array) and cls_or_tup.type == 'tuple': - for typ in unite(cls_or_tup.py__iter__()): - result |= evaluator.execute(typ) - else: - result |= evaluator.execute(cls_or_tup) - return result - - -def global_names_dict_generator(evaluator, scope, position): - """ - For global name lookups. Yields tuples of (names_dict, position). If the - position is None, the position does not matter anymore in that scope. - - This function is used to include names from outer scopes. For example, when - the current scope is function: - - >>> from jedi._compatibility import u, no_unicode_pprint - >>> from jedi.parser import ParserWithRecovery, load_grammar - >>> parser = ParserWithRecovery(load_grammar(), u(''' - ... x = ['a', 'b', 'c'] - ... def func(): - ... y = None - ... ''')) - >>> scope = parser.module.subscopes[0] - >>> scope - - - `global_names_dict_generator` is a generator. First it yields names from - most inner scope. - - >>> from jedi.evaluate import Evaluator - >>> evaluator = Evaluator(load_grammar()) - >>> scope = evaluator.wrap(scope) - >>> pairs = list(global_names_dict_generator(evaluator, scope, (4, 0))) - >>> no_unicode_pprint(pairs[0]) - ({'func': [], 'y': []}, (4, 0)) - - Then it yields the names from one level "lower". In this example, this - is the most outer scope. As you can see, the position in the tuple is now - None, because typically the whole module is loaded before the function is - called. - - >>> no_unicode_pprint(pairs[1]) - ({'func': [], 'x': []}, None) - - After that we have a few underscore names that are part of the module. - - >>> sorted(pairs[2][0].keys()) - ['__doc__', '__file__', '__name__', '__package__'] - >>> pairs[3] # global names -> there are none in our example. - ({}, None) - >>> pairs[4] # package modules -> Also none. - ({}, None) - - Finally, it yields names from builtin, if `include_builtin` is - true (default). - - >>> pairs[5][0].values() #doctest: +ELLIPSIS - [[], ...] - """ - in_func = False - while scope is not None: - if not (scope.type == 'classdef' and in_func): - # Names in methods cannot be resolved within the class. - - for names_dict in scope.names_dicts(True): - yield names_dict, position - if hasattr(scope, 'resets_positions'): - # TODO This is so ugly, seriously. However there's - # currently no good way of influencing - # global_names_dict_generator when it comes to certain - # objects. - position = None - if scope.type == 'funcdef': - # The position should be reset if the current scope is a function. - in_func = True - position = None - scope = evaluator.wrap(scope.get_parent_scope()) - - # Add builtins to the global scope. - for names_dict in evaluator.BUILTINS.names_dicts(True): - yield names_dict, None - - -def check_tuple_assignments(evaluator, types, name): - """ - Checks if tuples are assigned. - """ - for index, node in name.assignment_indexes(): - iterated = iterable.py__iter__(evaluator, types, node) - for _ in range(index + 1): - try: - types = next(iterated) - except StopIteration: - # We could do this with the default param in next. But this - # would allow this loop to run for a very long time if the - # index number is high. Therefore break if the loop is - # finished. - types = set() - break - return types - - -def filter_private_variable(scope, origin_node): - """Check if a variable is defined inside the same class or outside.""" - instance = scope.get_parent_scope() - coming_from = origin_node - while coming_from is not None \ - and not isinstance(coming_from, (tree.Class, compiled.CompiledObject)): - coming_from = coming_from.get_parent_scope() - - # CompiledObjects don't have double underscore attributes, but Jedi abuses - # those for fakes (builtins.pym -> list). - if isinstance(instance, compiled.CompiledObject): - return instance != coming_from - else: - return isinstance(instance, er.Instance) and instance.base.base != coming_from diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/flow_analysis.py b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/flow_analysis.py deleted file mode 100644 index e188264..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/flow_analysis.py +++ /dev/null @@ -1,91 +0,0 @@ -from jedi.parser import tree - - -class Status(object): - lookup_table = {} - - def __init__(self, value, name): - self._value = value - self._name = name - Status.lookup_table[value] = self - - def invert(self): - if self is REACHABLE: - return UNREACHABLE - elif self is UNREACHABLE: - return REACHABLE - else: - return UNSURE - - def __and__(self, other): - if UNSURE in (self, other): - return UNSURE - else: - return REACHABLE if self._value and other._value else UNREACHABLE - - def __repr__(self): - return '<%s: %s>' % (type(self).__name__, self._name) - - -REACHABLE = Status(True, 'reachable') -UNREACHABLE = Status(False, 'unreachable') -UNSURE = Status(None, 'unsure') - - -def break_check(evaluator, base_scope, stmt, origin_scope=None): - element_scope = evaluator.wrap(stmt.get_parent_scope(include_flows=True)) - # Direct parents get resolved, we filter scopes that are separate branches. - # This makes sense for autocompletion and static analysis. For actual - # Python it doesn't matter, because we're talking about potentially - # unreachable code. - # e.g. `if 0:` would cause all name lookup within the flow make - # unaccessible. This is not a "problem" in Python, because the code is - # never called. In Jedi though, we still want to infer types. - while origin_scope is not None: - if element_scope == origin_scope: - return REACHABLE - origin_scope = origin_scope.parent - x = _break_check(evaluator, stmt, base_scope, element_scope) - return x - - -def _break_check(evaluator, stmt, base_scope, element_scope): - element_scope = evaluator.wrap(element_scope) - base_scope = evaluator.wrap(base_scope) - - reachable = REACHABLE - if isinstance(element_scope, tree.IfStmt): - if element_scope.node_after_else(stmt): - for check_node in element_scope.check_nodes(): - reachable = _check_if(evaluator, check_node) - if reachable in (REACHABLE, UNSURE): - break - reachable = reachable.invert() - else: - node = element_scope.node_in_which_check_node(stmt) - if node is not None: - reachable = _check_if(evaluator, node) - elif isinstance(element_scope, (tree.TryStmt, tree.WhileStmt)): - return UNSURE - - # Only reachable branches need to be examined further. - if reachable in (UNREACHABLE, UNSURE): - return reachable - - if element_scope.type == 'file_input': - # The definition is in another module and therefore just return what we - # have generated. - return reachable - if base_scope != element_scope and base_scope != element_scope.parent: - return reachable & _break_check(evaluator, stmt, base_scope, element_scope.parent) - else: - return reachable - - -def _check_if(evaluator, node): - types = evaluator.eval_element(node) - values = set(x.py__bool__() for x in types) - if len(values) == 1: - return Status.lookup_table[values.pop()] - else: - return UNSURE diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/helpers.py b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/helpers.py deleted file mode 100644 index 27293ed..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/helpers.py +++ /dev/null @@ -1,200 +0,0 @@ -import copy -from itertools import chain - -from jedi.parser import tree - - -def deep_ast_copy(obj, parent=None, new_elements=None): - """ - Much, much faster than copy.deepcopy, but just for Parser elements (Doesn't - copy parents). - """ - - if new_elements is None: - new_elements = {} - - def copy_node(obj): - # If it's already in the cache, just return it. - try: - return new_elements[obj] - except KeyError: - # Actually copy and set attributes. - new_obj = copy.copy(obj) - new_elements[obj] = new_obj - - # Copy children - new_children = [] - for child in obj.children: - typ = child.type - if typ in ('newline', 'operator', 'keyword', 'number', 'string', - 'indent', 'dedent', 'endmarker', 'error_leaf'): - # At the moment we're not actually copying those primitive - # elements, because there's really no need to. The parents are - # obviously wrong, but that's not an issue. - new_child = child - elif typ == 'name': - new_elements[child] = new_child = copy.copy(child) - new_child.parent = new_obj - else: # Is a BaseNode. - new_child = copy_node(child) - new_child.parent = new_obj - new_children.append(new_child) - new_obj.children = new_children - - # Copy the names_dict (if there is one). - try: - names_dict = obj.names_dict - except AttributeError: - pass - else: - try: - new_obj.names_dict = new_names_dict = {} - except AttributeError: # Impossible to set CompFor.names_dict - pass - else: - for string, names in names_dict.items(): - new_names_dict[string] = [new_elements[n] for n in names] - return new_obj - - if isinstance(obj, tree.BaseNode): - new_obj = copy_node(obj) - else: - # Special case of a Name object. - new_elements[obj] = new_obj = copy.copy(obj) - - if parent is not None: - new_obj.parent = parent - return new_obj - - -def call_of_leaf(leaf, cut_own_trailer=False): - """ - Creates a "call" node that consist of all ``trailer`` and ``power`` - objects. E.g. if you call it with ``append``:: - - list([]).append(3) or None - - You would get a node with the content ``list([]).append`` back. - - This generates a copy of the original ast node. - - If you're using the leaf, e.g. the bracket `)` it will return ``list([])``. - - # TODO remove cut_own_trailer option, since its always used with it. Just - # ignore it, It's not what we want anyway. Or document it better? - """ - trailer = leaf.parent - # The leaf may not be the last or first child, because there exist three - # different trailers: `( x )`, `[ x ]` and `.x`. In the first two examples - # we should not match anything more than x. - if trailer.type != 'trailer' or leaf not in (trailer.children[0], trailer.children[-1]): - if trailer.type == 'atom': - return trailer - return leaf - - power = trailer.parent - index = power.children.index(trailer) - power = deep_ast_copy(power) - if cut_own_trailer: - cut = index - else: - cut = index + 1 - power.children[cut:] = [] - - if power.type == 'error_node': - start = index - while True: - start -= 1 - if power.children[start].type != 'trailer': - break - transformed = tree.Node('power', power.children[start:]) - transformed.parent = power.parent - return transformed - - return power - - -def get_names_of_node(node): - try: - children = node.children - except AttributeError: - if node.type == 'name': - return [node] - else: - return [] - else: - return list(chain.from_iterable(get_names_of_node(c) for c in children)) - - -def get_module_names(module, all_scopes): - """ - Returns a dictionary with name parts as keys and their call paths as - values. - """ - if all_scopes: - dct = module.used_names - else: - dct = module.names_dict - return chain.from_iterable(dct.values()) - - -class FakeImport(tree.ImportName): - def __init__(self, name, parent, level=0): - super(FakeImport, self).__init__([]) - self.parent = parent - self._level = level - self.name = name - - def get_defined_names(self): - return [self.name] - - def aliases(self): - return {} - - @property - def level(self): - return self._level - - @property - def start_pos(self): - return 0, 0 - - def paths(self): - return [[self.name]] - - def is_definition(self): - return True - - -class FakeName(tree.Name): - def __init__(self, name_str, parent=None, start_pos=(0, 0), is_definition=None): - """ - In case is_definition is defined (not None), that bool value will be - returned. - """ - super(FakeName, self).__init__(tree.zero_position_modifier, name_str, start_pos) - self.parent = parent - self._is_definition = is_definition - - def get_definition(self): - return self.parent - - def is_definition(self): - if self._is_definition is None: - return super(FakeName, self).is_definition() - else: - return self._is_definition - - -class LazyName(FakeName): - def __init__(self, name, parent_callback, is_definition=None): - super(LazyName, self).__init__(name, is_definition=is_definition) - self._parent_callback = parent_callback - - @property - def parent(self): - return self._parent_callback() - - @parent.setter - def parent(self, value): - pass # Do nothing, super classes can try to set the parent. diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/imports.py b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/imports.py deleted file mode 100644 index d65d897..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/imports.py +++ /dev/null @@ -1,517 +0,0 @@ -""" -:mod:`jedi.evaluate.imports` is here to resolve import statements and return -the modules/classes/functions/whatever, which they stand for. However there's -not any actual importing done. This module is about finding modules in the -filesystem. This can be quite tricky sometimes, because Python imports are not -always that simple. - -This module uses imp for python up to 3.2 and importlib for python 3.3 on; the -correct implementation is delegated to _compatibility. - -This module also supports import autocompletion, which means to complete -statements like ``from datetim`` (curser at the end would return ``datetime``). -""" -import imp -import os -import pkgutil -import sys -from itertools import chain - -from jedi._compatibility import find_module, unicode -from jedi import common -from jedi import debug -from jedi.parser import fast -from jedi.parser import tree -from jedi.parser.utils import save_parser, load_parser, parser_cache -from jedi.evaluate import sys_path -from jedi.evaluate import helpers -from jedi import settings -from jedi.common import source_to_unicode -from jedi.evaluate import compiled -from jedi.evaluate import analysis -from jedi.evaluate.cache import memoize_default, NO_DEFAULT - - -def completion_names(evaluator, imp, pos): - name = imp.name_for_position(pos) - module = evaluator.wrap(imp.get_parent_until()) - if name is None: - level = 0 - for node in imp.children: - if node.end_pos <= pos: - if node in ('.', '...'): - level += len(node.value) - import_path = [] - else: - # Completion on an existing name. - - # The import path needs to be reduced by one, because we're completing. - import_path = imp.path_for_name(name)[:-1] - level = imp.level - - importer = Importer(evaluator, tuple(import_path), module, level) - if isinstance(imp, tree.ImportFrom): - c = imp.children - only_modules = c[c.index('import')].start_pos >= pos - else: - only_modules = True - return importer.completion_names(evaluator, only_modules) - - -class ImportWrapper(tree.Base): - def __init__(self, evaluator, name): - self._evaluator = evaluator - self._name = name - - self._import = name.get_parent_until(tree.Import) - self.import_path = self._import.path_for_name(name) - - @memoize_default() - def follow(self, is_goto=False): - module = self._evaluator.wrap(self._import.get_parent_until()) - import_path = self._import.path_for_name(self._name) - from_import_name = None - try: - from_names = self._import.get_from_names() - except AttributeError: - # Is an import_name - pass - else: - if len(from_names) + 1 == len(import_path): - # We have to fetch the from_names part first and then check - # if from_names exists in the modules. - from_import_name = import_path[-1] - import_path = from_names - - importer = Importer(self._evaluator, tuple(import_path), - module, self._import.level) - - types = importer.follow() - - #if self._import.is_nested() and not self.nested_resolve: - # scopes = [NestedImportModule(module, self._import)] - - if from_import_name is not None: - types = set(chain.from_iterable( - self._evaluator.find_types(t, unicode(from_import_name), - is_goto=is_goto) - for t in types)) - - if not types: - path = import_path + [from_import_name] - importer = Importer(self._evaluator, tuple(path), - module, self._import.level) - types = importer.follow() - # goto only accepts `Name` - if is_goto: - types = set(s.name for s in types) - else: - # goto only accepts `Name` - if is_goto: - types = set(s.name for s in types) - - debug.dbg('after import: %s', types) - return types - - -class NestedImportModule(tree.Module): - """ - TODO while there's no use case for nested import module right now, we might - be able to use them for static analysis checks later on. - """ - def __init__(self, module, nested_import): - self._module = module - self._nested_import = nested_import - - def _get_nested_import_name(self): - """ - Generates an Import statement, that can be used to fake nested imports. - """ - i = self._nested_import - # This is not an existing Import statement. Therefore, set position to - # 0 (0 is not a valid line number). - zero = (0, 0) - names = [unicode(name) for name in i.namespace_names[1:]] - name = helpers.FakeName(names, self._nested_import) - new = tree.Import(i._sub_module, zero, zero, name) - new.parent = self._module - debug.dbg('Generated a nested import: %s', new) - return helpers.FakeName(str(i.namespace_names[1]), new) - - def __getattr__(self, name): - return getattr(self._module, name) - - def __repr__(self): - return "<%s: %s of %s>" % (self.__class__.__name__, self._module, - self._nested_import) - - -def _add_error(evaluator, name, message=None): - if hasattr(name, 'parent'): - # Should be a name, not a string! - analysis.add(evaluator, 'import-error', name, message) - - -def get_init_path(directory_path): - """ - The __init__ file can be searched in a directory. If found return it, else - None. - """ - for suffix, _, _ in imp.get_suffixes(): - path = os.path.join(directory_path, '__init__' + suffix) - if os.path.exists(path): - return path - return None - - -class Importer(object): - def __init__(self, evaluator, import_path, module, level=0): - """ - An implementation similar to ``__import__``. Use `follow` - to actually follow the imports. - - *level* specifies whether to use absolute or relative imports. 0 (the - default) means only perform absolute imports. Positive values for level - indicate the number of parent directories to search relative to the - directory of the module calling ``__import__()`` (see PEP 328 for the - details). - - :param import_path: List of namespaces (strings or Names). - """ - debug.speed('import %s' % (import_path,)) - self._evaluator = evaluator - self.level = level - self.module = module - try: - self.file_path = module.py__file__() - except AttributeError: - # Can be None for certain compiled modules like 'builtins'. - self.file_path = None - - if level: - base = module.py__package__().split('.') - if base == ['']: - base = [] - if level > len(base): - path = module.py__file__() - if path is not None: - import_path = list(import_path) - for i in range(level): - path = os.path.dirname(path) - dir_name = os.path.basename(path) - # This is not the proper way to do relative imports. However, since - # Jedi cannot be sure about the entry point, we just calculate an - # absolute path here. - if dir_name: - import_path.insert(0, dir_name) - else: - _add_error(self._evaluator, import_path[-1]) - import_path = [] - # TODO add import error. - debug.warning('Attempted relative import beyond top-level package.') - else: - # Here we basically rewrite the level to 0. - import_path = tuple(base) + tuple(import_path) - self.import_path = import_path - - @property - def str_import_path(self): - """Returns the import path as pure strings instead of `Name`.""" - return tuple(str(name) for name in self.import_path) - - @memoize_default() - def sys_path_with_modifications(self): - in_path = [] - sys_path_mod = list(sys_path.sys_path_with_modifications(self._evaluator, self.module)) - if self.file_path is not None: - # If you edit e.g. gunicorn, there will be imports like this: - # `from gunicorn import something`. But gunicorn is not in the - # sys.path. Therefore look if gunicorn is a parent directory, #56. - if self.import_path: # TODO is this check really needed? - for path in sys_path.traverse_parents(self.file_path): - if os.path.basename(path) == self.str_import_path[0]: - in_path.append(os.path.dirname(path)) - - # Since we know nothing about the call location of the sys.path, - # it's a possibility that the current directory is the origin of - # the Python execution. - sys_path_mod.insert(0, os.path.dirname(self.file_path)) - - return in_path + sys_path_mod - - @memoize_default(NO_DEFAULT) - def follow(self): - if not self.import_path: - return set() - return self._do_import(self.import_path, self.sys_path_with_modifications()) - - def _do_import(self, import_path, sys_path): - """ - This method is very similar to importlib's `_gcd_import`. - """ - import_parts = [str(i) for i in import_path] - - # Handle "magic" Flask extension imports: - # ``flask.ext.foo`` is really ``flask_foo`` or ``flaskext.foo``. - if len(import_path) > 2 and import_parts[:2] == ['flask', 'ext']: - # New style. - ipath = ('flask_' + str(import_parts[2]),) + import_path[3:] - modules = self._do_import(ipath, sys_path) - if modules: - return modules - else: - # Old style - return self._do_import(('flaskext',) + import_path[2:], sys_path) - - module_name = '.'.join(import_parts) - try: - return set([self._evaluator.modules[module_name]]) - except KeyError: - pass - - if len(import_path) > 1: - # This is a recursive way of importing that works great with - # the module cache. - bases = self._do_import(import_path[:-1], sys_path) - if not bases: - return set() - # We can take the first element, because only the os special - # case yields multiple modules, which is not important for - # further imports. - parent_module = list(bases)[0] - - # This is a huge exception, we follow a nested import - # ``os.path``, because it's a very important one in Python - # that is being achieved by messing with ``sys.modules`` in - # ``os``. - if [str(i) for i in import_path] == ['os', 'path']: - return self._evaluator.find_types(parent_module, 'path') - - try: - paths = parent_module.py__path__() - except AttributeError: - # The module is not a package. - _add_error(self._evaluator, import_path[-1]) - return set() - else: - debug.dbg('search_module %s in paths %s', module_name, paths) - for path in paths: - # At the moment we are only using one path. So this is - # not important to be correct. - try: - module_file, module_path, is_pkg = \ - find_module(import_parts[-1], [path]) - break - except ImportError: - module_path = None - if module_path is None: - _add_error(self._evaluator, import_path[-1]) - return set() - else: - parent_module = None - try: - debug.dbg('search_module %s in %s', import_parts[-1], self.file_path) - # Override the sys.path. It works only good that way. - # Injecting the path directly into `find_module` did not work. - sys.path, temp = sys_path, sys.path - try: - module_file, module_path, is_pkg = \ - find_module(import_parts[-1]) - finally: - sys.path = temp - except ImportError: - # The module is not a package. - _add_error(self._evaluator, import_path[-1]) - return set() - - source = None - if is_pkg: - # In this case, we don't have a file yet. Search for the - # __init__ file. - if module_path.endswith(('.zip', '.egg')): - source = module_file.loader.get_source(module_name) - else: - module_path = get_init_path(module_path) - elif module_file: - source = module_file.read() - module_file.close() - - if module_file is None and not module_path.endswith(('.py', '.zip', '.egg')): - module = compiled.load_module(self._evaluator, module_path) - else: - module = _load_module(self._evaluator, module_path, source, sys_path, parent_module) - - if module is None: - # The file might raise an ImportError e.g. and therefore not be - # importable. - return set() - - self._evaluator.modules[module_name] = module - return set([module]) - - def _generate_name(self, name): - # Create a pseudo import to be able to follow them. - name = helpers.FakeName(name) - imp = helpers.FakeImport(name, parent=self.module) - name.parent = imp - return name - - def _get_module_names(self, search_path=None): - """ - Get the names of all modules in the search_path. This means file names - and not names defined in the files. - """ - - names = [] - # add builtin module names - if search_path is None: - names += [self._generate_name(name) for name in sys.builtin_module_names] - - if search_path is None: - search_path = self.sys_path_with_modifications() - for module_loader, name, is_pkg in pkgutil.iter_modules(search_path): - names.append(self._generate_name(name)) - return names - - def completion_names(self, evaluator, only_modules=False): - """ - :param only_modules: Indicates wheter it's possible to import a - definition that is not defined in a module. - """ - from jedi.evaluate import finder - names = [] - if self.import_path: - # flask - if self.str_import_path == ('flask', 'ext'): - # List Flask extensions like ``flask_foo`` - for mod in self._get_module_names(): - modname = str(mod) - if modname.startswith('flask_'): - extname = modname[len('flask_'):] - names.append(self._generate_name(extname)) - # Now the old style: ``flaskext.foo`` - for dir in self.sys_path_with_modifications(): - flaskext = os.path.join(dir, 'flaskext') - if os.path.isdir(flaskext): - names += self._get_module_names([flaskext]) - - for scope in self.follow(): - # Non-modules are not completable. - if not scope.type == 'file_input': # not a module - continue - - # namespace packages - if isinstance(scope, tree.Module) and scope.path.endswith('__init__.py'): - paths = scope.py__path__() - names += self._get_module_names(paths) - - if only_modules: - # In the case of an import like `from x.` we don't need to - # add all the variables. - if ('os',) == self.str_import_path and not self.level: - # os.path is a hardcoded exception, because it's a - # ``sys.modules`` modification. - names.append(self._generate_name('path')) - - continue - - for names_dict in scope.names_dicts(search_global=False): - _names = list(chain.from_iterable(names_dict.values())) - if not _names: - continue - _names = finder.filter_definition_names(_names, scope) - names += _names - else: - # Empty import path=completion after import - if not self.level: - names += self._get_module_names() - - if self.file_path is not None: - path = os.path.abspath(self.file_path) - for i in range(self.level - 1): - path = os.path.dirname(path) - names += self._get_module_names([path]) - - return names - - -def _load_module(evaluator, path=None, source=None, sys_path=None, parent_module=None): - def load(source): - dotted_path = path and compiled.dotted_from_fs_path(path, sys_path) - if path is not None and path.endswith(('.py', '.zip', '.egg')) \ - and dotted_path not in settings.auto_import_modules: - if source is None: - with open(path, 'rb') as f: - source = f.read() - else: - return compiled.load_module(evaluator, path) - p = path - p = fast.FastParser(evaluator.grammar, common.source_to_unicode(source), p) - save_parser(path, p) - from jedi.evaluate.representation import ModuleWrapper - return ModuleWrapper(evaluator, p.module, parent_module) - - if sys_path is None: - sys_path = evaluator.sys_path - - cached = load_parser(path) - module = load(source) if cached is None else cached.module - module = evaluator.wrap(module) - return module - - -def add_module(evaluator, module_name, module): - if '.' not in module_name: - # We cannot add paths with dots, because that would collide with - # the sepatator dots for nested packages. Therefore we return - # `__main__` in ModuleWrapper.py__name__(), which is similar to - # Python behavior. - evaluator.modules[module_name] = module - - -def get_modules_containing_name(evaluator, mods, name): - """ - Search a name in the directories of modules. - """ - def check_python_file(path): - try: - return parser_cache[path].parser.module - except KeyError: - try: - return check_fs(path) - except IOError: - return None - - def check_fs(path): - with open(path, 'rb') as f: - source = source_to_unicode(f.read()) - if name in source: - module_name = os.path.basename(path)[:-3] # Remove `.py`. - module = _load_module(evaluator, path, source) - add_module(evaluator, module_name, module) - return module - - # skip non python modules - mods = set(m for m in mods if not isinstance(m, compiled.CompiledObject)) - mod_paths = set() - for m in mods: - mod_paths.add(m.path) - yield m - - if settings.dynamic_params_for_other_modules: - paths = set(settings.additional_dynamic_modules) - for p in mod_paths: - if p is not None: - # We need abspath, because the seetings paths might not already - # have been converted to absolute paths. - d = os.path.dirname(os.path.abspath(p)) - for entry in os.listdir(d): - if entry not in mod_paths: - if entry.endswith('.py'): - paths.add(d + os.path.sep + entry) - - for p in sorted(paths): - # make testing easier, sort it - same results on every interpreter - c = check_python_file(p) - if c is not None and c not in mods and not isinstance(c, compiled.CompiledObject): - yield c diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/iterable.py b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/iterable.py deleted file mode 100644 index 79a1a0e..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/iterable.py +++ /dev/null @@ -1,863 +0,0 @@ -""" -Contains all classes and functions to deal with lists, dicts, generators and -iterators in general. - -Array modifications -******************* - -If the content of an array (``set``/``list``) is requested somewhere, the -current module will be checked for appearances of ``arr.append``, -``arr.insert``, etc. If the ``arr`` name points to an actual array, the -content will be added - -This can be really cpu intensive, as you can imagine. Because |jedi| has to -follow **every** ``append`` and check wheter it's the right array. However this -works pretty good, because in *slow* cases, the recursion detector and other -settings will stop this process. - -It is important to note that: - -1. Array modfications work only in the current module. -2. Jedi only checks Array additions; ``list.pop``, etc are ignored. -""" -from jedi.common import unite, safe_property -from jedi import debug -from jedi import settings -from jedi._compatibility import use_metaclass, unicode, zip_longest -from jedi.parser import tree -from jedi.evaluate import compiled -from jedi.evaluate import helpers -from jedi.evaluate.cache import CachedMetaClass, memoize_default -from jedi.evaluate import analysis -from jedi.evaluate import pep0484 -from jedi import common - - -class IterableWrapper(tree.Base): - def is_class(self): - return False - - @memoize_default() - def _get_names_dict(self, names_dict): - builtin_methods = {} - for cls in reversed(type(self).mro()): - try: - builtin_methods.update(cls.builtin_methods) - except AttributeError: - pass - - if not builtin_methods: - return names_dict - - dct = {} - for names in names_dict.values(): - for name in names: - name_str = name.value - try: - method = builtin_methods[name_str, self.type] - except KeyError: - dct[name_str] = [name] - else: - parent = BuiltinMethod(self, method, name.parent) - dct[name_str] = [helpers.FakeName(name_str, parent, is_definition=True)] - return dct - - -class BuiltinMethod(IterableWrapper): - """``Generator.__next__`` ``dict.values`` methods and so on.""" - def __init__(self, builtin, method, builtin_func): - self._builtin = builtin - self._method = method - self._builtin_func = builtin_func - - def py__call__(self, params): - return self._method(self._builtin) - - def __getattr__(self, name): - return getattr(self._builtin_func, name) - - -def has_builtin_methods(cls): - cls.builtin_methods = {} - for func in cls.__dict__.values(): - try: - cls.builtin_methods.update(func.registered_builtin_methods) - except AttributeError: - pass - return cls - - -def register_builtin_method(method_name, type=None): - def wrapper(func): - dct = func.__dict__.setdefault('registered_builtin_methods', {}) - dct[method_name, type] = func - return func - return wrapper - - -@has_builtin_methods -class GeneratorMixin(object): - type = None - - @register_builtin_method('send') - @register_builtin_method('next') - @register_builtin_method('__next__') - def py__next__(self): - # TODO add TypeError if params are given. - return unite(self.py__iter__()) - - @memoize_default() - def names_dicts(self, search_global=False): # is always False - gen_obj = compiled.get_special_object(self._evaluator, 'GENERATOR_OBJECT') - yield self._get_names_dict(gen_obj.names_dict) - - def py__bool__(self): - return True - - def py__class__(self): - gen_obj = compiled.get_special_object(self._evaluator, 'GENERATOR_OBJECT') - return gen_obj.py__class__() - - -class Generator(use_metaclass(CachedMetaClass, IterableWrapper, GeneratorMixin)): - """Handling of `yield` functions.""" - - def __init__(self, evaluator, func, var_args): - super(Generator, self).__init__() - self._evaluator = evaluator - self.func = func - self.var_args = var_args - - def py__iter__(self): - from jedi.evaluate.representation import FunctionExecution - f = FunctionExecution(self._evaluator, self.func, self.var_args) - return f.get_yield_types() - - def __getattr__(self, name): - if name not in ['start_pos', 'end_pos', 'parent', 'get_imports', - 'doc', 'docstr', 'get_parent_until', - 'get_code', 'subscopes']: - raise AttributeError("Accessing %s of %s is not allowed." - % (self, name)) - return getattr(self.func, name) - - def __repr__(self): - return "<%s of %s>" % (type(self).__name__, self.func) - - -class Comprehension(IterableWrapper): - @staticmethod - def from_atom(evaluator, atom): - bracket = atom.children[0] - if bracket == '{': - if atom.children[1].children[1] == ':': - cls = DictComprehension - else: - cls = SetComprehension - elif bracket == '(': - cls = GeneratorComprehension - elif bracket == '[': - cls = ListComprehension - return cls(evaluator, atom) - - def __init__(self, evaluator, atom): - self._evaluator = evaluator - self._atom = atom - - def _get_comprehension(self): - # The atom contains a testlist_comp - return self._atom.children[1] - - def _get_comp_for(self): - # The atom contains a testlist_comp - return self._get_comprehension().children[1] - - @memoize_default() - def _eval_node(self, index=0): - """ - The first part `x + 1` of the list comprehension: - - [x + 1 for x in foo] - """ - comp_for = self._get_comp_for() - # For nested comprehensions we need to search the last one. - from jedi.evaluate.representation import InstanceElement - node = self._get_comprehension().children[index] - if isinstance(node, InstanceElement): - # This seems to be a strange case that I haven't found a way to - # write tests against. However since it's my new goal to get rid of - # InstanceElement anyway, I don't care. - node = node.var - last_comp = list(comp_for.get_comp_fors())[-1] - return helpers.deep_ast_copy(node, parent=last_comp) - - def _nested(self, comp_fors): - evaluator = self._evaluator - comp_for = comp_fors[0] - input_node = comp_for.children[3] - input_types = evaluator.eval_element(input_node) - - iterated = py__iter__(evaluator, input_types, input_node) - exprlist = comp_for.children[1] - for i, types in enumerate(iterated): - evaluator.predefined_if_name_dict_dict[comp_for] = \ - unpack_tuple_to_dict(evaluator, types, exprlist) - try: - for result in self._nested(comp_fors[1:]): - yield result - except IndexError: - iterated = evaluator.eval_element(self._eval_node()) - if self.type == 'dict': - yield iterated, evaluator.eval_element(self._eval_node(2)) - else: - yield iterated - finally: - del evaluator.predefined_if_name_dict_dict[comp_for] - - @memoize_default(default=[]) - @common.to_list - def _iterate(self): - comp_fors = tuple(self._get_comp_for().get_comp_fors()) - for result in self._nested(comp_fors): - yield result - - def py__iter__(self): - return self._iterate() - - def __repr__(self): - return "<%s of %s>" % (type(self).__name__, self._atom) - - -@has_builtin_methods -class ArrayMixin(object): - @memoize_default() - def names_dicts(self, search_global=False): # Always False. - # `array.type` is a string with the type, e.g. 'list'. - scope = compiled.builtin_from_name(self._evaluator, self.type) - # builtins only have one class -> [0] - scopes = self._evaluator.execute_evaluated(scope, self) - names_dicts = list(scopes)[0].names_dicts(search_global) - #yield names_dicts[0] - yield self._get_names_dict(names_dicts[1]) - - def py__bool__(self): - return None # We don't know the length, because of appends. - - def py__class__(self): - return compiled.builtin_from_name(self._evaluator, self.type) - - @safe_property - def parent(self): - return self._evaluator.BUILTINS - - @property - def name(self): - return FakeSequence(self._evaluator, [], self.type).name - - @memoize_default() - def dict_values(self): - return unite(self._evaluator.eval_element(v) for k, v in self._items()) - - @register_builtin_method('values', type='dict') - def _imitate_values(self): - items = self.dict_values() - return create_evaluated_sequence_set(self._evaluator, items, sequence_type='list') - #return set([FakeSequence(self._evaluator, [AlreadyEvaluated(items)], 'tuple')]) - - @register_builtin_method('items', type='dict') - def _imitate_items(self): - items = [set([FakeSequence(self._evaluator, (k, v), 'tuple')]) - for k, v in self._items()] - - return create_evaluated_sequence_set(self._evaluator, *items, sequence_type='list') - - -class ListComprehension(Comprehension, ArrayMixin): - type = 'list' - - def py__getitem__(self, index): - all_types = list(self.py__iter__()) - result = all_types[index] - if isinstance(index, slice): - return create_evaluated_sequence_set( - self._evaluator, - unite(result), - sequence_type='list' - ) - return result - - -class SetComprehension(Comprehension, ArrayMixin): - type = 'set' - - -@has_builtin_methods -class DictComprehension(Comprehension, ArrayMixin): - type = 'dict' - - def _get_comp_for(self): - return self._get_comprehension().children[3] - - def py__iter__(self): - for keys, values in self._iterate(): - yield keys - - def py__getitem__(self, index): - for keys, values in self._iterate(): - for k in keys: - if isinstance(k, compiled.CompiledObject): - if k.obj == index: - return values - return self.dict_values() - - def dict_values(self): - return unite(values for keys, values in self._iterate()) - - @register_builtin_method('items', type='dict') - def _imitate_items(self): - items = set(FakeSequence(self._evaluator, - (AlreadyEvaluated(keys), AlreadyEvaluated(values)), 'tuple') - for keys, values in self._iterate()) - - return create_evaluated_sequence_set(self._evaluator, items, sequence_type='list') - - -class GeneratorComprehension(Comprehension, GeneratorMixin): - pass - - -class Array(IterableWrapper, ArrayMixin): - mapping = {'(': 'tuple', - '[': 'list', - '{': 'dict'} - - def __init__(self, evaluator, atom): - self._evaluator = evaluator - self.atom = atom - self.type = Array.mapping[atom.children[0]] - """The builtin name of the array (list, set, tuple or dict).""" - - c = self.atom.children - array_node = c[1] - if self.type == 'dict' and array_node != '}' \ - and (not hasattr(array_node, 'children') - or ':' not in array_node.children): - self.type = 'set' - - @property - def name(self): - return helpers.FakeName(self.type, parent=self) - - def py__getitem__(self, index): - """Here the index is an int/str. Raises IndexError/KeyError.""" - if self.type == 'dict': - for key, value in self._items(): - for k in self._evaluator.eval_element(key): - if isinstance(k, compiled.CompiledObject) \ - and index == k.obj: - return self._evaluator.eval_element(value) - raise KeyError('No key found in dictionary %s.' % self) - - # Can raise an IndexError - if isinstance(index, slice): - return set([self]) - else: - return self._evaluator.eval_element(self._items()[index]) - - def __getattr__(self, name): - if name not in ['start_pos', 'get_only_subelement', 'parent', - 'get_parent_until', 'items']: - raise AttributeError('Strange access on %s: %s.' % (self, name)) - return getattr(self.atom, name) - - # @memoize_default() - def py__iter__(self): - """ - While values returns the possible values for any array field, this - function returns the value for a certain index. - """ - if self.type == 'dict': - # Get keys. - types = set() - for k, _ in self._items(): - types |= self._evaluator.eval_element(k) - # We don't know which dict index comes first, therefore always - # yield all the types. - for _ in types: - yield types - else: - for value in self._items(): - yield self._evaluator.eval_element(value) - - additions = check_array_additions(self._evaluator, self) - if additions: - yield additions - - def _values(self): - """Returns a list of a list of node.""" - if self.type == 'dict': - return unite(v for k, v in self._items()) - else: - return self._items() - - def _items(self): - c = self.atom.children - array_node = c[1] - if array_node in (']', '}', ')'): - return [] # Direct closing bracket, doesn't contain items. - - if tree.is_node(array_node, 'testlist_comp'): - return array_node.children[::2] - elif tree.is_node(array_node, 'dictorsetmaker'): - kv = [] - iterator = iter(array_node.children) - for key in iterator: - op = next(iterator, None) - if op is None or op == ',': - kv.append(key) # A set. - else: - assert op == ':' # A dict. - kv.append((key, next(iterator))) - next(iterator, None) # Possible comma. - return kv - else: - return [array_node] - - def __repr__(self): - return "<%s of %s>" % (type(self).__name__, self.atom) - - -class _FakeArray(Array): - def __init__(self, evaluator, container, type): - self.type = type - self._evaluator = evaluator - self.atom = container - - -class ImplicitTuple(_FakeArray): - def __init__(self, evaluator, testlist): - super(ImplicitTuple, self).__init__(evaluator, testlist, 'tuple') - self._testlist = testlist - - def _items(self): - return self._testlist.children[::2] - - -class FakeSequence(_FakeArray): - def __init__(self, evaluator, sequence_values, type): - """ - type should be one of "tuple", "list" - """ - super(FakeSequence, self).__init__(evaluator, sequence_values, type) - self._sequence_values = sequence_values - - def _items(self): - return self._sequence_values - - -def create_evaluated_sequence_set(evaluator, *types_order, **kwargs): - """ - ``sequence_type`` is a named argument, that doesn't work in Python2. For backwards - compatibility reasons, we're now using kwargs. - """ - sequence_type = kwargs.pop('sequence_type') - assert not kwargs - - sets = tuple(AlreadyEvaluated(types) for types in types_order) - return set([FakeSequence(evaluator, sets, sequence_type)]) - - -class AlreadyEvaluated(frozenset): - """A simple container to add already evaluated objects to an array.""" - def get_code(self, normalized=False): - # For debugging purposes. - return str(self) - - -class MergedNodes(frozenset): - pass - - -class FakeDict(_FakeArray): - def __init__(self, evaluator, dct): - super(FakeDict, self).__init__(evaluator, dct, 'dict') - self._dct = dct - - def py__iter__(self): - yield set(compiled.create(self._evaluator, key) for key in self._dct) - - def py__getitem__(self, index): - return unite(self._evaluator.eval_element(v) for v in self._dct[index]) - - def _items(self): - for key, values in self._dct.items(): - # TODO this is not proper. The values could be multiple values?! - yield key, values[0] - - -class MergedArray(_FakeArray): - def __init__(self, evaluator, arrays): - super(MergedArray, self).__init__(evaluator, arrays, arrays[-1].type) - self._arrays = arrays - - def py__iter__(self): - for array in self._arrays: - for types in array.py__iter__(): - yield types - - def py__getitem__(self, index): - return unite(self.py__iter__()) - - def _items(self): - for array in self._arrays: - for a in array._items(): - yield a - - def __len__(self): - return sum(len(a) for a in self._arrays) - - -def unpack_tuple_to_dict(evaluator, types, exprlist): - """ - Unpacking tuple assignments in for statements and expr_stmts. - """ - if exprlist.type == 'name': - return {exprlist.value: types} - elif exprlist.type == 'atom' and exprlist.children[0] in '([': - return unpack_tuple_to_dict(evaluator, types, exprlist.children[1]) - elif exprlist.type in ('testlist', 'testlist_comp', 'exprlist', - 'testlist_star_expr'): - dct = {} - parts = iter(exprlist.children[::2]) - n = 0 - for iter_types in py__iter__(evaluator, types, exprlist): - n += 1 - try: - part = next(parts) - except StopIteration: - analysis.add(evaluator, 'value-error-too-many-values', part, - message="ValueError: too many values to unpack (expected %s)" % n) - else: - dct.update(unpack_tuple_to_dict(evaluator, iter_types, part)) - has_parts = next(parts, None) - if types and has_parts is not None: - analysis.add(evaluator, 'value-error-too-few-values', has_parts, - message="ValueError: need more than %s values to unpack" % n) - return dct - elif exprlist.type == 'power' or exprlist.type == 'atom_expr': - # Something like ``arr[x], var = ...``. - # This is something that is not yet supported, would also be difficult - # to write into a dict. - return {} - elif exprlist.type == 'star_expr': # `a, *b, c = x` type unpackings - # Currently we're not supporting them. - return {} - raise NotImplementedError - - -def py__iter__(evaluator, types, node=None): - debug.dbg('py__iter__') - type_iters = [] - for typ in types: - try: - iter_method = typ.py__iter__ - except AttributeError: - if node is not None: - analysis.add(evaluator, 'type-error-not-iterable', node, - message="TypeError: '%s' object is not iterable" % typ) - else: - type_iters.append(iter_method()) - #for result in iter_method(): - #yield result - - for t in zip_longest(*type_iters, fillvalue=set()): - yield unite(t) - - -def py__iter__types(evaluator, types, node=None): - """ - Calls `py__iter__`, but ignores the ordering in the end and just returns - all types that it contains. - """ - return unite(py__iter__(evaluator, types, node)) - - -def py__getitem__(evaluator, types, trailer): - from jedi.evaluate.representation import Class - result = set() - - trailer_op, node, trailer_cl = trailer.children - assert trailer_op == "[" - assert trailer_cl == "]" - - # special case: PEP0484 typing module, see - # https://github.com/davidhalter/jedi/issues/663 - for typ in list(types): - if isinstance(typ, Class): - typing_module_types = \ - pep0484.get_types_for_typing_module(evaluator, typ, node) - if typing_module_types is not None: - types.remove(typ) - result |= typing_module_types - - if not types: - # all consumed by special cases - return result - - for index in create_index_types(evaluator, node): - if isinstance(index, (compiled.CompiledObject, Slice)): - index = index.obj - - if type(index) not in (float, int, str, unicode, slice): - # If the index is not clearly defined, we have to get all the - # possiblities. - for typ in list(types): - if isinstance(typ, Array) and typ.type == 'dict': - types.remove(typ) - result |= typ.dict_values() - return result | py__iter__types(evaluator, types) - - for typ in types: - # The actual getitem call. - try: - getitem = typ.py__getitem__ - except AttributeError: - analysis.add(evaluator, 'type-error-not-subscriptable', trailer_op, - message="TypeError: '%s' object is not subscriptable" % typ) - else: - try: - result |= getitem(index) - except IndexError: - result |= py__iter__types(evaluator, set([typ])) - except KeyError: - # Must be a dict. Lists don't raise KeyErrors. - result |= typ.dict_values() - return result - - -def check_array_additions(evaluator, array): - """ Just a mapper function for the internal _check_array_additions """ - if array.type not in ('list', 'set'): - # TODO also check for dict updates - return set() - - is_list = array.type == 'list' - try: - current_module = array.atom.get_parent_until() - except AttributeError: - # If there's no get_parent_until, it's a FakeSequence or another Fake - # type. Those fake types are used inside Jedi's engine. No values may - # be added to those after their creation. - return set() - return _check_array_additions(evaluator, array, current_module, is_list) - - -@memoize_default(default=set(), evaluator_is_first_arg=True) -@debug.increase_indent -def _check_array_additions(evaluator, compare_array, module, is_list): - """ - Checks if a `Array` has "add" (append, insert, extend) statements: - - >>> a = [""] - >>> a.append(1) - """ - debug.dbg('Dynamic array search for %s' % compare_array, color='MAGENTA') - if not settings.dynamic_array_additions or isinstance(module, compiled.CompiledObject): - debug.dbg('Dynamic array search aborted.', color='MAGENTA') - return set() - - def check_additions(arglist, add_name): - params = list(param.Arguments(evaluator, arglist).unpack()) - result = set() - if add_name in ['insert']: - params = params[1:] - if add_name in ['append', 'add', 'insert']: - for key, nodes in params: - result |= unite(evaluator.eval_element(node) for node in nodes) - elif add_name in ['extend', 'update']: - for key, nodes in params: - for node in nodes: - types = evaluator.eval_element(node) - result |= py__iter__types(evaluator, types, node) - return result - - from jedi.evaluate import representation as er, param - - def get_execution_parent(element): - """ Used to get an Instance/FunctionExecution parent """ - if isinstance(element, Array): - node = element.atom - else: - # Is an Instance with an - # Arguments([AlreadyEvaluated([_ArrayInstance])]) inside - # Yeah... I know... It's complicated ;-) - node = list(element.var_args.argument_node[0])[0].var_args.trailer - if isinstance(node, er.InstanceElement) or node is None: - return node - return node.get_parent_until(er.FunctionExecution) - - temp_param_add, settings.dynamic_params_for_other_modules = \ - settings.dynamic_params_for_other_modules, False - - search_names = ['append', 'extend', 'insert'] if is_list else ['add', 'update'] - comp_arr_parent = get_execution_parent(compare_array) - - added_types = set() - for add_name in search_names: - try: - possible_names = module.used_names[add_name] - except KeyError: - continue - else: - for name in possible_names: - # Check if the original scope is an execution. If it is, one - # can search for the same statement, that is in the module - # dict. Executions are somewhat special in jedi, since they - # literally copy the contents of a function. - if isinstance(comp_arr_parent, er.FunctionExecution): - if comp_arr_parent.start_pos < name.start_pos < comp_arr_parent.end_pos: - name = comp_arr_parent.name_for_position(name.start_pos) - else: - # Don't check definitions that are not defined in the - # same function. This is not "proper" anyway. It also - # improves Jedi's speed for array lookups, since we - # don't have to check the whole source tree anymore. - continue - trailer = name.parent - power = trailer.parent - trailer_pos = power.children.index(trailer) - try: - execution_trailer = power.children[trailer_pos + 1] - except IndexError: - continue - else: - if execution_trailer.type != 'trailer' \ - or execution_trailer.children[0] != '(' \ - or execution_trailer.children[1] == ')': - continue - power = helpers.call_of_leaf(name, cut_own_trailer=True) - # InstanceElements are special, because they don't get copied, - # but have this wrapper around them. - if isinstance(comp_arr_parent, er.InstanceElement): - power = er.get_instance_el(evaluator, comp_arr_parent.instance, power) - - if evaluator.recursion_detector.push_stmt(power): - # Check for recursion. Possible by using 'extend' in - # combination with function calls. - continue - try: - if compare_array in evaluator.eval_element(power): - # The arrays match. Now add the results - added_types |= check_additions(execution_trailer.children[1], add_name) - finally: - evaluator.recursion_detector.pop_stmt() - # reset settings - settings.dynamic_params_for_other_modules = temp_param_add - debug.dbg('Dynamic array result %s' % added_types, color='MAGENTA') - return added_types - - -def check_array_instances(evaluator, instance): - """Used for set() and list() instances.""" - if not settings.dynamic_array_additions: - return instance.var_args - - ai = _ArrayInstance(evaluator, instance) - from jedi.evaluate import param - return param.Arguments(evaluator, [AlreadyEvaluated([ai])]) - - -class _ArrayInstance(IterableWrapper): - """ - Used for the usage of set() and list(). - This is definitely a hack, but a good one :-) - It makes it possible to use set/list conversions. - - In contrast to Array, ListComprehension and all other iterable types, this - is something that is only used inside `evaluate/compiled/fake/builtins.py` - and therefore doesn't need `names_dicts`, `py__bool__` and so on, because - we don't use these operations in `builtins.py`. - """ - def __init__(self, evaluator, instance): - self._evaluator = evaluator - self.instance = instance - self.var_args = instance.var_args - - def py__iter__(self): - try: - _, first_nodes = next(self.var_args.unpack()) - except StopIteration: - types = set() - else: - types = unite(self._evaluator.eval_element(node) for node in first_nodes) - for types in py__iter__(self._evaluator, types, first_nodes[0]): - yield types - - module = self.var_args.get_parent_until() - if module is None: - return - is_list = str(self.instance.name) == 'list' - additions = _check_array_additions(self._evaluator, self.instance, module, is_list) - if additions: - yield additions - - -class Slice(object): - def __init__(self, evaluator, start, stop, step): - self._evaluator = evaluator - # all of them are either a Precedence or None. - self._start = start - self._stop = stop - self._step = step - - @property - def obj(self): - """ - Imitate CompiledObject.obj behavior and return a ``builtin.slice()`` - object. - """ - def get(element): - if element is None: - return None - - result = self._evaluator.eval_element(element) - if len(result) != 1: - # For simplicity, we want slices to be clear defined with just - # one type. Otherwise we will return an empty slice object. - raise IndexError - try: - return list(result)[0].obj - except AttributeError: - return None - - try: - return slice(get(self._start), get(self._stop), get(self._step)) - except IndexError: - return slice(None, None, None) - - -def create_index_types(evaluator, index): - """ - Handles slices in subscript nodes. - """ - if index == ':': - # Like array[:] - return set([Slice(evaluator, None, None, None)]) - elif tree.is_node(index, 'subscript'): # subscript is a slice operation. - # Like array[:3] - result = [] - for el in index.children: - if el == ':': - if not result: - result.append(None) - elif tree.is_node(el, 'sliceop'): - if len(el.children) == 2: - result.append(el.children[1]) - else: - result.append(el) - result += [None] * (3 - len(result)) - - return set([Slice(evaluator, *result)]) - - # No slices - return evaluator.eval_element(index) diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/jedi_typing.py b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/jedi_typing.py deleted file mode 100644 index f48a567..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/jedi_typing.py +++ /dev/null @@ -1,100 +0,0 @@ -""" -This module is not intended to be used in jedi, rather it will be fed to the -jedi-parser to replace classes in the typing module -""" - -try: - from collections import abc -except ImportError: - # python 2 - import collections as abc - - -def factory(typing_name, indextypes): - class Iterable(abc.Iterable): - def __iter__(self): - while True: - yield indextypes[0]() - - class Iterator(Iterable, abc.Iterator): - def next(self): - """ needed for python 2 """ - return self.__next__() - - def __next__(self): - return indextypes[0]() - - class Sequence(abc.Sequence): - def __getitem__(self, index): - return indextypes[0]() - - class MutableSequence(Sequence, abc.MutableSequence): - pass - - class List(MutableSequence, list): - pass - - class Tuple(Sequence, tuple): - def __getitem__(self, index): - if indextypes[1] == Ellipsis: - # https://www.python.org/dev/peps/pep-0484/#the-typing-module - # Tuple[int, ...] means a tuple of ints of indetermined length - return indextypes[0]() - else: - return indextypes[index]() - - class AbstractSet(Iterable, abc.Set): - pass - - class MutableSet(AbstractSet, abc.MutableSet): - pass - - class KeysView(Iterable, abc.KeysView): - pass - - class ValuesView(abc.ValuesView): - def __iter__(self): - while True: - yield indextypes[1]() - - class ItemsView(abc.ItemsView): - def __iter__(self): - while True: - yield (indextypes[0](), indextypes[1]()) - - class Mapping(Iterable, abc.Mapping): - def __getitem__(self, item): - return indextypes[1]() - - def keys(self): - return KeysView() - - def values(self): - return ValuesView() - - def items(self): - return ItemsView() - - class MutableMapping(Mapping, abc.MutableMapping): - pass - - class Dict(MutableMapping, dict): - pass - - dct = { - "Sequence": Sequence, - "MutableSequence": MutableSequence, - "List": List, - "Iterable": Iterable, - "Iterator": Iterator, - "AbstractSet": AbstractSet, - "MutableSet": MutableSet, - "Mapping": Mapping, - "MutableMapping": MutableMapping, - "Tuple": Tuple, - "KeysView": KeysView, - "ItemsView": ItemsView, - "ValuesView": ValuesView, - "Dict": Dict, - } - return dct[typing_name] diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/param.py b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/param.py deleted file mode 100644 index 997e079..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/param.py +++ /dev/null @@ -1,438 +0,0 @@ -from collections import defaultdict -from itertools import chain - -from jedi._compatibility import unicode, zip_longest -from jedi import debug -from jedi import common -from jedi.parser import tree -from jedi.evaluate import iterable -from jedi.evaluate import analysis -from jedi.evaluate import precedence -from jedi.evaluate.helpers import FakeName -from jedi.cache import underscore_memoization - - -def try_iter_content(types, depth=0): - """Helper method for static analysis.""" - if depth > 10: - # It's possible that a loop has references on itself (especially with - # CompiledObject). Therefore don't loop infinitely. - return - - for typ in types: - try: - f = typ.py__iter__ - except AttributeError: - pass - else: - for iter_types in f(): - try_iter_content(iter_types, depth + 1) - - -class Arguments(tree.Base): - def __init__(self, evaluator, argument_node, trailer=None): - """ - The argument_node is either a parser node or a list of evaluated - objects. Those evaluated objects may be lists of evaluated objects - themselves (one list for the first argument, one for the second, etc). - - :param argument_node: May be an argument_node or a list of nodes. - """ - self.argument_node = argument_node - self._evaluator = evaluator - self.trailer = trailer # Can be None, e.g. in a class definition. - - def _split(self): - if isinstance(self.argument_node, (tuple, list)): - for el in self.argument_node: - yield 0, el - else: - if not (tree.is_node(self.argument_node, 'arglist') or ( - # in python 3.5 **arg is an argument, not arglist - (tree.is_node(self.argument_node, 'argument') and - self.argument_node.children[0] in ('*', '**')))): - yield 0, self.argument_node - return - - iterator = iter(self.argument_node.children) - for child in iterator: - if child == ',': - continue - elif child in ('*', '**'): - yield len(child.value), next(iterator) - elif tree.is_node(child, 'argument') and \ - child.children[0] in ('*', '**'): - assert len(child.children) == 2 - yield len(child.children[0].value), child.children[1] - else: - yield 0, child - - def get_parent_until(self, *args, **kwargs): - if self.trailer is None: - try: - element = self.argument_node[0] - from jedi.evaluate.iterable import AlreadyEvaluated - if isinstance(element, AlreadyEvaluated): - element = list(self._evaluator.eval_element(element))[0] - except IndexError: - return None - else: - return element.get_parent_until(*args, **kwargs) - else: - return self.trailer.get_parent_until(*args, **kwargs) - - def as_tuple(self): - for stars, argument in self._split(): - if tree.is_node(argument, 'argument'): - argument, default = argument.children[::2] - else: - default = None - yield argument, default, stars - - def unpack(self, func=None): - named_args = [] - for stars, el in self._split(): - if stars == 1: - arrays = self._evaluator.eval_element(el) - iterators = [_iterate_star_args(self._evaluator, a, el, func) - for a in arrays] - iterators = list(iterators) - for values in list(zip_longest(*iterators)): - yield None, [v for v in values if v is not None] - elif stars == 2: - arrays = self._evaluator.eval_element(el) - dicts = [_star_star_dict(self._evaluator, a, el, func) - for a in arrays] - for dct in dicts: - for key, values in dct.items(): - yield key, values - else: - if tree.is_node(el, 'argument'): - c = el.children - if len(c) == 3: # Keyword argument. - named_args.append((c[0].value, (c[2],))) - else: # Generator comprehension. - # Include the brackets with the parent. - comp = iterable.GeneratorComprehension( - self._evaluator, self.argument_node.parent) - yield None, (iterable.AlreadyEvaluated([comp]),) - elif isinstance(el, (list, tuple)): - yield None, el - else: - yield None, (el,) - - # Reordering var_args is necessary, because star args sometimes appear - # after named argument, but in the actual order it's prepended. - for key_arg in named_args: - yield key_arg - - def _reorder_var_args(var_args): - named_index = None - new_args = [] - for i, stmt in enumerate(var_args): - if isinstance(stmt, tree.ExprStmt): - if named_index is None and stmt.assignment_details: - named_index = i - - if named_index is not None: - expression_list = stmt.expression_list() - if expression_list and expression_list[0] == '*': - new_args.insert(named_index, stmt) - named_index += 1 - continue - - new_args.append(stmt) - return new_args - - def eval_argument_clinic(self, arguments): - """Uses a list with argument clinic information (see PEP 436).""" - iterator = self.unpack() - for i, (name, optional, allow_kwargs) in enumerate(arguments): - key, va_values = next(iterator, (None, [])) - if key is not None: - raise NotImplementedError - if not va_values and not optional: - debug.warning('TypeError: %s expected at least %s arguments, got %s', - name, len(arguments), i) - raise ValueError - values = set(chain.from_iterable(self._evaluator.eval_element(el) - for el in va_values)) - if not values and not optional: - # For the stdlib we always want values. If we don't get them, - # that's ok, maybe something is too hard to resolve, however, - # we will not proceed with the evaluation of that function. - debug.warning('argument_clinic "%s" not resolvable.', name) - raise ValueError - yield values - - def scope(self): - # Returns the scope in which the arguments are used. - return (self.trailer or self.argument_node).get_parent_until(tree.IsScope) - - def eval_args(self): - # TODO this method doesn't work with named args and a lot of other - # things. Use unpack. - return [self._evaluator.eval_element(el) for stars, el in self._split()] - - def __repr__(self): - return '<%s: %s>' % (type(self).__name__, self.argument_node) - - def get_calling_var_args(self): - if tree.is_node(self.argument_node, 'arglist', 'argument') \ - or self.argument_node == () and self.trailer is not None: - return _get_calling_var_args(self._evaluator, self) - else: - return None - - def eval_all(self, func=None): - """ - Evaluates all arguments as a support for static analysis - (normally Jedi). - """ - for key, element_values in self.unpack(): - for element in element_values: - types = self._evaluator.eval_element(element) - try_iter_content(types) - - -class ExecutedParam(tree.Param): - """Fake a param and give it values.""" - def __init__(self, original_param, var_args, values): - self._original_param = original_param - self.var_args = var_args - self._values = values - - def eval(self, evaluator): - types = set() - for v in self._values: - types |= evaluator.eval_element(v) - return types - - @property - def position_nr(self): - # Need to use the original logic here, because it uses the parent. - return self._original_param.position_nr - - @property - @underscore_memoization - def name(self): - return FakeName(str(self._original_param.name), self, self.start_pos) - - def __getattr__(self, name): - return getattr(self._original_param, name) - - -def _get_calling_var_args(evaluator, var_args): - old_var_args = None - while var_args != old_var_args: - old_var_args = var_args - for name, default, stars in reversed(list(var_args.as_tuple())): - if not stars or not isinstance(name, tree.Name): - continue - - names = evaluator.goto(name) - if len(names) != 1: - break - param = names[0].get_definition() - if not isinstance(param, ExecutedParam): - if isinstance(param, tree.Param): - # There is no calling var_args in this case - there's just - # a param without any input. - return None - break - # We never want var_args to be a tuple. This should be enough for - # now, we can change it later, if we need to. - if isinstance(param.var_args, Arguments): - var_args = param.var_args - return var_args.argument_node or var_args.trailer - - -def get_params(evaluator, func, var_args): - param_names = [] - param_dict = {} - for param in func.params: - param_dict[str(param.name)] = param - unpacked_va = list(var_args.unpack(func)) - from jedi.evaluate.representation import InstanceElement - if isinstance(func, InstanceElement): - # Include self at this place. - unpacked_va.insert(0, (None, [iterable.AlreadyEvaluated([func.instance])])) - var_arg_iterator = common.PushBackIterator(iter(unpacked_va)) - - non_matching_keys = defaultdict(lambda: []) - keys_used = {} - keys_only = False - had_multiple_value_error = False - for param in func.params: - # The value and key can both be null. There, the defaults apply. - # args / kwargs will just be empty arrays / dicts, respectively. - # Wrong value count is just ignored. If you try to test cases that are - # not allowed in Python, Jedi will maybe not show any completions. - default = [] if param.default is None else [param.default] - key, va_values = next(var_arg_iterator, (None, default)) - while key is not None: - keys_only = True - k = unicode(key) - try: - key_param = param_dict[unicode(key)] - except KeyError: - non_matching_keys[key] = va_values - else: - param_names.append(ExecutedParam(key_param, var_args, va_values).name) - - if k in keys_used: - had_multiple_value_error = True - m = ("TypeError: %s() got multiple values for keyword argument '%s'." - % (func.name, k)) - calling_va = _get_calling_var_args(evaluator, var_args) - if calling_va is not None: - analysis.add(evaluator, 'type-error-multiple-values', - calling_va, message=m) - else: - try: - keys_used[k] = param_names[-1] - except IndexError: - # TODO this is wrong stupid and whatever. - pass - key, va_values = next(var_arg_iterator, (None, ())) - - values = [] - if param.stars == 1: - # *args param - lst_values = [iterable.MergedNodes(va_values)] if va_values else [] - for key, va_values in var_arg_iterator: - # Iterate until a key argument is found. - if key: - var_arg_iterator.push_back((key, va_values)) - break - if va_values: - lst_values.append(iterable.MergedNodes(va_values)) - seq = iterable.FakeSequence(evaluator, lst_values, 'tuple') - values = [iterable.AlreadyEvaluated([seq])] - elif param.stars == 2: - # **kwargs param - dct = iterable.FakeDict(evaluator, dict(non_matching_keys)) - values = [iterable.AlreadyEvaluated([dct])] - non_matching_keys = {} - else: - # normal param - if va_values: - values = va_values - else: - # No value: Return an empty container - values = [] - if not keys_only: - calling_va = var_args.get_calling_var_args() - if calling_va is not None: - m = _error_argument_count(func, len(unpacked_va)) - analysis.add(evaluator, 'type-error-too-few-arguments', - calling_va, message=m) - - # Now add to result if it's not one of the previously covered cases. - if (not keys_only or param.stars == 2): - param_names.append(ExecutedParam(param, var_args, values).name) - keys_used[unicode(param.name)] = param_names[-1] - - if keys_only: - # All arguments should be handed over to the next function. It's not - # about the values inside, it's about the names. Jedi needs to now that - # there's nothing to find for certain names. - for k in set(param_dict) - set(keys_used): - param = param_dict[k] - values = [] if param.default is None else [param.default] - param_names.append(ExecutedParam(param, var_args, values).name) - - if not (non_matching_keys or had_multiple_value_error - or param.stars or param.default): - # add a warning only if there's not another one. - calling_va = _get_calling_var_args(evaluator, var_args) - if calling_va is not None: - m = _error_argument_count(func, len(unpacked_va)) - analysis.add(evaluator, 'type-error-too-few-arguments', - calling_va, message=m) - - for key, va_values in non_matching_keys.items(): - m = "TypeError: %s() got an unexpected keyword argument '%s'." \ - % (func.name, key) - for value in va_values: - analysis.add(evaluator, 'type-error-keyword-argument', value.parent, message=m) - - remaining_params = list(var_arg_iterator) - if remaining_params: - m = _error_argument_count(func, len(unpacked_va)) - # Just report an error for the first param that is not needed (like - # cPython). - first_key, first_values = remaining_params[0] - for v in first_values: - if first_key is not None: - # Is a keyword argument, return the whole thing instead of just - # the value node. - v = v.parent - try: - non_kw_param = keys_used[first_key] - except KeyError: - pass - else: - origin_args = non_kw_param.parent.var_args.argument_node - # TODO calculate the var_args tree and check if it's in - # the tree (if not continue). - # print('\t\tnonkw', non_kw_param.parent.var_args.argument_node, ) - if origin_args not in [f.parent.parent for f in first_values]: - continue - analysis.add(evaluator, 'type-error-too-many-arguments', - v, message=m) - return param_names - - -def _iterate_star_args(evaluator, array, input_node, func=None): - from jedi.evaluate.representation import Instance - if isinstance(array, iterable.Array): - # TODO ._items is not the call we want here. Replace in the future. - for node in array._items(): - yield node - elif isinstance(array, iterable.Generator): - for types in array.py__iter__(): - yield iterable.AlreadyEvaluated(types) - elif isinstance(array, Instance) and array.name.get_code() == 'tuple': - debug.warning('Ignored a tuple *args input %s' % array) - else: - if func is not None: - m = "TypeError: %s() argument after * must be a sequence, not %s" \ - % (func.name.value, array) - analysis.add(evaluator, 'type-error-star', input_node, message=m) - - -def _star_star_dict(evaluator, array, input_node, func): - dct = defaultdict(lambda: []) - from jedi.evaluate.representation import Instance - if isinstance(array, Instance) and array.name.get_code() == 'dict': - # For now ignore this case. In the future add proper iterators and just - # make one call without crazy isinstance checks. - return {} - - if isinstance(array, iterable.FakeDict): - return array._dct - elif isinstance(array, iterable.Array) and array.type == 'dict': - # TODO bad call to non-public API - for key_node, value in array._items(): - for key in evaluator.eval_element(key_node): - if precedence.is_string(key): - dct[key.obj].append(value) - - else: - if func is not None: - m = "TypeError: %s argument after ** must be a mapping, not %s" \ - % (func.name.value, array) - analysis.add(evaluator, 'type-error-star-star', input_node, message=m) - return dict(dct) - - -def _error_argument_count(func, actual_count): - default_arguments = sum(1 for p in func.params if p.default or p.stars) - - if default_arguments == 0: - before = 'exactly ' - else: - before = 'from %s to ' % (len(func.params) - default_arguments) - return ('TypeError: %s() takes %s%s arguments (%s given).' - % (func.name, before, len(func.params), actual_count)) diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/pep0484.py b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/pep0484.py deleted file mode 100644 index 2387fe6..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/pep0484.py +++ /dev/null @@ -1,195 +0,0 @@ -""" -PEP 0484 ( https://www.python.org/dev/peps/pep-0484/ ) describes type hints -through function annotations. There is a strong suggestion in this document -that only the type of type hinting defined in PEP0484 should be allowed -as annotations in future python versions. - -The (initial / probably incomplete) implementation todo list for pep-0484: -v Function parameter annotations with builtin/custom type classes -v Function returntype annotations with builtin/custom type classes -v Function parameter annotations with strings (forward reference) -v Function return type annotations with strings (forward reference) -v Local variable type hints -v Assigned types: `Url = str\ndef get(url:Url) -> str:` -v Type hints in `with` statements -x Stub files support -x support `@no_type_check` and `@no_type_check_decorator` -x support for typing.cast() operator -x support for type hint comments for functions, `# type: (int, str) -> int`. - See comment from Guido https://github.com/davidhalter/jedi/issues/662 -""" - -import itertools - -import os -from jedi.parser import \ - Parser, load_grammar, ParseError, ParserWithRecovery, tree -from jedi.evaluate.cache import memoize_default -from jedi.common import unite -from jedi.evaluate import compiled -from jedi import debug -from jedi import _compatibility -import re - - -def _evaluate_for_annotation(evaluator, annotation, index=None): - """ - Evaluates a string-node, looking for an annotation - If index is not None, the annotation is expected to be a tuple - and we're interested in that index - """ - if annotation is not None: - definitions = evaluator.eval_element( - _fix_forward_reference(evaluator, annotation)) - if index is not None: - definitions = list(itertools.chain.from_iterable( - definition.py__getitem__(index) for definition in definitions - if definition.type == 'tuple' and - len(list(definition.py__iter__())) >= index)) - return list(itertools.chain.from_iterable( - evaluator.execute(d) for d in definitions)) - else: - return [] - - -def _fix_forward_reference(evaluator, node): - evaled_nodes = evaluator.eval_element(node) - if len(evaled_nodes) != 1: - debug.warning("Eval'ed typing index %s should lead to 1 object, " - " not %s" % (node, evaled_nodes)) - return node - evaled_node = list(evaled_nodes)[0] - if isinstance(evaled_node, compiled.CompiledObject) and \ - isinstance(evaled_node.obj, str): - try: - p = Parser(load_grammar(), _compatibility.unicode(evaled_node.obj), - start_symbol='eval_input') - newnode = p.get_parsed_node() - except ParseError: - debug.warning('Annotation not parsed: %s' % evaled_node.obj) - return node - else: - module = node.get_parent_until() - p.position_modifier.line = module.end_pos[0] - newnode.parent = module - return newnode - else: - return node - - -@memoize_default(None, evaluator_is_first_arg=True) -def follow_param(evaluator, param): - annotation = param.annotation() - return _evaluate_for_annotation(evaluator, annotation) - - -@memoize_default(None, evaluator_is_first_arg=True) -def find_return_types(evaluator, func): - annotation = func.py__annotations__().get("return", None) - return _evaluate_for_annotation(evaluator, annotation) - - -_typing_module = None - - -def _get_typing_replacement_module(): - """ - The idea is to return our jedi replacement for the PEP-0484 typing module - as discussed at https://github.com/davidhalter/jedi/issues/663 - """ - global _typing_module - if _typing_module is None: - typing_path = \ - os.path.abspath(os.path.join(__file__, "../jedi_typing.py")) - with open(typing_path) as f: - code = _compatibility.unicode(f.read()) - p = ParserWithRecovery(load_grammar(), code) - _typing_module = p.module - return _typing_module - - -def get_types_for_typing_module(evaluator, typ, node): - from jedi.evaluate.iterable import FakeSequence - if not typ.base.get_parent_until().name.value == "typing": - return None - # we assume that any class using [] in a module called - # "typing" with a name for which we have a replacement - # should be replaced by that class. This is not 100% - # airtight but I don't have a better idea to check that it's - # actually the PEP-0484 typing module and not some other - if tree.is_node(node, "subscriptlist"): - nodes = node.children[::2] # skip the commas - else: - nodes = [node] - del node - - nodes = [_fix_forward_reference(evaluator, node) for node in nodes] - - # hacked in Union and Optional, since it's hard to do nicely in parsed code - if typ.name.value == "Union": - return unite(evaluator.eval_element(node) for node in nodes) - if typ.name.value == "Optional": - return evaluator.eval_element(nodes[0]) - - typing = _get_typing_replacement_module() - factories = evaluator.find_types(typing, "factory") - assert len(factories) == 1 - factory = list(factories)[0] - assert factory - function_body_nodes = factory.children[4].children - valid_classnames = set(child.name.value - for child in function_body_nodes - if isinstance(child, tree.Class)) - if typ.name.value not in valid_classnames: - return None - compiled_classname = compiled.create(evaluator, typ.name.value) - - args = FakeSequence(evaluator, nodes, "tuple") - - result = evaluator.execute_evaluated(factory, compiled_classname, args) - return result - - -def find_type_from_comment_hint_for(evaluator, node, name): - return \ - _find_type_from_comment_hint(evaluator, node, node.children[1], name) - - -def find_type_from_comment_hint_with(evaluator, node, name): - assert len(node.children[1].children) == 3, \ - "Can only be here when children[1] is 'foo() as f'" - return _find_type_from_comment_hint( - evaluator, node, node.children[1].children[2], name) - - -def find_type_from_comment_hint_assign(evaluator, node, name): - return \ - _find_type_from_comment_hint(evaluator, node, node.children[0], name) - - -def _find_type_from_comment_hint(evaluator, node, varlist, name): - index = None - if varlist.type in ("testlist_star_expr", "exprlist"): - # something like "a, b = 1, 2" - index = 0 - for child in varlist.children: - if child == name: - break - if child.type == "operator": - continue - index += 1 - else: - return [] - - comment = node.get_following_comment_same_line() - if comment is None: - return [] - match = re.match(r"^#\s*type:\s*([^#]*)", comment) - if not match: - return [] - annotation = tree.String( - tree.zero_position_modifier, - repr(str(match.group(1).strip())), - node.start_pos) - annotation.parent = node.parent - return _evaluate_for_annotation(evaluator, annotation, index) diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/precedence.py b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/precedence.py deleted file mode 100644 index 5225aa6..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/precedence.py +++ /dev/null @@ -1,178 +0,0 @@ -""" -Handles operator precedence. -""" -import operator - -from jedi._compatibility import unicode -from jedi.parser import tree -from jedi import debug -from jedi.evaluate.compiled import CompiledObject, create, builtin_from_name -from jedi.evaluate import analysis - -# Maps Python syntax to the operator module. -COMPARISON_OPERATORS = { - '==': operator.eq, - '!=': operator.ne, - 'is': operator.is_, - 'is not': operator.is_not, - '<': operator.lt, - '<=': operator.le, - '>': operator.gt, - '>=': operator.ge, -} - - -def literals_to_types(evaluator, result): - # Changes literals ('a', 1, 1.0, etc) to its type instances (str(), - # int(), float(), etc). - new_result = set() - for typ in result: - if is_literal(typ): - # Literals are only valid as long as the operations are - # correct. Otherwise add a value-free instance. - cls = builtin_from_name(evaluator, typ.name.value) - new_result |= evaluator.execute(cls) - else: - new_result.add(typ) - return new_result - - -def calculate_children(evaluator, children): - """ - Calculate a list of children with operators. - """ - iterator = iter(children) - types = evaluator.eval_element(next(iterator)) - for operator in iterator: - right = next(iterator) - if tree.is_node(operator, 'comp_op'): # not in / is not - operator = ' '.join(str(c.value) for c in operator.children) - - # handle lazy evaluation of and/or here. - if operator in ('and', 'or'): - left_bools = set([left.py__bool__() for left in types]) - if left_bools == set([True]): - if operator == 'and': - types = evaluator.eval_element(right) - elif left_bools == set([False]): - if operator != 'and': - types = evaluator.eval_element(right) - # Otherwise continue, because of uncertainty. - else: - types = calculate(evaluator, types, operator, - evaluator.eval_element(right)) - debug.dbg('calculate_children types %s', types) - return types - - -def calculate(evaluator, left_result, operator, right_result): - result = set() - if not left_result or not right_result: - # illegal slices e.g. cause left/right_result to be None - result = (left_result or set()) | (right_result or set()) - result = literals_to_types(evaluator, result) - else: - # I don't think there's a reasonable chance that a string - # operation is still correct, once we pass something like six - # objects. - if len(left_result) * len(right_result) > 6: - result = literals_to_types(evaluator, left_result | right_result) - else: - for left in left_result: - for right in right_result: - result |= _element_calculate(evaluator, left, operator, right) - return result - - -def factor_calculate(evaluator, types, operator): - """ - Calculates `+`, `-`, `~` and `not` prefixes. - """ - for typ in types: - if operator == '-': - if _is_number(typ): - yield create(evaluator, -typ.obj) - elif operator == 'not': - value = typ.py__bool__() - if value is None: # Uncertainty. - return - yield create(evaluator, not value) - else: - yield typ - - -def _is_number(obj): - return isinstance(obj, CompiledObject) \ - and isinstance(obj.obj, (int, float)) - - -def is_string(obj): - return isinstance(obj, CompiledObject) \ - and isinstance(obj.obj, (str, unicode)) - - -def is_literal(obj): - return _is_number(obj) or is_string(obj) - - -def _is_tuple(obj): - from jedi.evaluate import iterable - return isinstance(obj, iterable.Array) and obj.type == 'tuple' - - -def _is_list(obj): - from jedi.evaluate import iterable - return isinstance(obj, iterable.Array) and obj.type == 'list' - - -def _element_calculate(evaluator, left, operator, right): - from jedi.evaluate import iterable, representation as er - l_is_num = _is_number(left) - r_is_num = _is_number(right) - if operator == '*': - # for iterables, ignore * operations - if isinstance(left, iterable.Array) or is_string(left): - return set([left]) - elif isinstance(right, iterable.Array) or is_string(right): - return set([right]) - elif operator == '+': - if l_is_num and r_is_num or is_string(left) and is_string(right): - return set([create(evaluator, left.obj + right.obj)]) - elif _is_tuple(left) and _is_tuple(right) or _is_list(left) and _is_list(right): - return set([iterable.MergedArray(evaluator, (left, right))]) - elif operator == '-': - if l_is_num and r_is_num: - return set([create(evaluator, left.obj - right.obj)]) - elif operator == '%': - # With strings and numbers the left type typically remains. Except for - # `int() % float()`. - return set([left]) - elif operator in COMPARISON_OPERATORS: - operation = COMPARISON_OPERATORS[operator] - if isinstance(left, CompiledObject) and isinstance(right, CompiledObject): - # Possible, because the return is not an option. Just compare. - left = left.obj - right = right.obj - - try: - result = operation(left, right) - except TypeError: - # Could be True or False. - return set([create(evaluator, True), create(evaluator, False)]) - else: - return set([create(evaluator, result)]) - elif operator == 'in': - return set() - - def check(obj): - """Checks if a Jedi object is either a float or an int.""" - return isinstance(obj, er.Instance) and obj.name.get_code() in ('int', 'float') - - # Static analysis, one is a number, the other one is not. - if operator in ('+', '-') and l_is_num != r_is_num \ - and not (check(left) or check(right)): - message = "TypeError: unsupported operand type(s) for +: %s and %s" - analysis.add(evaluator, 'type-error-operation', operator, - message % (left, right)) - - return set([left, right]) diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/recursion.py b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/recursion.py deleted file mode 100644 index 9b95fad..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/recursion.py +++ /dev/null @@ -1,157 +0,0 @@ -""" -Recursions are the recipe of |jedi| to conquer Python code. However, someone -must stop recursions going mad. Some settings are here to make |jedi| stop at -the right time. You can read more about them :ref:`here `. - -Next to :mod:`jedi.evaluate.cache` this module also makes |jedi| not -thread-safe. Why? ``execution_recursion_decorator`` uses class variables to -count the function calls. -""" -from jedi import debug -from jedi import settings -from jedi.evaluate import iterable - - -def recursion_decorator(func): - def run(evaluator, stmt, *args, **kwargs): - rec_detect = evaluator.recursion_detector - if rec_detect.push_stmt(stmt): - return set() - else: - result = func(evaluator, stmt, *args, **kwargs) - rec_detect.pop_stmt() - return result - return run - - -class RecursionDetector(object): - """ - A decorator to detect recursions in statements. In a recursion a statement - at the same place, in the same module may not be executed two times. - """ - def __init__(self, evaluator): - self.top = None - self.current = None - self._evaluator = evaluator - - def push_stmt(self, stmt): - self.current = _RecursionNode(self._evaluator, stmt, self.current) - check = self._check_recursion() - if check: - debug.warning('catched stmt recursion: %s against %s @%s', stmt, - check.stmt, stmt.start_pos) - self.pop_stmt() - return True - return False - - def pop_stmt(self): - if self.current is not None: - # I don't know how current can be None, but sometimes it happens - # with Python3. - self.current = self.current.parent - - def _check_recursion(self): - test = self.current - while True: - test = test.parent - if self.current == test: - return test - if not test: - return False - - def node_statements(self): - result = [] - n = self.current - while n: - result.insert(0, n.stmt) - n = n.parent - return result - - -class _RecursionNode(object): - """ A node of the RecursionDecorator. """ - def __init__(self, evaluator, stmt, parent): - self._evaluator = evaluator - self.script = stmt.get_parent_until() - self.position = stmt.start_pos - self.parent = parent - self.stmt = stmt - - # Don't check param instances, they are not causing recursions - # The same's true for the builtins, because the builtins are really - # simple. - self.is_ignored = self.script == self._evaluator.BUILTINS - - def __eq__(self, other): - if not other: - return None - - return self.script == other.script \ - and self.position == other.position \ - and not self.is_ignored and not other.is_ignored - - -def execution_recursion_decorator(func): - def run(execution, **kwargs): - detector = execution._evaluator.execution_recursion_detector - if detector.push_execution(execution): - result = set() - else: - result = func(execution, **kwargs) - detector.pop_execution() - return result - - return run - - -class ExecutionRecursionDetector(object): - """ - Catches recursions of executions. - """ - def __init__(self, evaluator): - self.recursion_level = 0 - self.parent_execution_funcs = [] - self.execution_funcs = set() - self.execution_count = 0 - self._evaluator = evaluator - - def __call__(self, execution): - debug.dbg('Execution recursions: %s', execution, self.recursion_level, - self.execution_count, len(self.execution_funcs)) - if self.check_recursion(execution): - result = set() - else: - result = self.func(execution) - self.pop_execution() - return result - - def pop_execution(self): - self.parent_execution_funcs.pop() - self.recursion_level -= 1 - - def push_execution(self, execution): - in_par_execution_funcs = execution.base in self.parent_execution_funcs - in_execution_funcs = execution.base in self.execution_funcs - self.recursion_level += 1 - self.execution_count += 1 - self.execution_funcs.add(execution.base) - self.parent_execution_funcs.append(execution.base) - - if self.execution_count > settings.max_executions: - return True - - if isinstance(execution.base, (iterable.Array, iterable.Generator)): - return False - module = execution.get_parent_until() - if module == self._evaluator.BUILTINS: - return False - - if in_par_execution_funcs: - if self.recursion_level > settings.max_function_recursion_level: - return True - if in_execution_funcs and \ - len(self.execution_funcs) > settings.max_until_execution_unique: - return True - if self.execution_count > settings.max_executions_without_builtins: - return True - return False diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/representation.py b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/representation.py deleted file mode 100644 index 8f3d642..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/representation.py +++ /dev/null @@ -1,974 +0,0 @@ -""" -Like described in the :mod:`jedi.parser.tree` module, -there's a need for an ast like module to represent the states of parsed -modules. - -But now there are also structures in Python that need a little bit more than -that. An ``Instance`` for example is only a ``Class`` before it is -instantiated. This class represents these cases. - -So, why is there also a ``Class`` class here? Well, there are decorators and -they change classes in Python 3. - -Representation modules also define "magic methods". Those methods look like -``py__foo__`` and are typically mappable to the Python equivalents ``__call__`` -and others. Here's a list: - -====================================== ======================================== -**Method** **Description** --------------------------------------- ---------------------------------------- -py__call__(params: Array) On callable objects, returns types. -py__bool__() Returns True/False/None; None means that - there's no certainty. -py__bases__() Returns a list of base classes. -py__mro__() Returns a list of classes (the mro). -py__iter__() Returns a generator of a set of types. -py__class__() Returns the class of an instance. -py__getitem__(index: int/str) Returns a a set of types of the index. - Can raise an IndexError/KeyError. -py__file__() Only on modules. -py__package__() Only on modules. For the import system. -py__path__() Only on modules. For the import system. -====================================== ======================================== - -__ -""" -import os -import pkgutil -import imp -import re -from itertools import chain - -from jedi._compatibility import use_metaclass, unicode, Python3Method, is_py3 -from jedi.parser import tree -from jedi import debug -from jedi import common -from jedi.cache import underscore_memoization, cache_star_import -from jedi.evaluate.cache import memoize_default, CachedMetaClass, NO_DEFAULT -from jedi.evaluate import compiled -from jedi.evaluate.compiled import mixed -from jedi.evaluate import recursion -from jedi.evaluate import iterable -from jedi.evaluate import docstrings -from jedi.evaluate import pep0484 -from jedi.evaluate import helpers -from jedi.evaluate import param -from jedi.evaluate import flow_analysis -from jedi.evaluate import imports - - -class Executed(tree.Base): - """ - An instance is also an executable - because __init__ is called - :param var_args: The param input array, consist of a parser node or a list. - """ - def __init__(self, evaluator, base, var_args=()): - self._evaluator = evaluator - self.base = base - self.var_args = var_args - - def is_scope(self): - return True - - def get_parent_until(self, *args, **kwargs): - return tree.Base.get_parent_until(self, *args, **kwargs) - - @common.safe_property - def parent(self): - return self.base.parent - - -class Instance(use_metaclass(CachedMetaClass, Executed)): - """ - This class is used to evaluate instances. - """ - def __init__(self, evaluator, base, var_args, is_generated=False): - super(Instance, self).__init__(evaluator, base, var_args) - self.decorates = None - # Generated instances are classes that are just generated by self - # (No var_args) used. - self.is_generated = is_generated - - if base.name.get_code() in ['list', 'set'] \ - and evaluator.BUILTINS == base.get_parent_until(): - # compare the module path with the builtin name. - self.var_args = iterable.check_array_instances(evaluator, self) - elif not is_generated: - # Need to execute the __init__ function, because the dynamic param - # searching needs it. - try: - method = self.get_subscope_by_name('__init__') - except KeyError: - pass - else: - evaluator.execute(method, self.var_args) - - def is_class(self): - return False - - @property - def py__call__(self): - def actual(params): - return self._evaluator.execute(method, params) - - try: - method = self.get_subscope_by_name('__call__') - except KeyError: - # Means the Instance is not callable. - raise AttributeError - - return actual - - def py__class__(self): - return self.base - - def py__bool__(self): - # Signalize that we don't know about the bool type. - return None - - @memoize_default() - def _get_method_execution(self, func): - func = get_instance_el(self._evaluator, self, func, True) - return FunctionExecution(self._evaluator, func, self.var_args) - - def _get_func_self_name(self, func): - """ - Returns the name of the first param in a class method (which is - normally self. - """ - try: - return str(func.params[0].name) - except IndexError: - return None - - def _self_names_dict(self, add_mro=True): - names = {} - # This loop adds the names of the self object, copies them and removes - # the self. - for sub in self.base.subscopes: - if isinstance(sub, tree.Class): - continue - # Get the self name, if there's one. - self_name = self._get_func_self_name(sub) - if self_name is None: - continue - - if sub.name.value == '__init__' and not self.is_generated: - # ``__init__`` is special because the params need are injected - # this way. Therefore an execution is necessary. - if not sub.get_decorators(): - # __init__ decorators should generally just be ignored, - # because to follow them and their self variables is too - # complicated. - sub = self._get_method_execution(sub) - for name_list in sub.names_dict.values(): - for name in name_list: - if name.value == self_name and name.get_previous_sibling() is None: - trailer = name.get_next_sibling() - if tree.is_node(trailer, 'trailer') \ - and len(trailer.children) == 2 \ - and trailer.children[0] == '.': - name = trailer.children[1] # After dot. - if name.is_definition(): - arr = names.setdefault(name.value, []) - arr.append(get_instance_el(self._evaluator, self, name)) - return names - - def get_subscope_by_name(self, name): - sub = self.base.get_subscope_by_name(name) - return get_instance_el(self._evaluator, self, sub, True) - - def execute_subscope_by_name(self, name, *args): - method = self.get_subscope_by_name(name) - return self._evaluator.execute_evaluated(method, *args) - - def get_descriptor_returns(self, obj): - """ Throws a KeyError if there's no method. """ - # Arguments in __get__ descriptors are obj, class. - # `method` is the new parent of the array, don't know if that's good. - none_obj = compiled.create(self._evaluator, None) - args = [obj, obj.base] if isinstance(obj, Instance) else [none_obj, obj] - try: - return self.execute_subscope_by_name('__get__', *args) - except KeyError: - return set([self]) - - @memoize_default() - def names_dicts(self, search_global): - yield self._self_names_dict() - - for s in self.base.py__mro__()[1:]: - if not isinstance(s, compiled.CompiledObject): - # Compiled objects don't have `self.` names. - for inst in self._evaluator.execute(s): - yield inst._self_names_dict(add_mro=False) - - for names_dict in self.base.names_dicts(search_global=False, is_instance=True): - yield LazyInstanceDict(self._evaluator, self, names_dict) - - def py__getitem__(self, index): - try: - method = self.get_subscope_by_name('__getitem__') - except KeyError: - debug.warning('No __getitem__, cannot access the array.') - return set() - else: - index_obj = compiled.create(self._evaluator, index) - return self._evaluator.execute_evaluated(method, index_obj) - - def py__iter__(self): - try: - method = self.get_subscope_by_name('__iter__') - except KeyError: - debug.warning('No __iter__ on %s.' % self) - return - else: - iters = self._evaluator.execute(method) - for generator in iters: - if isinstance(generator, Instance): - # `__next__` logic. - name = '__next__' if is_py3 else 'next' - try: - yield generator.execute_subscope_by_name(name) - except KeyError: - debug.warning('Instance has no __next__ function in %s.', generator) - else: - for typ in generator.py__iter__(): - yield typ - - @property - @underscore_memoization - def name(self): - name = self.base.name - return helpers.FakeName(unicode(name), self, name.start_pos) - - def __getattr__(self, name): - if name not in ['start_pos', 'end_pos', 'get_imports', 'type', - 'doc', 'raw_doc']: - raise AttributeError("Instance %s: Don't touch this (%s)!" - % (self, name)) - return getattr(self.base, name) - - def __repr__(self): - dec = '' - if self.decorates is not None: - dec = " decorates " + repr(self.decorates) - return "<%s of %s(%s)%s>" % (type(self).__name__, self.base, - self.var_args, dec) - - -class LazyInstanceDict(object): - def __init__(self, evaluator, instance, dct): - self._evaluator = evaluator - self._instance = instance - self._dct = dct - - def __getitem__(self, name): - return [get_instance_el(self._evaluator, self._instance, var, True) - for var in self._dct[name]] - - def values(self): - return [self[key] for key in self._dct] - - -class InstanceName(tree.Name): - def __init__(self, origin_name, parent): - super(InstanceName, self).__init__(tree.zero_position_modifier, - origin_name.value, - origin_name.start_pos) - self._origin_name = origin_name - self.parent = parent - - def is_definition(self): - return self._origin_name.is_definition() - - -def get_instance_el(evaluator, instance, var, is_class_var=False): - """ - Returns an InstanceElement if it makes sense, otherwise leaves the object - untouched. - - Basically having an InstanceElement is context information. That is needed - in quite a lot of cases, which includes Nodes like ``power``, that need to - know where a self name comes from for example. - """ - if isinstance(var, tree.Name): - parent = get_instance_el(evaluator, instance, var.parent, is_class_var) - return InstanceName(var, parent) - elif var.type != 'funcdef' \ - and isinstance(var, (Instance, compiled.CompiledObject, tree.Leaf, - tree.Module, FunctionExecution)): - return var - - var = evaluator.wrap(var) - return InstanceElement(evaluator, instance, var, is_class_var) - - -class InstanceElement(use_metaclass(CachedMetaClass, tree.Base)): - """ - InstanceElement is a wrapper for any object, that is used as an instance - variable (e.g. self.variable or class methods). - """ - def __init__(self, evaluator, instance, var, is_class_var): - self._evaluator = evaluator - self.instance = instance - self.var = var - self.is_class_var = is_class_var - - @common.safe_property - @memoize_default() - def parent(self): - par = self.var.parent - if isinstance(par, Class) and par == self.instance.base \ - or isinstance(par, tree.Class) \ - and par == self.instance.base.base: - par = self.instance - else: - par = get_instance_el(self._evaluator, self.instance, par, - self.is_class_var) - return par - - def get_parent_until(self, *args, **kwargs): - return tree.BaseNode.get_parent_until(self, *args, **kwargs) - - def get_definition(self): - return self.get_parent_until((tree.ExprStmt, tree.IsScope, tree.Import)) - - def get_decorated_func(self): - """ Needed because the InstanceElement should not be stripped """ - func = self.var.get_decorated_func() - func = get_instance_el(self._evaluator, self.instance, func) - return func - - def get_rhs(self): - return get_instance_el(self._evaluator, self.instance, - self.var.get_rhs(), self.is_class_var) - - def is_definition(self): - return self.var.is_definition() - - @property - def children(self): - # Copy and modify the array. - return [get_instance_el(self._evaluator, self.instance, command, self.is_class_var) - for command in self.var.children] - - @property - @memoize_default() - def name(self): - name = self.var.name - return helpers.FakeName(unicode(name), self, name.start_pos) - - def __iter__(self): - for el in self.var.__iter__(): - yield get_instance_el(self._evaluator, self.instance, el, - self.is_class_var) - - def __getitem__(self, index): - return get_instance_el(self._evaluator, self.instance, self.var[index], - self.is_class_var) - - def __getattr__(self, name): - return getattr(self.var, name) - - def isinstance(self, *cls): - return isinstance(self.var, cls) - - def is_scope(self): - """ - Since we inherit from Base, it would overwrite the action we want here. - """ - return self.var.is_scope() - - def py__call__(self, params): - if isinstance(self.var, compiled.CompiledObject): - # This check is a bit strange, but CompiledObject itself is a bit - # more complicated than we would it actually like to be. - return self.var.py__call__(params) - else: - return Function.py__call__(self, params) - - def __repr__(self): - return "<%s of %s>" % (type(self).__name__, self.var) - - -class Wrapper(tree.Base): - def is_scope(self): - return True - - def is_class(self): - return False - - def py__bool__(self): - """ - Since Wrapper is a super class for classes, functions and modules, - the return value will always be true. - """ - return True - - @property - @underscore_memoization - def name(self): - name = self.base.name - return helpers.FakeName(unicode(name), self, name.start_pos) - - -class Class(use_metaclass(CachedMetaClass, Wrapper)): - """ - This class is not only important to extend `tree.Class`, it is also a - important for descriptors (if the descriptor methods are evaluated or not). - """ - def __init__(self, evaluator, base): - self._evaluator = evaluator - self.base = base - - @memoize_default(default=()) - def py__mro__(self): - def add(cls): - if cls not in mro: - mro.append(cls) - - mro = [self] - # TODO Do a proper mro resolution. Currently we are just listing - # classes. However, it's a complicated algorithm. - for cls in self.py__bases__(): - # TODO detect for TypeError: duplicate base class str, - # e.g. `class X(str, str): pass` - try: - mro_method = cls.py__mro__ - except AttributeError: - # TODO add a TypeError like: - """ - >>> class Y(lambda: test): pass - Traceback (most recent call last): - File "", line 1, in - TypeError: function() argument 1 must be code, not str - >>> class Y(1): pass - Traceback (most recent call last): - File "", line 1, in - TypeError: int() takes at most 2 arguments (3 given) - """ - pass - else: - add(cls) - for cls_new in mro_method(): - add(cls_new) - return tuple(mro) - - @memoize_default(default=()) - def py__bases__(self): - arglist = self.base.get_super_arglist() - if arglist: - args = param.Arguments(self._evaluator, arglist) - return list(chain.from_iterable(args.eval_args())) - else: - return [compiled.create(self._evaluator, object)] - - def py__call__(self, params): - return set([Instance(self._evaluator, self, params)]) - - def py__class__(self): - return compiled.create(self._evaluator, type) - - @property - def params(self): - try: - return self.get_subscope_by_name('__init__').params - except KeyError: - return [] # object.__init__ - - def names_dicts(self, search_global, is_instance=False): - if search_global: - yield self.names_dict - else: - for scope in self.py__mro__(): - if isinstance(scope, compiled.CompiledObject): - yield scope.names_dicts(False, is_instance)[0] - else: - yield scope.names_dict - - def is_class(self): - return True - - def get_subscope_by_name(self, name): - for s in self.py__mro__(): - for sub in reversed(s.subscopes): - if sub.name.value == name: - return sub - raise KeyError("Couldn't find subscope.") - - def __getattr__(self, name): - if name not in ['start_pos', 'end_pos', 'parent', 'raw_doc', - 'doc', 'get_imports', 'get_parent_until', 'get_code', - 'subscopes', 'names_dict', 'type']: - raise AttributeError("Don't touch this: %s of %s !" % (name, self)) - return getattr(self.base, name) - - def __repr__(self): - return "" % (type(self).__name__, self.base) - - -class Function(use_metaclass(CachedMetaClass, Wrapper)): - """ - Needed because of decorators. Decorators are evaluated here. - """ - def __init__(self, evaluator, func, is_decorated=False): - """ This should not be called directly """ - self._evaluator = evaluator - self.base = self.base_func = func - self.is_decorated = is_decorated - # A property that is set by the decorator resolution. - self.decorates = None - - @memoize_default() - def get_decorated_func(self): - """ - Returns the function, that should to be executed in the end. - This is also the places where the decorators are processed. - """ - f = self.base_func - decorators = self.base_func.get_decorators() - - if not decorators or self.is_decorated: - return self - - # Only enter it, if has not already been processed. - if not self.is_decorated: - for dec in reversed(decorators): - debug.dbg('decorator: %s %s', dec, f) - dec_results = self._evaluator.eval_element(dec.children[1]) - trailer = dec.children[2:-1] - if trailer: - # Create a trailer and evaluate it. - trailer = tree.Node('trailer', trailer) - trailer.parent = dec - dec_results = self._evaluator.eval_trailer(dec_results, trailer) - - if not len(dec_results): - debug.warning('decorator not found: %s on %s', dec, self.base_func) - return self - decorator = dec_results.pop() - if dec_results: - debug.warning('multiple decorators found %s %s', - self.base_func, dec_results) - - # Create param array. - if isinstance(f, Function): - old_func = f # TODO this is just hacky. change. - elif f.type == 'funcdef': - old_func = Function(self._evaluator, f, is_decorated=True) - else: - old_func = f - - wrappers = self._evaluator.execute_evaluated(decorator, old_func) - if not len(wrappers): - debug.warning('no wrappers found %s', self.base_func) - return self - if len(wrappers) > 1: - # TODO resolve issue with multiple wrappers -> multiple types - debug.warning('multiple wrappers found %s %s', - self.base_func, wrappers) - f = list(wrappers)[0] - if isinstance(f, (Instance, Function)): - f.decorates = self - - debug.dbg('decorator end %s', f) - return f - - def names_dicts(self, search_global): - if search_global: - yield self.names_dict - else: - scope = self.py__class__() - for names_dict in scope.names_dicts(False): - yield names_dict - - @Python3Method - def py__call__(self, params): - if self.base.is_generator(): - return set([iterable.Generator(self._evaluator, self, params)]) - else: - return FunctionExecution(self._evaluator, self, params).get_return_types() - - @memoize_default() - def py__annotations__(self): - parser_func = self.base - return_annotation = parser_func.annotation() - if return_annotation: - dct = {'return': return_annotation} - else: - dct = {} - for function_param in parser_func.params: - param_annotation = function_param.annotation() - if param_annotation is not None: - dct[function_param.name.value] = param_annotation - return dct - - def py__class__(self): - # This differentiation is only necessary for Python2. Python3 does not - # use a different method class. - if isinstance(self.base.get_parent_scope(), tree.Class): - name = 'METHOD_CLASS' - else: - name = 'FUNCTION_CLASS' - return compiled.get_special_object(self._evaluator, name) - - def __getattr__(self, name): - return getattr(self.base_func, name) - - def __repr__(self): - dec = '' - if self.decorates is not None: - dec = " decorates " + repr(self.decorates) - return "" % (type(self).__name__, self.base_func, dec) - - -class LambdaWrapper(Function): - def get_decorated_func(self): - return self - - -class FunctionExecution(Executed): - """ - This class is used to evaluate functions and their returns. - - This is the most complicated class, because it contains the logic to - transfer parameters. It is even more complicated, because there may be - multiple calls to functions and recursion has to be avoided. But this is - responsibility of the decorators. - """ - type = 'funcdef' - - def __init__(self, evaluator, base, *args, **kwargs): - super(FunctionExecution, self).__init__(evaluator, base, *args, **kwargs) - self._copy_dict = {} - funcdef = base.base_func - if isinstance(funcdef, mixed.MixedObject): - # The extra information in mixed is not needed anymore. We can just - # unpack it and give it the tree object. - funcdef = funcdef.definition - - # Just overwrite the old version. We don't need it anymore. - funcdef = helpers.deep_ast_copy(funcdef, new_elements=self._copy_dict) - for child in funcdef.children: - if child.type not in ('operator', 'keyword'): - # Not all nodes are properly copied by deep_ast_copy. - child.parent = self - self.children = funcdef.children - self.names_dict = funcdef.names_dict - - @memoize_default(default=set()) - @recursion.execution_recursion_decorator - def get_return_types(self, check_yields=False): - func = self.base - - if func.isinstance(LambdaWrapper): - return self._evaluator.eval_element(self.children[-1]) - - if func.listeners: - # Feed the listeners, with the params. - for listener in func.listeners: - listener.execute(self._get_params()) - # If we do have listeners, that means that there's not a regular - # execution ongoing. In this case Jedi is interested in the - # inserted params, not in the actual execution of the function. - return set() - - if check_yields: - types = set() - returns = self.yields - else: - returns = self.returns - types = set(docstrings.find_return_types(self._evaluator, func)) - types |= set(pep0484.find_return_types(self._evaluator, func)) - - for r in returns: - check = flow_analysis.break_check(self._evaluator, self, r) - if check is flow_analysis.UNREACHABLE: - debug.dbg('Return unreachable: %s', r) - else: - if check_yields: - types |= iterable.unite(self._eval_yield(r)) - else: - types |= self._evaluator.eval_element(r.children[1]) - if check is flow_analysis.REACHABLE: - debug.dbg('Return reachable: %s', r) - break - return types - - def _eval_yield(self, yield_expr): - element = yield_expr.children[1] - if element.type == 'yield_arg': - # It must be a yield from. - yield_from_types = self._evaluator.eval_element(element.children[1]) - for result in iterable.py__iter__(self._evaluator, yield_from_types, element): - yield result - else: - yield self._evaluator.eval_element(element) - - @recursion.execution_recursion_decorator - def get_yield_types(self): - yields = self.yields - stopAt = tree.ForStmt, tree.WhileStmt, FunctionExecution, tree.IfStmt - for_parents = [(x, x.get_parent_until((stopAt))) for x in yields] - - # Calculate if the yields are placed within the same for loop. - yields_order = [] - last_for_stmt = None - for yield_, for_stmt in for_parents: - # For really simple for loops we can predict the order. Otherwise - # we just ignore it. - parent = for_stmt.parent - if parent.type == 'suite': - parent = parent.parent - if for_stmt.type == 'for_stmt' and parent == self \ - and for_stmt.defines_one_name(): # Simplicity for now. - if for_stmt == last_for_stmt: - yields_order[-1][1].append(yield_) - else: - yields_order.append((for_stmt, [yield_])) - elif for_stmt == self: - yields_order.append((None, [yield_])) - else: - yield self.get_return_types(check_yields=True) - return - last_for_stmt = for_stmt - - evaluator = self._evaluator - for for_stmt, yields in yields_order: - if for_stmt is None: - # No for_stmt, just normal yields. - for yield_ in yields: - for result in self._eval_yield(yield_): - yield result - else: - input_node = for_stmt.get_input_node() - for_types = evaluator.eval_element(input_node) - ordered = iterable.py__iter__(evaluator, for_types, input_node) - for index_types in ordered: - dct = {str(for_stmt.children[1]): index_types} - evaluator.predefined_if_name_dict_dict[for_stmt] = dct - for yield_in_same_for_stmt in yields: - for result in self._eval_yield(yield_in_same_for_stmt): - yield result - del evaluator.predefined_if_name_dict_dict[for_stmt] - - def names_dicts(self, search_global): - yield self.names_dict - - @memoize_default(default=NO_DEFAULT) - def _get_params(self): - """ - This returns the params for an TODO and is injected as a - 'hack' into the tree.Function class. - This needs to be here, because Instance can have __init__ functions, - which act the same way as normal functions. - """ - return param.get_params(self._evaluator, self.base, self.var_args) - - def param_by_name(self, name): - return [n for n in self._get_params() if str(n) == name][0] - - def name_for_position(self, position): - return tree.Function.name_for_position(self, position) - - def __getattr__(self, name): - if name not in ['start_pos', 'end_pos', 'imports', 'name', 'type']: - raise AttributeError('Tried to access %s: %s. Why?' % (name, self)) - return getattr(self.base, name) - - @common.safe_property - @memoize_default() - def returns(self): - return tree.Scope._search_in_scope(self, tree.ReturnStmt) - - @common.safe_property - @memoize_default() - def yields(self): - return tree.Scope._search_in_scope(self, tree.YieldExpr) - - @common.safe_property - @memoize_default() - def statements(self): - return tree.Scope._search_in_scope(self, tree.ExprStmt) - - @common.safe_property - @memoize_default() - def subscopes(self): - return tree.Scope._search_in_scope(self, tree.Scope) - - def __repr__(self): - return "<%s of %s>" % (type(self).__name__, self.base) - - -class GlobalName(helpers.FakeName): - def __init__(self, name): - """ - We need to mark global names somehow. Otherwise they are just normal - names that are not definitions. - """ - super(GlobalName, self).__init__(name.value, name.parent, - name.start_pos, is_definition=True) - - -class ModuleWrapper(use_metaclass(CachedMetaClass, tree.Module, Wrapper)): - def __init__(self, evaluator, module, parent_module=None): - self._evaluator = evaluator - self.base = self._module = module - self._parent_module = parent_module - - def names_dicts(self, search_global): - yield self.base.names_dict - yield self._module_attributes_dict() - - for star_module in self.star_imports(): - yield star_module.names_dict - - yield dict((str(n), [GlobalName(n)]) for n in self.base.global_names) - yield self._sub_modules_dict() - - # I'm not sure if the star import cache is really that effective anymore - # with all the other really fast import caches. Recheck. Also we would need - # to push the star imports into Evaluator.modules, if we reenable this. - #@cache_star_import - @memoize_default([]) - def star_imports(self): - modules = [] - for i in self.base.imports: - if i.is_star_import(): - name = i.star_import_name() - new = imports.ImportWrapper(self._evaluator, name).follow() - for module in new: - if isinstance(module, tree.Module): - modules += module.star_imports() - modules += new - return modules - - @memoize_default() - def _module_attributes_dict(self): - def parent_callback(): - # Create a string type object (without a defined string in it): - return list(self._evaluator.execute(compiled.create(self._evaluator, str)))[0] - - names = ['__file__', '__package__', '__doc__', '__name__'] - # All the additional module attributes are strings. - return dict((n, [helpers.LazyName(n, parent_callback, is_definition=True)]) - for n in names) - - @property - @memoize_default() - def name(self): - return helpers.FakeName(unicode(self.base.name), self, (1, 0)) - - def _get_init_directory(self): - """ - :return: The path to the directory of a package. None in case it's not - a package. - """ - for suffix, _, _ in imp.get_suffixes(): - ending = '__init__' + suffix - py__file__ = self.py__file__() - if py__file__ is not None and py__file__.endswith(ending): - # Remove the ending, including the separator. - return self.py__file__()[:-len(ending) - 1] - return None - - def py__name__(self): - for name, module in self._evaluator.modules.items(): - if module == self: - return name - - return '__main__' - - def py__file__(self): - """ - In contrast to Python's __file__ can be None. - """ - if self._module.path is None: - return None - - return os.path.abspath(self._module.path) - - def py__package__(self): - if self._get_init_directory() is None: - return re.sub(r'\.?[^\.]+$', '', self.py__name__()) - else: - return self.py__name__() - - def _py__path__(self): - if self._parent_module is None: - search_path = self._evaluator.sys_path - else: - search_path = self._parent_module.py__path__() - init_path = self.py__file__() - if os.path.basename(init_path) == '__init__.py': - with open(init_path, 'rb') as f: - content = common.source_to_unicode(f.read()) - # these are strings that need to be used for namespace packages, - # the first one is ``pkgutil``, the second ``pkg_resources``. - options = ('declare_namespace(__name__)', 'extend_path(__path__') - if options[0] in content or options[1] in content: - # It is a namespace, now try to find the rest of the - # modules on sys_path or whatever the search_path is. - paths = set() - for s in search_path: - other = os.path.join(s, unicode(self.name)) - if os.path.isdir(other): - paths.add(other) - return list(paths) - # Default to this. - return [self._get_init_directory()] - - @property - def py__path__(self): - """ - Not seen here, since it's a property. The callback actually uses a - variable, so use it like:: - - foo.py__path__(sys_path) - - In case of a package, this returns Python's __path__ attribute, which - is a list of paths (strings). - Raises an AttributeError if the module is not a package. - """ - path = self._get_init_directory() - - if path is None: - raise AttributeError('Only packages have __path__ attributes.') - else: - return self._py__path__ - - @memoize_default() - def _sub_modules_dict(self): - """ - Lists modules in the directory of this module (if this module is a - package). - """ - path = self._module.path - names = {} - if path is not None and path.endswith(os.path.sep + '__init__.py'): - mods = pkgutil.iter_modules([os.path.dirname(path)]) - for module_loader, name, is_pkg in mods: - fake_n = helpers.FakeName(name) - # It's obviously a relative import to the current module. - imp = helpers.FakeImport(fake_n, self, level=1) - fake_n.parent = imp - names[name] = [fake_n] - - # TODO add something like this in the future, its cleaner than the - # import hacks. - # ``os.path`` is a hardcoded exception, because it's a - # ``sys.modules`` modification. - #if str(self.name) == 'os': - # names.append(helpers.FakeName('path', parent=self)) - - return names - - def py__class__(self): - return compiled.get_special_object(self._evaluator, 'MODULE_CLASS') - - def __getattr__(self, name): - return getattr(self._module, name) - - def __repr__(self): - return "<%s: %s>" % (type(self).__name__, self._module) diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/site.py b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/site.py deleted file mode 100644 index bf884fa..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/site.py +++ /dev/null @@ -1,110 +0,0 @@ -"""An adapted copy of relevant site-packages functionality from Python stdlib. - -This file contains some functions related to handling site-packages in Python -with jedi-specific modifications: - -- the functions operate on sys_path argument rather than global sys.path - -- in .pth files "import ..." lines that allow execution of arbitrary code are - skipped to prevent code injection into jedi interpreter - -""" - -# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, -# 2011, 2012, 2013, 2014, 2015 Python Software Foundation; All Rights Reserved - -from __future__ import print_function - -import sys -import os - - -def makepath(*paths): - dir = os.path.join(*paths) - try: - dir = os.path.abspath(dir) - except OSError: - pass - return dir, os.path.normcase(dir) - - -def _init_pathinfo(sys_path): - """Return a set containing all existing directory entries from sys_path""" - d = set() - for dir in sys_path: - try: - if os.path.isdir(dir): - dir, dircase = makepath(dir) - d.add(dircase) - except TypeError: - continue - return d - - -def addpackage(sys_path, sitedir, name, known_paths): - """Process a .pth file within the site-packages directory: - For each line in the file, either combine it with sitedir to a path - and add that to known_paths, or execute it if it starts with 'import '. - """ - if known_paths is None: - known_paths = _init_pathinfo(sys_path) - reset = 1 - else: - reset = 0 - fullname = os.path.join(sitedir, name) - try: - f = open(fullname, "r") - except OSError: - return - with f: - for n, line in enumerate(f): - if line.startswith("#"): - continue - try: - if line.startswith(("import ", "import\t")): - # Change by immerrr: don't evaluate import lines to prevent - # code injection into jedi through pth files. - # - # exec(line) - continue - line = line.rstrip() - dir, dircase = makepath(sitedir, line) - if not dircase in known_paths and os.path.exists(dir): - sys_path.append(dir) - known_paths.add(dircase) - except Exception: - print("Error processing line {:d} of {}:\n".format(n+1, fullname), - file=sys.stderr) - import traceback - for record in traceback.format_exception(*sys.exc_info()): - for line in record.splitlines(): - print(' '+line, file=sys.stderr) - print("\nRemainder of file ignored", file=sys.stderr) - break - if reset: - known_paths = None - return known_paths - - -def addsitedir(sys_path, sitedir, known_paths=None): - """Add 'sitedir' argument to sys_path if missing and handle .pth files in - 'sitedir'""" - if known_paths is None: - known_paths = _init_pathinfo(sys_path) - reset = 1 - else: - reset = 0 - sitedir, sitedircase = makepath(sitedir) - if not sitedircase in known_paths: - sys_path.append(sitedir) # Add path component - known_paths.add(sitedircase) - try: - names = os.listdir(sitedir) - except OSError: - return - names = [name for name in names if name.endswith(".pth")] - for name in sorted(names): - addpackage(sys_path, sitedir, name, known_paths) - if reset: - known_paths = None - return known_paths diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/stdlib.py b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/stdlib.py deleted file mode 100644 index f0c4346..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/stdlib.py +++ /dev/null @@ -1,280 +0,0 @@ -""" -Implementations of standard library functions, because it's not possible to -understand them with Jedi. - -To add a new implementation, create a function and add it to the -``_implemented`` dict at the bottom of this module. - -Note that this module exists only to implement very specific functionality in -the standard library. The usual way to understand the standard library is the -compiled module that returns the types for C-builtins. -""" -import collections -import re - -from jedi._compatibility import unicode -from jedi.common import unite -from jedi.evaluate import compiled -from jedi.evaluate import representation as er -from jedi.evaluate import iterable -from jedi.parser import ParserWithRecovery -from jedi.parser import tree -from jedi import debug -from jedi.evaluate import precedence -from jedi.evaluate import param -from jedi.evaluate import analysis - - -class NotInStdLib(LookupError): - pass - - -def execute(evaluator, obj, arguments): - try: - obj_name = str(obj.name) - except AttributeError: - pass - else: - if obj.parent == evaluator.BUILTINS: - module_name = 'builtins' - elif isinstance(obj.parent, tree.Module): - module_name = str(obj.parent.name) - else: - module_name = '' - - # for now we just support builtin functions. - try: - func = _implemented[module_name][obj_name] - except KeyError: - pass - else: - return func(evaluator, obj, arguments) - raise NotInStdLib() - - -def _follow_param(evaluator, arguments, index): - try: - key, values = list(arguments.unpack())[index] - except IndexError: - return set() - else: - return unite(evaluator.eval_element(v) for v in values) - - -def argument_clinic(string, want_obj=False, want_scope=False, want_arguments=False): - """ - Works like Argument Clinic (PEP 436), to validate function params. - """ - clinic_args = [] - allow_kwargs = False - optional = False - while string: - # Optional arguments have to begin with a bracket. And should always be - # at the end of the arguments. This is therefore not a proper argument - # clinic implementation. `range()` for exmple allows an optional start - # value at the beginning. - match = re.match('(?:(?:(\[),? ?|, ?|)(\w+)|, ?/)\]*', string) - string = string[len(match.group(0)):] - if not match.group(2): # A slash -> allow named arguments - allow_kwargs = True - continue - optional = optional or bool(match.group(1)) - word = match.group(2) - clinic_args.append((word, optional, allow_kwargs)) - - def f(func): - def wrapper(evaluator, obj, arguments): - debug.dbg('builtin start %s' % obj, color='MAGENTA') - try: - lst = list(arguments.eval_argument_clinic(clinic_args)) - except ValueError: - return set() - else: - kwargs = {} - if want_scope: - kwargs['scope'] = arguments.scope() - if want_obj: - kwargs['obj'] = obj - if want_arguments: - kwargs['arguments'] = arguments - return func(evaluator, *lst, **kwargs) - finally: - debug.dbg('builtin end', color='MAGENTA') - - return wrapper - return f - - -@argument_clinic('object, name[, default], /') -def builtins_getattr(evaluator, objects, names, defaults=None): - # follow the first param - for obj in objects: - if not isinstance(obj, (er.Instance, er.Class, tree.Module, compiled.CompiledObject)): - debug.warning('getattr called without instance') - continue - - for name in names: - if precedence.is_string(name): - return evaluator.find_types(obj, name.obj) - else: - debug.warning('getattr called without str') - continue - return set() - - -@argument_clinic('object[, bases, dict], /') -def builtins_type(evaluator, objects, bases, dicts): - if bases or dicts: - # It's a type creation... maybe someday... - return set() - else: - return set([o.py__class__() for o in objects]) - - -class SuperInstance(er.Instance): - """To be used like the object ``super`` returns.""" - def __init__(self, evaluator, cls): - su = cls.py_mro()[1] - super().__init__(evaluator, su and su[0] or self) - - -@argument_clinic('[type[, obj]], /', want_scope=True) -def builtins_super(evaluator, types, objects, scope): - # TODO make this able to detect multiple inheritance super - accept = (tree.Function, er.FunctionExecution) - if scope.isinstance(*accept): - wanted = (tree.Class, er.Instance) - cls = scope.get_parent_until(accept + wanted, - include_current=False) - if isinstance(cls, wanted): - if isinstance(cls, tree.Class): - cls = er.Class(evaluator, cls) - elif isinstance(cls, er.Instance): - cls = cls.base - su = cls.py__bases__() - if su: - return evaluator.execute(su[0]) - return set() - - -@argument_clinic('sequence, /', want_obj=True, want_arguments=True) -def builtins_reversed(evaluator, sequences, obj, arguments): - # While we could do without this variable (just by using sequences), we - # want static analysis to work well. Therefore we need to generated the - # values again. - first_arg = next(arguments.as_tuple())[0] - ordered = list(iterable.py__iter__(evaluator, sequences, first_arg)) - - rev = [iterable.AlreadyEvaluated(o) for o in reversed(ordered)] - # Repack iterator values and then run it the normal way. This is - # necessary, because `reversed` is a function and autocompletion - # would fail in certain cases like `reversed(x).__iter__` if we - # just returned the result directly. - rev = iterable.AlreadyEvaluated( - [iterable.FakeSequence(evaluator, rev, 'list')] - ) - return set([er.Instance(evaluator, obj, param.Arguments(evaluator, [rev]))]) - - -@argument_clinic('obj, type, /', want_arguments=True) -def builtins_isinstance(evaluator, objects, types, arguments): - bool_results = set([]) - for o in objects: - try: - mro_func = o.py__class__().py__mro__ - except AttributeError: - # This is temporary. Everything should have a class attribute in - # Python?! Maybe we'll leave it here, because some numpy objects or - # whatever might not. - return set([compiled.create(True), compiled.create(False)]) - - mro = mro_func() - - for cls_or_tup in types: - if cls_or_tup.is_class(): - bool_results.add(cls_or_tup in mro) - elif str(cls_or_tup.name) == 'tuple' \ - and cls_or_tup.get_parent_scope() == evaluator.BUILTINS: - # Check for tuples. - classes = unite(cls_or_tup.py__iter__()) - bool_results.add(any(cls in mro for cls in classes)) - else: - _, nodes = list(arguments.unpack())[1] - for node in nodes: - message = 'TypeError: isinstance() arg 2 must be a ' \ - 'class, type, or tuple of classes and types, ' \ - 'not %s.' % cls_or_tup - analysis.add(evaluator, 'type-error-isinstance', node, message) - - return set(compiled.create(evaluator, x) for x in bool_results) - - -def collections_namedtuple(evaluator, obj, arguments): - """ - Implementation of the namedtuple function. - - This has to be done by processing the namedtuple class template and - evaluating the result. - - .. note:: |jedi| only supports namedtuples on Python >2.6. - - """ - # Namedtuples are not supported on Python 2.6 - if not hasattr(collections, '_class_template'): - return set() - - # Process arguments - # TODO here we only use one of the types, we should use all. - name = list(_follow_param(evaluator, arguments, 0))[0].obj - _fields = list(_follow_param(evaluator, arguments, 1))[0] - if isinstance(_fields, compiled.CompiledObject): - fields = _fields.obj.replace(',', ' ').split() - elif isinstance(_fields, iterable.Array): - try: - fields = [v.obj for v in unite(_fields.py__iter__())] - except AttributeError: - return set() - else: - return set() - - # Build source - source = collections._class_template.format( - typename=name, - field_names=fields, - num_fields=len(fields), - arg_list=', '.join(fields), - repr_fmt=', '.join(collections._repr_template.format(name=name) for name in fields), - field_defs='\n'.join(collections._field_template.format(index=index, name=name) - for index, name in enumerate(fields)) - ) - - # Parse source - generated_class = ParserWithRecovery(evaluator.grammar, unicode(source)).module.subscopes[0] - return set([er.Class(evaluator, generated_class)]) - - -@argument_clinic('first, /') -def _return_first_param(evaluator, firsts): - return firsts - - -_implemented = { - 'builtins': { - 'getattr': builtins_getattr, - 'type': builtins_type, - 'super': builtins_super, - 'reversed': builtins_reversed, - 'isinstance': builtins_isinstance, - }, - 'copy': { - 'copy': _return_first_param, - 'deepcopy': _return_first_param, - }, - 'json': { - 'load': lambda *args: set(), - 'loads': lambda *args: set(), - }, - 'collections': { - 'namedtuple': collections_namedtuple, - }, -} diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/sys_path.py b/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/sys_path.py deleted file mode 100644 index f69b1a4..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/evaluate/sys_path.py +++ /dev/null @@ -1,284 +0,0 @@ -import glob -import os -import sys -from jedi.evaluate.site import addsitedir - -from jedi._compatibility import exec_function, unicode -from jedi.parser import tree -from jedi.parser import ParserWithRecovery -from jedi.evaluate.cache import memoize_default -from jedi import debug -from jedi import common -from jedi.parser.utils import load_parser, save_parser - - -def get_venv_path(venv): - """Get sys.path for specified virtual environment.""" - sys_path = _get_venv_path_dirs(venv) - with common.ignored(ValueError): - sys_path.remove('') - sys_path = _get_sys_path_with_egglinks(sys_path) - # As of now, get_venv_path_dirs does not scan built-in pythonpath and - # user-local site-packages, let's approximate them using path from Jedi - # interpreter. - return sys_path + sys.path - - - -def _get_sys_path_with_egglinks(sys_path): - """Find all paths including those referenced by egg-links. - - Egg-link-referenced directories are inserted into path immediately before - the directory on which their links were found. Such directories are not - taken into consideration by normal import mechanism, but they are traversed - when doing pkg_resources.require. - """ - result = [] - for p in sys_path: - # pkg_resources does not define a specific order for egg-link files - # using os.listdir to enumerate them, we're sorting them to have - # reproducible tests. - for egg_link in sorted(glob.glob(os.path.join(p, '*.egg-link'))): - with open(egg_link) as fd: - for line in fd: - line = line.strip() - if line: - result.append(os.path.join(p, line)) - # pkg_resources package only interprets the first - # non-empty line in egg-link files. - break - result.append(p) - return result - - -def _get_venv_path_dirs(venv): - """Get sys.path for venv without starting up the interpreter.""" - venv = os.path.abspath(venv) - sitedir = _get_venv_sitepackages(venv) - sys_path = [] - addsitedir(sys_path, sitedir) - return sys_path - - -def _get_venv_sitepackages(venv): - if os.name == 'nt': - p = os.path.join(venv, 'lib', 'site-packages') - else: - p = os.path.join(venv, 'lib', 'python%d.%d' % sys.version_info[:2], - 'site-packages') - return p - - -def _execute_code(module_path, code): - c = "import os; from os.path import *; result=%s" - variables = {'__file__': module_path} - try: - exec_function(c % code, variables) - except Exception: - debug.warning('sys.path manipulation detected, but failed to evaluate.') - else: - try: - res = variables['result'] - if isinstance(res, str): - return [os.path.abspath(res)] - except KeyError: - pass - return [] - - -def _paths_from_assignment(evaluator, expr_stmt): - """ - Extracts the assigned strings from an assignment that looks as follows:: - - >>> sys.path[0:0] = ['module/path', 'another/module/path'] - - This function is in general pretty tolerant (and therefore 'buggy'). - However, it's not a big issue usually to add more paths to Jedi's sys_path, - because it will only affect Jedi in very random situations and by adding - more paths than necessary, it usually benefits the general user. - """ - for assignee, operator in zip(expr_stmt.children[::2], expr_stmt.children[1::2]): - try: - assert operator in ['=', '+='] - assert tree.is_node(assignee, 'power', 'atom_expr') and \ - len(assignee.children) > 1 - c = assignee.children - assert c[0].type == 'name' and c[0].value == 'sys' - trailer = c[1] - assert trailer.children[0] == '.' and trailer.children[1].value == 'path' - # TODO Essentially we're not checking details on sys.path - # manipulation. Both assigment of the sys.path and changing/adding - # parts of the sys.path are the same: They get added to the current - # sys.path. - """ - execution = c[2] - assert execution.children[0] == '[' - subscript = execution.children[1] - assert subscript.type == 'subscript' - assert ':' in subscript.children - """ - except AssertionError: - continue - - from jedi.evaluate.iterable import py__iter__ - from jedi.evaluate.precedence import is_string - types = evaluator.eval_element(expr_stmt) - for types in py__iter__(evaluator, types, expr_stmt): - for typ in types: - if is_string(typ): - yield typ.obj - - -def _paths_from_list_modifications(module_path, trailer1, trailer2): - """ extract the path from either "sys.path.append" or "sys.path.insert" """ - # Guarantee that both are trailers, the first one a name and the second one - # a function execution with at least one param. - if not (tree.is_node(trailer1, 'trailer') and trailer1.children[0] == '.' - and tree.is_node(trailer2, 'trailer') and trailer2.children[0] == '(' - and len(trailer2.children) == 3): - return [] - - name = trailer1.children[1].value - if name not in ['insert', 'append']: - return [] - arg = trailer2.children[1] - if name == 'insert' and len(arg.children) in (3, 4): # Possible trailing comma. - arg = arg.children[2] - return _execute_code(module_path, arg.get_code()) - - -def _check_module(evaluator, module): - """ - Detect sys.path modifications within module. - """ - def get_sys_path_powers(names): - for name in names: - power = name.parent.parent - if tree.is_node(power, 'power', 'atom_expr'): - c = power.children - if isinstance(c[0], tree.Name) and c[0].value == 'sys' \ - and tree.is_node(c[1], 'trailer'): - n = c[1].children[1] - if isinstance(n, tree.Name) and n.value == 'path': - yield name, power - - sys_path = list(evaluator.sys_path) # copy - try: - possible_names = module.used_names['path'] - except KeyError: - # module.used_names is MergedNamesDict whose getitem never throws - # keyerror, this is superfluous. - pass - else: - for name, power in get_sys_path_powers(possible_names): - stmt = name.get_definition() - if len(power.children) >= 4: - sys_path.extend(_paths_from_list_modifications(module.path, *power.children[2:4])) - elif name.get_definition().type == 'expr_stmt': - sys_path.extend(_paths_from_assignment(evaluator, stmt)) - return sys_path - - -@memoize_default(evaluator_is_first_arg=True, default=[]) -def sys_path_with_modifications(evaluator, module): - if module.path is None: - # Support for modules without a path is bad, therefore return the - # normal path. - return list(evaluator.sys_path) - - curdir = os.path.abspath(os.curdir) - #TODO why do we need a chdir? - with common.ignored(OSError): - os.chdir(os.path.dirname(module.path)) - - buildout_script_paths = set() - - result = _check_module(evaluator, module) - result += _detect_django_path(module.path) - for buildout_script in _get_buildout_scripts(module.path): - for path in _get_paths_from_buildout_script(evaluator, buildout_script): - buildout_script_paths.add(path) - # cleanup, back to old directory - os.chdir(curdir) - return list(result) + list(buildout_script_paths) - - -def _get_paths_from_buildout_script(evaluator, buildout_script): - def load(buildout_script): - try: - with open(buildout_script, 'rb') as f: - source = common.source_to_unicode(f.read()) - except IOError: - debug.dbg('Error trying to read buildout_script: %s', buildout_script) - return - - p = ParserWithRecovery(evaluator.grammar, source, buildout_script) - save_parser(buildout_script, p) - return p.module - - cached = load_parser(buildout_script) - module = cached and cached.module or load(buildout_script) - if not module: - return - - for path in _check_module(evaluator, module): - yield path - - -def traverse_parents(path): - while True: - new = os.path.dirname(path) - if new == path: - return - path = new - yield path - - -def _get_parent_dir_with_file(path, filename): - for parent in traverse_parents(path): - if os.path.isfile(os.path.join(parent, filename)): - return parent - return None - - -def _detect_django_path(module_path): - """ Detects the path of the very well known Django library (if used) """ - result = [] - - for parent in traverse_parents(module_path): - with common.ignored(IOError): - with open(parent + os.path.sep + 'manage.py'): - debug.dbg('Found django path: %s', module_path) - result.append(parent) - return result - - -def _get_buildout_scripts(module_path): - """ - if there is a 'buildout.cfg' file in one of the parent directories of the - given module it will return a list of all files in the buildout bin - directory that look like python files. - - :param module_path: absolute path to the module. - :type module_path: str - """ - project_root = _get_parent_dir_with_file(module_path, 'buildout.cfg') - if not project_root: - return [] - bin_path = os.path.join(project_root, 'bin') - if not os.path.exists(bin_path): - return [] - extra_module_paths = [] - for filename in os.listdir(bin_path): - try: - filepath = os.path.join(bin_path, filename) - with open(filepath, 'r') as f: - firstline = f.readline() - if firstline.startswith('#!') and 'python' in firstline: - extra_module_paths.append(filepath) - except (UnicodeDecodeError, IOError) as e: - # Probably a binary file; permission error or race cond. because file got deleted - # ignore - debug.warning(unicode(e)) - continue - return extra_module_paths diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/__init__.py b/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/__init__.py deleted file mode 100644 index 22f3860..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/__init__.py +++ /dev/null @@ -1,409 +0,0 @@ -""" -The ``Parser`` tries to convert the available Python code in an easy to read -format, something like an abstract syntax tree. The classes who represent this -tree, are sitting in the :mod:`jedi.parser.tree` module. - -The Python module ``tokenize`` is a very important part in the ``Parser``, -because it splits the code into different words (tokens). Sometimes it looks a -bit messy. Sorry for that! You might ask now: "Why didn't you use the ``ast`` -module for this? Well, ``ast`` does a very good job understanding proper Python -code, but fails to work as soon as there's a single line of broken code. - -There's one important optimization that needs to be known: Statements are not -being parsed completely. ``Statement`` is just a representation of the tokens -within the statement. This lowers memory usage and cpu time and reduces the -complexity of the ``Parser`` (there's another parser sitting inside -``Statement``, which produces ``Array`` and ``Call``). -""" -import os -import re - -from jedi.parser import tree as pt -from jedi.parser import tokenize -from jedi.parser.token import (DEDENT, INDENT, ENDMARKER, NEWLINE, NUMBER, - STRING) -from jedi.parser.pgen2.pgen import generate_grammar -from jedi.parser.pgen2.parse import PgenParser - -OPERATOR_KEYWORDS = 'and', 'for', 'if', 'else', 'in', 'is', 'lambda', 'not', 'or' -# Not used yet. In the future I intend to add something like KeywordStatement -STATEMENT_KEYWORDS = 'assert', 'del', 'global', 'nonlocal', 'raise', \ - 'return', 'yield', 'pass', 'continue', 'break' - - -_loaded_grammars = {} - - -class ParseError(Exception): - """ - Signals you that the code you fed the Parser was not correct Python code. - """ - - -def load_grammar(version='3.4'): - # For now we only support two different Python syntax versions: The latest - # Python 3 and Python 2. This may change. - if version in ('3.2', '3.3'): - version = '3.4' - elif version == '2.6': - version = '2.7' - - file = 'grammar' + version + '.txt' - - global _loaded_grammars - path = os.path.join(os.path.dirname(__file__), file) - try: - return _loaded_grammars[path] - except KeyError: - return _loaded_grammars.setdefault(path, generate_grammar(path)) - - -class ParserSyntaxError(object): - def __init__(self, message, position): - self.message = message - self.position = position - - -class Parser(object): - AST_MAPPING = { - 'expr_stmt': pt.ExprStmt, - 'classdef': pt.Class, - 'funcdef': pt.Function, - 'file_input': pt.Module, - 'import_name': pt.ImportName, - 'import_from': pt.ImportFrom, - 'break_stmt': pt.KeywordStatement, - 'continue_stmt': pt.KeywordStatement, - 'return_stmt': pt.ReturnStmt, - 'raise_stmt': pt.KeywordStatement, - 'yield_expr': pt.YieldExpr, - 'del_stmt': pt.KeywordStatement, - 'pass_stmt': pt.KeywordStatement, - 'global_stmt': pt.GlobalStmt, - 'nonlocal_stmt': pt.KeywordStatement, - 'print_stmt': pt.KeywordStatement, - 'assert_stmt': pt.AssertStmt, - 'if_stmt': pt.IfStmt, - 'with_stmt': pt.WithStmt, - 'for_stmt': pt.ForStmt, - 'while_stmt': pt.WhileStmt, - 'try_stmt': pt.TryStmt, - 'comp_for': pt.CompFor, - 'decorator': pt.Decorator, - 'lambdef': pt.Lambda, - 'old_lambdef': pt.Lambda, - 'lambdef_nocond': pt.Lambda, - } - - def __init__(self, grammar, source, start_symbol='file_input', - tokenizer=None, start_parsing=True): - # Todo Remove start_parsing (with False) - - self._used_names = {} - self._scope_names_stack = [{}] - self._last_failed_start_pos = (0, 0) - self._global_names = [] - - # For the fast parser. - self.position_modifier = pt.PositionModifier() - - self._added_newline = False - # The Python grammar needs a newline at the end of each statement. - if not source.endswith('\n') and start_symbol == 'file_input': - source += '\n' - self._added_newline = True - - self.source = source - self._start_symbol = start_symbol - self._grammar = grammar - - self._parsed = None - - if start_parsing: - if tokenizer is None: - tokenizer = tokenize.source_tokens(source, use_exact_op_types=True) - self.parse(tokenizer) - - def parse(self, tokenizer): - if self._parsed is not None: - return self._parsed - - start_number = self._grammar.symbol2number[self._start_symbol] - pgen_parser = PgenParser( - self._grammar, self.convert_node, self.convert_leaf, - self.error_recovery, start_number - ) - - try: - self._parsed = pgen_parser.parse(tokenizer) - finally: - self.stack = pgen_parser.stack - - if self._start_symbol == 'file_input' != self._parsed.type: - # If there's only one statement, we get back a non-module. That's - # not what we want, we want a module, so we add it here: - self._parsed = self.convert_node(self._grammar, - self._grammar.symbol2number['file_input'], - [self._parsed]) - - if self._added_newline: - self.remove_last_newline() - - def get_parsed_node(self): - # TODO rename to get_root_node - return self._parsed - - def error_recovery(self, grammar, stack, arcs, typ, value, start_pos, prefix, - add_token_callback): - raise ParseError - - def convert_node(self, grammar, type, children): - """ - Convert raw node information to a Node instance. - - This is passed to the parser driver which calls it whenever a reduction of a - grammar rule produces a new complete node, so that the tree is build - strictly bottom-up. - """ - symbol = grammar.number2symbol[type] - try: - new_node = Parser.AST_MAPPING[symbol](children) - except KeyError: - new_node = pt.Node(symbol, children) - - # We need to check raw_node always, because the same node can be - # returned by convert multiple times. - if symbol == 'global_stmt': - self._global_names += new_node.get_global_names() - elif isinstance(new_node, pt.Lambda): - new_node.names_dict = self._scope_names_stack.pop() - elif isinstance(new_node, (pt.ClassOrFunc, pt.Module)) \ - and symbol in ('funcdef', 'classdef', 'file_input'): - # scope_name_stack handling - scope_names = self._scope_names_stack.pop() - if isinstance(new_node, pt.ClassOrFunc): - n = new_node.name - scope_names[n.value].remove(n) - # Set the func name of the current node - arr = self._scope_names_stack[-1].setdefault(n.value, []) - arr.append(n) - new_node.names_dict = scope_names - elif isinstance(new_node, pt.CompFor): - # The name definitions of comprehenions shouldn't be part of the - # current scope. They are part of the comprehension scope. - for n in new_node.get_defined_names(): - self._scope_names_stack[-1][n.value].remove(n) - return new_node - - def convert_leaf(self, grammar, type, value, prefix, start_pos): - # print('leaf', repr(value), token.tok_name[type]) - if type == tokenize.NAME: - if value in grammar.keywords: - if value in ('def', 'class', 'lambda'): - self._scope_names_stack.append({}) - - return pt.Keyword(self.position_modifier, value, start_pos, prefix) - else: - name = pt.Name(self.position_modifier, value, start_pos, prefix) - # Keep a listing of all used names - arr = self._used_names.setdefault(name.value, []) - arr.append(name) - arr = self._scope_names_stack[-1].setdefault(name.value, []) - arr.append(name) - return name - elif type == STRING: - return pt.String(self.position_modifier, value, start_pos, prefix) - elif type == NUMBER: - return pt.Number(self.position_modifier, value, start_pos, prefix) - elif type == NEWLINE: - return pt.Newline(self.position_modifier, value, start_pos, prefix) - elif type == INDENT: - return pt.Indent(self.position_modifier, value, start_pos, prefix) - elif type == DEDENT: - return pt.Dedent(self.position_modifier, value, start_pos, prefix) - elif type == ENDMARKER: - return pt.EndMarker(self.position_modifier, value, start_pos, prefix) - else: - return pt.Operator(self.position_modifier, value, start_pos, prefix) - - def remove_last_newline(self): - """ - In all of this we need to work with _start_pos, because if we worked - with start_pos, we would need to check the position_modifier as well - (which is accounted for in the start_pos property). - """ - endmarker = self._parsed.children[-1] - # The newline is either in the endmarker as a prefix or the previous - # leaf as a newline token. - prefix = endmarker.prefix - if prefix.endswith('\n'): - endmarker.prefix = prefix = prefix[:-1] - last_end = 0 - if '\n' not in prefix: - # Basically if the last line doesn't end with a newline. we - # have to add the previous line's end_position. - try: - last_end = endmarker.get_previous_leaf().end_pos[1] - except IndexError: - pass - last_line = re.sub('.*\n', '', prefix) - endmarker._start_pos = endmarker._start_pos[0] - 1, last_end + len(last_line) - else: - try: - newline = endmarker.get_previous_leaf() - except IndexError: - return # This means that the parser is empty. - while True: - if newline.value == '': - # Must be a DEDENT, just continue. - try: - newline = newline.get_previous_leaf() - except IndexError: - # If there's a statement that fails to be parsed, there - # will be no previous leaf. So just ignore it. - break - elif newline.value != '\n': - # TODO REMOVE, error recovery was simplified. - # This may happen if error correction strikes and removes - # a whole statement including '\n'. - break - else: - newline.value = '' - if self._last_failed_start_pos > newline._start_pos: - # It may be the case that there was a syntax error in a - # function. In that case error correction removes the - # right newline. So we use the previously assigned - # _last_failed_start_pos variable to account for that. - endmarker._start_pos = self._last_failed_start_pos - else: - endmarker._start_pos = newline._start_pos - break - - -class ParserWithRecovery(Parser): - """ - This class is used to parse a Python file, it then divides them into a - class structure of different scopes. - - :param grammar: The grammar object of pgen2. Loaded by load_grammar. - :param source: The codebase for the parser. Must be unicode. - :param module_path: The path of the module in the file system, may be None. - :type module_path: str - """ - def __init__(self, grammar, source, module_path=None, tokenizer=None, - start_parsing=True): - self.syntax_errors = [] - - self._omit_dedent_list = [] - self._indent_counter = 0 - - # TODO do print absolute import detection here. - # try: - # del python_grammar_no_print_statement.keywords["print"] - # except KeyError: - # pass # Doesn't exist in the Python 3 grammar. - - # if self.options["print_function"]: - # python_grammar = pygram.python_grammar_no_print_statement - # else: - super(ParserWithRecovery, self).__init__( - grammar, source, - tokenizer=tokenizer, - start_parsing=start_parsing - ) - if start_parsing: - self.module = self._parsed - self.module.used_names = self._used_names - self.module.path = module_path - self.module.global_names = self._global_names - - def parse(self, tokenizer): - return super(ParserWithRecovery, self).parse(self._tokenize(self._tokenize(tokenizer))) - - def error_recovery(self, grammar, stack, arcs, typ, value, start_pos, prefix, - add_token_callback): - """ - This parser is written in a dynamic way, meaning that this parser - allows using different grammars (even non-Python). However, error - recovery is purely written for Python. - """ - def current_suite(stack): - # For now just discard everything that is not a suite or - # file_input, if we detect an error. - for index, (dfa, state, (type_, nodes)) in reversed(list(enumerate(stack))): - # `suite` can sometimes be only simple_stmt, not stmt. - symbol = grammar.number2symbol[type_] - if symbol == 'file_input': - break - elif symbol == 'suite' and len(nodes) > 1: - # suites without an indent in them get discarded. - break - elif symbol == 'simple_stmt' and len(nodes) > 1: - # simple_stmt can just be turned into a Node, if there are - # enough statements. Ignore the rest after that. - break - return index, symbol, nodes - - index, symbol, nodes = current_suite(stack) - if symbol == 'simple_stmt': - index -= 2 - (_, _, (type_, suite_nodes)) = stack[index] - symbol = grammar.number2symbol[type_] - suite_nodes.append(pt.Node(symbol, list(nodes))) - # Remove - nodes[:] = [] - nodes = suite_nodes - stack[index] - - # print('err', token.tok_name[typ], repr(value), start_pos, len(stack), index) - if self._stack_removal(grammar, stack, arcs, index + 1, value, start_pos): - add_token_callback(typ, value, start_pos, prefix) - else: - if typ == INDENT: - # For every deleted INDENT we have to delete a DEDENT as well. - # Otherwise the parser will get into trouble and DEDENT too early. - self._omit_dedent_list.append(self._indent_counter) - else: - error_leaf = pt.ErrorLeaf(self.position_modifier, typ, value, start_pos, prefix) - stack[-1][2][1].append(error_leaf) - - def _stack_removal(self, grammar, stack, arcs, start_index, value, start_pos): - failed_stack = [] - found = False - all_nodes = [] - for dfa, state, (typ, nodes) in stack[start_index:]: - if nodes: - found = True - if found: - symbol = grammar.number2symbol[typ] - failed_stack.append((symbol, nodes)) - all_nodes += nodes - if nodes and nodes[0] in ('def', 'class', 'lambda'): - self._scope_names_stack.pop() - if failed_stack: - stack[start_index - 1][2][1].append(pt.ErrorNode(all_nodes)) - - self._last_failed_start_pos = start_pos - - stack[start_index:] = [] - return failed_stack - - def _tokenize(self, tokenizer): - for typ, value, start_pos, prefix in tokenizer: - # print(tokenize.tok_name[typ], repr(value), start_pos, repr(prefix)) - if typ == DEDENT: - # We need to count indents, because if we just omit any DEDENT, - # we might omit them in the wrong place. - o = self._omit_dedent_list - if o and o[-1] == self._indent_counter: - o.pop() - continue - - self._indent_counter -= 1 - elif typ == INDENT: - self._indent_counter += 1 - - yield typ, value, start_pos, prefix - - def __repr__(self): - return "<%s: %s>" % (type(self).__name__, self.module) diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/__pycache__/__init__.cpython-35.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/__pycache__/__init__.cpython-35.pyc deleted file mode 100644 index 76178be..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/__pycache__/__init__.cpython-35.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/__pycache__/__init__.cpython-36.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/__pycache__/__init__.cpython-36.pyc deleted file mode 100644 index 1d6a40d..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/__pycache__/__init__.cpython-36.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/__pycache__/fast.cpython-35.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/__pycache__/fast.cpython-35.pyc deleted file mode 100644 index 0f99ff5..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/__pycache__/fast.cpython-35.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/__pycache__/fast.cpython-36.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/__pycache__/fast.cpython-36.pyc deleted file mode 100644 index 1c9eab1..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/__pycache__/fast.cpython-36.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/__pycache__/token.cpython-35.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/__pycache__/token.cpython-35.pyc deleted file mode 100644 index 3f4c430..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/__pycache__/token.cpython-35.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/__pycache__/token.cpython-36.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/__pycache__/token.cpython-36.pyc deleted file mode 100644 index ebb6cc1..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/__pycache__/token.cpython-36.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/__pycache__/tokenize.cpython-35.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/__pycache__/tokenize.cpython-35.pyc deleted file mode 100644 index 54ed5b8..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/__pycache__/tokenize.cpython-35.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/__pycache__/tokenize.cpython-36.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/__pycache__/tokenize.cpython-36.pyc deleted file mode 100644 index 605cb4f..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/__pycache__/tokenize.cpython-36.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/__pycache__/tree.cpython-35.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/__pycache__/tree.cpython-35.pyc deleted file mode 100644 index 319854f..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/__pycache__/tree.cpython-35.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/__pycache__/tree.cpython-36.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/__pycache__/tree.cpython-36.pyc deleted file mode 100644 index f0bb362..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/__pycache__/tree.cpython-36.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/__pycache__/utils.cpython-35.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/__pycache__/utils.cpython-35.pyc deleted file mode 100644 index 18f8ed5..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/__pycache__/utils.cpython-35.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/__pycache__/utils.cpython-36.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/__pycache__/utils.cpython-36.pyc deleted file mode 100644 index 9067cf9..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/__pycache__/utils.cpython-36.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/fast.py b/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/fast.py deleted file mode 100644 index 9c471fd..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/fast.py +++ /dev/null @@ -1,621 +0,0 @@ -""" -Basically a parser that is faster, because it tries to parse only parts and if -anything changes, it only reparses the changed parts. But because it's not -finished (and still not working as I want), I won't document it any further. -""" -import re -from itertools import chain - -from jedi._compatibility import use_metaclass -from jedi import settings -from jedi.parser import ParserWithRecovery -from jedi.parser import tree -from jedi.parser.utils import underscore_memoization, parser_cache -from jedi import debug -from jedi.parser.tokenize import (source_tokens, NEWLINE, - ENDMARKER, INDENT, DEDENT) - -FLOWS = 'if', 'else', 'elif', 'while', 'with', 'try', 'except', 'finally', 'for' - - -class FastModule(tree.Module): - type = 'file_input' - - def __init__(self, module_path): - super(FastModule, self).__init__([]) - self.modules = [] - self.reset_caches() - self.names_dict = {} - self.path = module_path - - def reset_caches(self): - self.modules = [] - try: - del self._used_names # Remove the used names cache. - except AttributeError: - pass # It was never used. - - @property - @underscore_memoization - def used_names(self): - return MergedNamesDict([m.used_names for m in self.modules]) - - @property - def global_names(self): - return [name for m in self.modules for name in m.global_names] - - @property - def error_statements(self): - return [e for m in self.modules for e in m.error_statements] - - def __repr__(self): - return "" % (type(self).__name__, self.name, - self.start_pos[0], self.end_pos[0]) - - # To avoid issues with with the `parser.ParserWithRecovery`, we need - # setters that do nothing, because if pickle comes along and sets those - # values. - @global_names.setter - def global_names(self, value): - pass - - @error_statements.setter - def error_statements(self, value): - pass - - @used_names.setter - def used_names(self, value): - pass - - -class MergedNamesDict(object): - def __init__(self, dicts): - self.dicts = dicts - - def __iter__(self): - return iter(set(key for dct in self.dicts for key in dct)) - - def __getitem__(self, value): - return list(chain.from_iterable(dct.get(value, []) for dct in self.dicts)) - - def items(self): - dct = {} - for d in self.dicts: - for key, values in d.items(): - try: - dct_values = dct[key] - dct_values += values - except KeyError: - dct[key] = list(values) - return dct.items() - - def values(self): - lst = [] - for dct in self.dicts: - lst += dct.values() - return lst - - -class CachedFastParser(type): - """ This is a metaclass for caching `FastParser`. """ - def __call__(self, grammar, source, module_path=None): - if not settings.fast_parser: - return ParserWithRecovery(grammar, source, module_path) - - pi = parser_cache.get(module_path, None) - if pi is None or isinstance(pi.parser, ParserWithRecovery): - p = super(CachedFastParser, self).__call__(grammar, source, module_path) - else: - p = pi.parser # pi is a `cache.ParserCacheItem` - p.update(source) - return p - - -class ParserNode(object): - def __init__(self, fast_module, parser, source): - self._fast_module = fast_module - self.parent = None - self._node_children = [] - - self.source = source - self.hash = hash(source) - self.parser = parser - if source: - self._end_pos = parser.module.end_pos - else: - self._end_pos = 1, 0 - - try: - # With fast_parser we have either 1 subscope or only statements. - self._content_scope = parser.module.subscopes[0] - # A parsed node's content will be in the first indent, because - # everything that's parsed is within this subscope. - self._is_class_or_def = True - except IndexError: - self._content_scope = parser.module - self._is_class_or_def = False - else: - self._rewrite_last_newline() - - # We need to be able to reset the original children of a parser. - self._old_children = list(self._content_scope.children) - - def is_root_node(self): - return self.parent is None - - def _rewrite_last_newline(self): - """ - The ENDMARKER can contain a newline in the prefix. However this prefix - really belongs to the function - respectively to the next function or - parser node. If we don't rewrite that newline, we end up with a newline - in the wrong position, i.d. at the end of the file instead of in the - middle. - """ - c = self._content_scope.children - if tree.is_node(c[-1], 'suite'): # In a simple_stmt there's no DEDENT. - end_marker = self.parser.module.children[-1] - # Set the DEDENT prefix instead of the ENDMARKER. - c[-1].children[-1].prefix = end_marker.prefix - end_marker.prefix = '' - - def __repr__(self): - module = self.parser.module - try: - return '<%s: %s-%s>' % (type(self).__name__, module.start_pos, module.end_pos) - except IndexError: - # There's no module yet. - return '<%s: empty>' % type(self).__name__ - - @property - def end_pos(self): - return self._end_pos[0] + self.parser.position_modifier.line, self._end_pos[1] - - def reset_node(self): - """ - Removes changes that were applied in this class. - """ - self._node_children = [] - scope = self._content_scope - scope.children = list(self._old_children) - try: - # This works if it's a MergedNamesDict. - # We are correcting it, because the MergedNamesDicts are artificial - # and can change after closing a node. - scope.names_dict = scope.names_dict.dicts[0] - except AttributeError: - pass - - def close(self): - """ - Closes the current parser node. This means that after this no further - nodes should be added anymore. - """ - # We only need to replace the dict if multiple dictionaries are used: - if self._node_children: - dcts = [n.parser.module.names_dict for n in self._node_children] - # Need to insert the own node as well. - dcts.insert(0, self._content_scope.names_dict) - self._content_scope.names_dict = MergedNamesDict(dcts) - endmarker = self.parser.get_parsed_node().children[-1] - assert endmarker.type == 'endmarker' - last_parser = self._node_children[-1].parser - endmarker.start_pos = last_parser.get_parsed_node().end_pos - - @property - def _indent(self): - if self.is_root_node(): - return 0 - - return self.parser.module.children[0].start_pos[1] - - def add_node(self, node, start_line, indent): - """ - Adding a node means adding a node that was either just parsed or one - that can be reused. - """ - # Content that is not a subscope can never be part of the current node, - # because it's basically a sister node, that sits next to it and not - # within it. - if (self._indent >= indent or not self._is_class_or_def) and \ - not self.is_root_node(): - self.close() - return self.parent.add_node(node, start_line, indent) - - # Changing the line offsets is very important, because if they don't - # fit, all the start_pos values will be wrong. - m = node.parser.module - node.parser.position_modifier.line = start_line - 1 - self._fast_module.modules.append(m) - node.parent = self - - self._node_children.append(node) - - # Insert parser objects into current structure. We only need to set the - # parents and children in a good way. - scope = self._content_scope - for child in m.children: - child.parent = scope - scope.children.append(child) - - return node - - def all_sub_nodes(self): - """ - Returns all nodes including nested ones. - """ - for n in self._node_children: - yield n - for y in n.all_sub_nodes(): - yield y - - @underscore_memoization # Should only happen once! - def remove_last_newline(self): - self.parser.remove_last_newline() - - -class FastParser(use_metaclass(CachedFastParser)): - _FLOWS_NEED_SPACE = 'if', 'elif', 'while', 'with', 'except', 'for' - _FLOWS_NEED_COLON = 'else', 'try', 'except', 'finally' - _keyword_re = re.compile('^[ \t]*(def |class |@|(?:%s)|(?:%s)\s*:)' - % ('|'.join(_FLOWS_NEED_SPACE), - '|'.join(_FLOWS_NEED_COLON))) - - def __init__(self, grammar, source, module_path=None): - # set values like `tree.Module`. - self._grammar = grammar - self.module_path = module_path - self._reset_caches() - self.update(source) - - def _reset_caches(self): - self.module = FastModule(self.module_path) - self.root_node = self.current_node = ParserNode(self.module, self, '') - - def get_parsed_node(self): - return self.module - - def update(self, source): - # Variables for testing purposes: It is important that the number of - # parsers used can be minimized. With these variables we can test - # against that. - self.number_parsers_used = 0 - self.number_of_splits = 0 - self.number_of_misses = 0 - self.module.reset_caches() - self.source = source - try: - self._parse(source) - except: - # FastParser is cached, be careful with exceptions. - self._reset_caches() - raise - - def _split_parts(self, source): - """ - Split the source code into different parts. This makes it possible to - parse each part seperately and therefore cache parts of the file and - not everything. - """ - def gen_part(): - text = ''.join(current_lines) - del current_lines[:] - self.number_of_splits += 1 - return text - - def just_newlines(current_lines): - for line in current_lines: - line = line.lstrip('\t \n\r') - if line and line[0] != '#': - return False - return True - - # Split only new lines. Distinction between \r\n is the tokenizer's - # job. - # It seems like there's no problem with form feed characters here, - # because we're not counting lines. - self._lines = source.splitlines(True) - current_lines = [] - is_decorator = False - # Use -1, because that indent is always smaller than any other. - indent_list = [-1, 0] - new_indent = False - parentheses_level = 0 - flow_indent = None - previous_line = None - # All things within flows are simply being ignored. - for i, l in enumerate(self._lines): - # Handle backslash newline escaping. - if l.endswith('\\\n') or l.endswith('\\\r\n'): - if previous_line is not None: - previous_line += l - else: - previous_line = l - continue - if previous_line is not None: - l = previous_line + l - previous_line = None - - # check for dedents - s = l.lstrip('\t \n\r') - indent = len(l) - len(s) - if not s or s[0] == '#': - current_lines.append(l) # Just ignore comments and blank lines - continue - - if new_indent and not parentheses_level: - if indent > indent_list[-2]: - # Set the actual indent, not just the random old indent + 1. - indent_list[-1] = indent - new_indent = False - - while indent < indent_list[-1]: # -> dedent - indent_list.pop() - # This automatically resets the flow_indent if there was a - # dedent or a flow just on one line (with one simple_stmt). - new_indent = False - if flow_indent is None and current_lines and not parentheses_level: - yield gen_part() - flow_indent = None - - # Check lines for functions/classes and split the code there. - if flow_indent is None: - m = self._keyword_re.match(l) - if m: - # Strip whitespace and colon from flows as a check. - if m.group(1).strip(' \t\r\n:') in FLOWS: - if not parentheses_level: - flow_indent = indent - else: - if not is_decorator and not just_newlines(current_lines): - yield gen_part() - is_decorator = '@' == m.group(1) - if not is_decorator: - parentheses_level = 0 - # The new indent needs to be higher - indent_list.append(indent + 1) - new_indent = True - elif is_decorator: - is_decorator = False - - parentheses_level = \ - max(0, (l.count('(') + l.count('[') + l.count('{') - - l.count(')') - l.count(']') - l.count('}'))) - - current_lines.append(l) - - if previous_line is not None: - current_lines.append(previous_line) - if current_lines: - yield gen_part() - - def _parse(self, source): - """ :type source: str """ - added_newline = False - if not source or source[-1] != '\n': - # To be compatible with Pythons grammar, we need a newline at the - # end. The parser would handle it, but since the fast parser abuses - # the normal parser in various ways, we need to care for this - # ourselves. - source += '\n' - added_newline = True - - next_code_part_end_line = code_part_end_line = 1 - start = 0 - nodes = list(self.root_node.all_sub_nodes()) - # Now we can reset the node, because we have all the old nodes. - self.root_node.reset_node() - self.current_node = self.root_node - last_end_line = 1 - - for code_part in self._split_parts(source): - next_code_part_end_line += code_part.count('\n') - # If the last code part parsed isn't equal to the current end_pos, - # we know that the parser went further (`def` start in a - # docstring). So just parse the next part. - if code_part_end_line == last_end_line: - self._parse_part(code_part, source[start:], code_part_end_line, nodes) - else: - self.number_of_misses += 1 - # Means that some lines where not fully parsed. Parse it now. - # This is a very rare case. Should only happens with very - # strange code bits. - while last_end_line < next_code_part_end_line: - code_part_end_line = last_end_line - # We could calculate the src in a more complicated way to - # make caching here possible as well. However, this is - # complicated and error-prone. Since this is not very often - # called - just ignore it. - src = ''.join(self._lines[code_part_end_line - 1:]) - self._parse_part(code_part, src, code_part_end_line, nodes) - last_end_line = self.current_node.end_pos[0] - debug.dbg("While parsing %s, starting with line %s wasn't included in split.", - self.module_path, code_part_end_line) - #assert code_part_end_line > last_end_line - # This means that the parser parsed faster than the last given - # `code_part`. - debug.dbg('While parsing %s, line %s slowed down the fast parser.', - self.module_path, code_part_end_line) - - code_part_end_line = next_code_part_end_line - start += len(code_part) - - last_end_line = self.current_node.end_pos[0] - - if added_newline: - self.current_node.remove_last_newline() - - # Now that the for loop is finished, we still want to close all nodes. - node = self.current_node - while node is not None: - node.close() - node = node.parent - - debug.dbg('Parsed %s, with %s parsers in %s splits.' - % (self.module_path, self.number_parsers_used, - self.number_of_splits)) - - def _parse_part(self, source, parser_code, code_part_end_line, nodes): - """ - Side effect: Alters the list of nodes. - """ - h = hash(source) - for index, node in enumerate(nodes): - if node.hash == h and node.source == source: - node.reset_node() - nodes.remove(node) - parser_code = source - break - else: - tokenizer = FastTokenizer(parser_code) - self.number_parsers_used += 1 - p = ParserWithRecovery(self._grammar, parser_code, self.module_path, tokenizer=tokenizer) - - end = code_part_end_line - 1 + p.module.end_pos[0] - used_lines = self._lines[code_part_end_line - 1:end - 1] - code_part_actually_used = ''.join(used_lines) - - node = ParserNode(self.module, p, code_part_actually_used) - - indent = len(parser_code) - len(parser_code.lstrip('\t ')) - - self.current_node.add_node(node, code_part_end_line, indent) - self.current_node = node - - -class FastTokenizer(object): - """ - Breaks when certain conditions are met, i.e. a new function or class opens. - """ - def __init__(self, source): - self.source = source - self._gen = source_tokens(source, use_exact_op_types=True) - self._closed = False - - # fast parser options - self.current = self.previous = NEWLINE, '', (0, 0) - self._in_flow = False - self._is_decorator = False - self._first_stmt = True - self._parentheses_level = 0 - self._indent_counter = 0 - self._flow_indent_counter = 0 - self._returned_endmarker = False - self._expect_indent = False - - def __iter__(self): - return self - - def next(self): - """ Python 2 Compatibility """ - return self.__next__() - - def __next__(self): - if self._closed: - return self._finish_dedents() - - typ, value, start_pos, prefix = current = next(self._gen) - if typ == ENDMARKER: - self._closed = True - self._returned_endmarker = True - return current - - self.previous = self.current - self.current = current - - if typ == INDENT: - self._indent_counter += 1 - if not self._expect_indent and not self._first_stmt and not self._in_flow: - # This does not mean that there is an actual flow, it means - # that the INDENT is syntactically wrong. - self._flow_indent_counter = self._indent_counter - 1 - self._in_flow = True - self._expect_indent = False - elif typ == DEDENT: - self._indent_counter -= 1 - if self._in_flow: - if self._indent_counter == self._flow_indent_counter: - self._in_flow = False - else: - self._closed = True - return current - - previous_type = self.previous[0] - if value in ('def', 'class') and self._parentheses_level: - # Account for the fact that an open parentheses before a function - # will reset the parentheses counter, but new lines before will - # still be ignored. So check the prefix. - - # TODO what about flow parentheses counter resets in the tokenizer? - self._parentheses_level = 0 - # We need to simulate a newline before the indent, because the - # open parentheses ignored them. - if re.search('\n\s*', prefix): - previous_type = NEWLINE - - # Parentheses ignore the indentation rules. The other three stand for - # new lines. - if previous_type in (NEWLINE, INDENT, DEDENT) \ - and not self._parentheses_level and typ not in (INDENT, DEDENT): - if not self._in_flow: - if value in FLOWS: - self._flow_indent_counter = self._indent_counter - self._first_stmt = False - elif value in ('def', 'class', '@'): - # The values here are exactly the same check as in - # _split_parts, but this time with tokenize and therefore - # precise. - if not self._first_stmt and not self._is_decorator: - return self._close() - - self._is_decorator = '@' == value - if not self._is_decorator: - self._first_stmt = False - self._expect_indent = True - elif self._expect_indent: - return self._close() - else: - self._first_stmt = False - - if value in '([{' and value: - self._parentheses_level += 1 - elif value in ')]}' and value: - # Ignore closing parentheses, because they are all - # irrelevant for the indentation. - self._parentheses_level = max(self._parentheses_level - 1, 0) - return current - - def _close(self): - if self._first_stmt: - # Continue like nothing has happened, because we want to enter - # the first class/function. - if self.current[1] != '@': - self._first_stmt = False - return self.current - else: - self._closed = True - return self._finish_dedents() - - def _finish_dedents(self): - if self._indent_counter: - self._indent_counter -= 1 - return DEDENT, '', self.current[2], '' - elif not self._returned_endmarker: - self._returned_endmarker = True - return ENDMARKER, '', self.current[2], self._get_prefix() - else: - raise StopIteration - - def _get_prefix(self): - """ - We're using the current prefix for the endmarker to not loose any - information. However we care about "lost" lines. The prefix of the - current line (indent) will always be included in the current line. - """ - cur = self.current - while cur[0] == DEDENT: - cur = next(self._gen) - prefix = cur[3] - - # \Z for the end of the string. $ is bugged, because it has the - # same behavior with or without re.MULTILINE. - return re.sub(r'[^\n]+\Z', '', prefix) diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/grammar2.7.txt b/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/grammar2.7.txt deleted file mode 100644 index 515dea6..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/grammar2.7.txt +++ /dev/null @@ -1,152 +0,0 @@ -# Grammar for 2to3. This grammar supports Python 2.x and 3.x. - -# Note: Changing the grammar specified in this file will most likely -# require corresponding changes in the parser module -# (../Modules/parsermodule.c). If you can't make the changes to -# that module yourself, please co-ordinate the required changes -# with someone who can; ask around on python-dev for help. Fred -# Drake will probably be listening there. - -# NOTE WELL: You should also follow all the steps listed in PEP 306, -# "How to Change Python's Grammar" - - -# Start symbols for the grammar: -# file_input is a module or sequence of commands read from an input file; -# single_input is a single interactive statement; -# eval_input is the input for the eval() and input() functions. -# NB: compound_stmt in single_input is followed by extra NEWLINE! -file_input: (NEWLINE | stmt)* ENDMARKER -single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE -eval_input: testlist NEWLINE* ENDMARKER - -decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE -decorators: decorator+ -decorated: decorators (classdef | funcdef) -funcdef: 'def' NAME parameters ['->' test] ':' suite -parameters: '(' [typedargslist] ')' -typedargslist: ((tfpdef ['=' test] ',')* - ('*' [tname] (',' tname ['=' test])* [',' '**' tname] | '**' tname) - | tfpdef ['=' test] (',' tfpdef ['=' test])* [',']) -tname: NAME [':' test] -tfpdef: tname | '(' tfplist ')' -tfplist: tfpdef (',' tfpdef)* [','] -varargslist: ((vfpdef ['=' test] ',')* - ('*' [vname] (',' vname ['=' test])* [',' '**' vname] | '**' vname) - | vfpdef ['=' test] (',' vfpdef ['=' test])* [',']) -vname: NAME -vfpdef: vname | '(' vfplist ')' -vfplist: vfpdef (',' vfpdef)* [','] - -stmt: simple_stmt | compound_stmt -simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE -small_stmt: (expr_stmt | print_stmt | del_stmt | pass_stmt | flow_stmt | - import_stmt | global_stmt | exec_stmt | assert_stmt) -expr_stmt: testlist_star_expr (augassign (yield_expr|testlist) | - ('=' (yield_expr|testlist_star_expr))*) -testlist_star_expr: (test|star_expr) (',' (test|star_expr))* [','] -augassign: ('+=' | '-=' | '*=' | '/=' | '%=' | '&=' | '|=' | '^=' | - '<<=' | '>>=' | '**=' | '//=') -# For normal assignments, additional restrictions enforced by the interpreter -print_stmt: 'print' ( [ test (',' test)* [','] ] | - '>>' test [ (',' test)+ [','] ] ) -del_stmt: 'del' exprlist -pass_stmt: 'pass' -flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt | yield_stmt -break_stmt: 'break' -continue_stmt: 'continue' -return_stmt: 'return' [testlist] -yield_stmt: yield_expr -raise_stmt: 'raise' [test [',' test [',' test]]] -import_stmt: import_name | import_from -import_name: 'import' dotted_as_names -# note below: the ('.' | '...') is necessary because '...' is tokenized as ELLIPSIS -import_from: ('from' (('.' | '...')* dotted_name | ('.' | '...')+) - 'import' ('*' | '(' import_as_names ')' | import_as_names)) -import_as_name: NAME ['as' NAME] -dotted_as_name: dotted_name ['as' NAME] -import_as_names: import_as_name (',' import_as_name)* [','] -dotted_as_names: dotted_as_name (',' dotted_as_name)* -dotted_name: NAME ('.' NAME)* -global_stmt: 'global' NAME (',' NAME)* -exec_stmt: 'exec' expr ['in' test [',' test]] -assert_stmt: 'assert' test [',' test] - -compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | with_stmt | funcdef | classdef | decorated -if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite] -while_stmt: 'while' test ':' suite ['else' ':' suite] -for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite] -try_stmt: ('try' ':' suite - ((except_clause ':' suite)+ - ['else' ':' suite] - ['finally' ':' suite] | - 'finally' ':' suite)) -with_stmt: 'with' with_item (',' with_item)* ':' suite -with_item: test ['as' expr] -with_var: 'as' expr -# NB compile.c makes sure that the default except clause is last -except_clause: 'except' [test [(',' | 'as') test]] -# Edit by David Halter: The stmt is now optional. This reflects how Jedi allows -# classes and functions to be empty, which is beneficial for autocompletion. -suite: simple_stmt | NEWLINE INDENT stmt* DEDENT - -# Backward compatibility cruft to support: -# [ x for x in lambda: True, lambda: False if x() ] -# even while also allowing: -# lambda x: 5 if x else 2 -# (But not a mix of the two) -testlist_safe: old_test [(',' old_test)+ [',']] -old_test: or_test | old_lambdef -old_lambdef: 'lambda' [varargslist] ':' old_test - -test: or_test ['if' or_test 'else' test] | lambdef -or_test: and_test ('or' and_test)* -and_test: not_test ('and' not_test)* -not_test: 'not' not_test | comparison -comparison: expr (comp_op expr)* -comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not' -star_expr: '*' expr -expr: xor_expr ('|' xor_expr)* -xor_expr: and_expr ('^' and_expr)* -and_expr: shift_expr ('&' shift_expr)* -shift_expr: arith_expr (('<<'|'>>') arith_expr)* -arith_expr: term (('+'|'-') term)* -term: factor (('*'|'/'|'%'|'//') factor)* -factor: ('+'|'-'|'~') factor | power -power: atom trailer* ['**' factor] -atom: ('(' [yield_expr|testlist_comp] ')' | - '[' [testlist_comp] ']' | - '{' [dictorsetmaker] '}' | - '`' testlist1 '`' | - NAME | NUMBER | STRING+ | '.' '.' '.') -# Modification by David Halter, remove `testlist_gexp` and `listmaker` -testlist_comp: (test|star_expr) ( comp_for | (',' (test|star_expr))* [','] ) -lambdef: 'lambda' [varargslist] ':' test -trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME -subscriptlist: subscript (',' subscript)* [','] -subscript: test | [test] ':' [test] [sliceop] -sliceop: ':' [test] -exprlist: (expr|star_expr) (',' (expr|star_expr))* [','] -testlist: test (',' test)* [','] -# Modification by David Halter, dictsetmaker -> dictorsetmaker (so that it's -# the same as in the 3.4 grammar). -dictorsetmaker: ( (test ':' test (comp_for | (',' test ':' test)* [','])) | - (test (comp_for | (',' test)* [','])) ) - -classdef: 'class' NAME ['(' [arglist] ')'] ':' suite - -arglist: (argument ',')* (argument [','] - |'*' test (',' argument)* [',' '**' test] - |'**' test) -argument: test [comp_for] | test '=' test # Really [keyword '='] test - -comp_iter: comp_for | comp_if -comp_for: 'for' exprlist 'in' testlist_safe [comp_iter] -comp_if: 'if' old_test [comp_iter] - -testlist1: test (',' test)* - -# not used in grammar, but may appear in "node" passed from Parser to Compiler -encoding_decl: NAME - -yield_expr: 'yield' [testlist] diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/grammar3.4.txt b/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/grammar3.4.txt deleted file mode 100644 index d4a32b8..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/grammar3.4.txt +++ /dev/null @@ -1,135 +0,0 @@ -# Grammar for Python - -# Note: Changing the grammar specified in this file will most likely -# require corresponding changes in the parser module -# (../Modules/parsermodule.c). If you can't make the changes to -# that module yourself, please co-ordinate the required changes -# with someone who can; ask around on python-dev for help. Fred -# Drake will probably be listening there. - -# NOTE WELL: You should also follow all the steps listed in PEP 306, -# "How to Change Python's Grammar" - -# Start symbols for the grammar: -# single_input is a single interactive statement; -# file_input is a module or sequence of commands read from an input file; -# eval_input is the input for the eval() functions. -# NB: compound_stmt in single_input is followed by extra NEWLINE! -file_input: (NEWLINE | stmt)* ENDMARKER -single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE -eval_input: testlist NEWLINE* ENDMARKER - -decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE -decorators: decorator+ -decorated: decorators (classdef | funcdef) -funcdef: 'def' NAME parameters ['->' test] ':' suite -parameters: '(' [typedargslist] ')' -typedargslist: (tfpdef ['=' test] (',' tfpdef ['=' test])* [',' - ['*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' tfpdef]] - | '*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' tfpdef) -tfpdef: NAME [':' test] -varargslist: (vfpdef ['=' test] (',' vfpdef ['=' test])* [',' - ['*' [vfpdef] (',' vfpdef ['=' test])* [',' '**' vfpdef] | '**' vfpdef]] - | '*' [vfpdef] (',' vfpdef ['=' test])* [',' '**' vfpdef] | '**' vfpdef) -vfpdef: NAME - -stmt: simple_stmt | compound_stmt -simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE -small_stmt: (expr_stmt | del_stmt | pass_stmt | flow_stmt | - import_stmt | global_stmt | nonlocal_stmt | assert_stmt) -expr_stmt: testlist_star_expr (augassign (yield_expr|testlist) | - ('=' (yield_expr|testlist_star_expr))*) -testlist_star_expr: (test|star_expr) (',' (test|star_expr))* [','] -augassign: ('+=' | '-=' | '*=' | '/=' | '%=' | '&=' | '|=' | '^=' | - '<<=' | '>>=' | '**=' | '//=') -# For normal assignments, additional restrictions enforced by the interpreter -del_stmt: 'del' exprlist -pass_stmt: 'pass' -flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt | yield_stmt -break_stmt: 'break' -continue_stmt: 'continue' -return_stmt: 'return' [testlist] -yield_stmt: yield_expr -raise_stmt: 'raise' [test ['from' test]] -import_stmt: import_name | import_from -import_name: 'import' dotted_as_names -# note below: the ('.' | '...') is necessary because '...' is tokenized as ELLIPSIS -import_from: ('from' (('.' | '...')* dotted_name | ('.' | '...')+) - 'import' ('*' | '(' import_as_names ')' | import_as_names)) -import_as_name: NAME ['as' NAME] -dotted_as_name: dotted_name ['as' NAME] -import_as_names: import_as_name (',' import_as_name)* [','] -dotted_as_names: dotted_as_name (',' dotted_as_name)* -dotted_name: NAME ('.' NAME)* -global_stmt: 'global' NAME (',' NAME)* -nonlocal_stmt: 'nonlocal' NAME (',' NAME)* -assert_stmt: 'assert' test [',' test] - -compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | with_stmt | funcdef | classdef | decorated -if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite] -while_stmt: 'while' test ':' suite ['else' ':' suite] -for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite] -try_stmt: ('try' ':' suite - ((except_clause ':' suite)+ - ['else' ':' suite] - ['finally' ':' suite] | - 'finally' ':' suite)) -with_stmt: 'with' with_item (',' with_item)* ':' suite -with_item: test ['as' expr] -# NB compile.c makes sure that the default except clause is last -except_clause: 'except' [test ['as' NAME]] -# Edit by David Halter: The stmt is now optional. This reflects how Jedi allows -# classes and functions to be empty, which is beneficial for autocompletion. -suite: simple_stmt | NEWLINE INDENT stmt* DEDENT - -test: or_test ['if' or_test 'else' test] | lambdef -test_nocond: or_test | lambdef_nocond -lambdef: 'lambda' [varargslist] ':' test -lambdef_nocond: 'lambda' [varargslist] ':' test_nocond -or_test: and_test ('or' and_test)* -and_test: not_test ('and' not_test)* -not_test: 'not' not_test | comparison -comparison: expr (comp_op expr)* -# <> isn't actually a valid comparison operator in Python. It's here for the -# sake of a __future__ import described in PEP 401 -comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not' -star_expr: '*' expr -expr: xor_expr ('|' xor_expr)* -xor_expr: and_expr ('^' and_expr)* -and_expr: shift_expr ('&' shift_expr)* -shift_expr: arith_expr (('<<'|'>>') arith_expr)* -arith_expr: term (('+'|'-') term)* -term: factor (('*'|'/'|'%'|'//') factor)* -factor: ('+'|'-'|'~') factor | power -power: atom trailer* ['**' factor] -atom: ('(' [yield_expr|testlist_comp] ')' | - '[' [testlist_comp] ']' | - '{' [dictorsetmaker] '}' | - NAME | NUMBER | STRING+ | '...' | 'None' | 'True' | 'False') -testlist_comp: (test|star_expr) ( comp_for | (',' (test|star_expr))* [','] ) -trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME -subscriptlist: subscript (',' subscript)* [','] -subscript: test | [test] ':' [test] [sliceop] -sliceop: ':' [test] -exprlist: (expr|star_expr) (',' (expr|star_expr))* [','] -testlist: test (',' test)* [','] -dictorsetmaker: ( (test ':' test (comp_for | (',' test ':' test)* [','])) | - (test (comp_for | (',' test)* [','])) ) - -classdef: 'class' NAME ['(' [arglist] ')'] ':' suite - -arglist: (argument ',')* (argument [','] - |'*' test (',' argument)* [',' '**' test] - |'**' test) -# The reason that keywords are test nodes instead of NAME is that using NAME -# results in an ambiguity. ast.c makes sure it's a NAME. -argument: test [comp_for] | test '=' test # Really [keyword '='] test -comp_iter: comp_for | comp_if -comp_for: 'for' exprlist 'in' or_test [comp_iter] -comp_if: 'if' test_nocond [comp_iter] - -# not used in grammar, but may appear in "node" passed from Parser to Compiler -encoding_decl: NAME - -yield_expr: 'yield' [yield_arg] -yield_arg: 'from' test | testlist diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/grammar3.5.txt b/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/grammar3.5.txt deleted file mode 100644 index 96a7271..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/grammar3.5.txt +++ /dev/null @@ -1,154 +0,0 @@ -# Grammar for Python - -# Note: Changing the grammar specified in this file will most likely -# require corresponding changes in the parser module -# (../Modules/parsermodule.c). If you can't make the changes to -# that module yourself, please co-ordinate the required changes -# with someone who can; ask around on python-dev for help. Fred -# Drake will probably be listening there. - -# NOTE WELL: You should also follow all the steps listed at -# https://docs.python.org/devguide/grammar.html - -# Start symbols for the grammar: -# single_input is a single interactive statement; -# file_input is a module or sequence of commands read from an input file; -# eval_input is the input for the eval() functions. -# NB: compound_stmt in single_input is followed by extra NEWLINE! -file_input: (NEWLINE | stmt)* ENDMARKER -single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE -eval_input: testlist NEWLINE* ENDMARKER - -decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE -decorators: decorator+ -decorated: decorators (classdef | funcdef | async_funcdef) - -# NOTE: Reinoud Elhorst, using ASYNC/AWAIT keywords instead of tokens -# skipping python3.5 compatibility, in favour of 3.7 solution -async_funcdef: 'async' funcdef -funcdef: 'def' NAME parameters ['->' test] ':' suite - -parameters: '(' [typedargslist] ')' -typedargslist: (tfpdef ['=' test] (',' tfpdef ['=' test])* [',' - ['*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' tfpdef]] - | '*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' tfpdef) -tfpdef: NAME [':' test] -varargslist: (vfpdef ['=' test] (',' vfpdef ['=' test])* [',' - ['*' [vfpdef] (',' vfpdef ['=' test])* [',' '**' vfpdef] | '**' vfpdef]] - | '*' [vfpdef] (',' vfpdef ['=' test])* [',' '**' vfpdef] | '**' vfpdef) -vfpdef: NAME - -stmt: simple_stmt | compound_stmt -simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE -small_stmt: (expr_stmt | del_stmt | pass_stmt | flow_stmt | - import_stmt | global_stmt | nonlocal_stmt | assert_stmt) -expr_stmt: testlist_star_expr (augassign (yield_expr|testlist) | - ('=' (yield_expr|testlist_star_expr))*) -testlist_star_expr: (test|star_expr) (',' (test|star_expr))* [','] -augassign: ('+=' | '-=' | '*=' | '@=' | '/=' | '%=' | '&=' | '|=' | '^=' | - '<<=' | '>>=' | '**=' | '//=') -# For normal assignments, additional restrictions enforced by the interpreter -del_stmt: 'del' exprlist -pass_stmt: 'pass' -flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt | yield_stmt -break_stmt: 'break' -continue_stmt: 'continue' -return_stmt: 'return' [testlist] -yield_stmt: yield_expr -raise_stmt: 'raise' [test ['from' test]] -import_stmt: import_name | import_from -import_name: 'import' dotted_as_names -# note below: the ('.' | '...') is necessary because '...' is tokenized as ELLIPSIS -import_from: ('from' (('.' | '...')* dotted_name | ('.' | '...')+) - 'import' ('*' | '(' import_as_names ')' | import_as_names)) -import_as_name: NAME ['as' NAME] -dotted_as_name: dotted_name ['as' NAME] -import_as_names: import_as_name (',' import_as_name)* [','] -dotted_as_names: dotted_as_name (',' dotted_as_name)* -dotted_name: NAME ('.' NAME)* -global_stmt: 'global' NAME (',' NAME)* -nonlocal_stmt: 'nonlocal' NAME (',' NAME)* -assert_stmt: 'assert' test [',' test] - -compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | with_stmt | funcdef | classdef | decorated | async_stmt -async_stmt: 'async' (funcdef | with_stmt | for_stmt) -if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite] -while_stmt: 'while' test ':' suite ['else' ':' suite] -for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite] -try_stmt: ('try' ':' suite - ((except_clause ':' suite)+ - ['else' ':' suite] - ['finally' ':' suite] | - 'finally' ':' suite)) -with_stmt: 'with' with_item (',' with_item)* ':' suite -with_item: test ['as' expr] -# NB compile.c makes sure that the default except clause is last -except_clause: 'except' [test ['as' NAME]] -# Edit by David Halter: The stmt is now optional. This reflects how Jedi allows -# classes and functions to be empty, which is beneficial for autocompletion. -suite: simple_stmt | NEWLINE INDENT stmt* DEDENT - -test: or_test ['if' or_test 'else' test] | lambdef -test_nocond: or_test | lambdef_nocond -lambdef: 'lambda' [varargslist] ':' test -lambdef_nocond: 'lambda' [varargslist] ':' test_nocond -or_test: and_test ('or' and_test)* -and_test: not_test ('and' not_test)* -not_test: 'not' not_test | comparison -comparison: expr (comp_op expr)* -# <> isn't actually a valid comparison operator in Python. It's here for the -# sake of a __future__ import described in PEP 401 (which really works :-) -comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not' -star_expr: '*' expr -expr: xor_expr ('|' xor_expr)* -xor_expr: and_expr ('^' and_expr)* -and_expr: shift_expr ('&' shift_expr)* -shift_expr: arith_expr (('<<'|'>>') arith_expr)* -arith_expr: term (('+'|'-') term)* -term: factor (('*'|'@'|'/'|'%'|'//') factor)* -factor: ('+'|'-'|'~') factor | power -power: atom_expr ['**' factor] -atom_expr: ['await'] atom trailer* -atom: ('(' [yield_expr|testlist_comp] ')' | - '[' [testlist_comp] ']' | - '{' [dictorsetmaker] '}' | - NAME | NUMBER | STRING+ | '...' | 'None' | 'True' | 'False') -testlist_comp: (test|star_expr) ( comp_for | (',' (test|star_expr))* [','] ) -trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME -subscriptlist: subscript (',' subscript)* [','] -subscript: test | [test] ':' [test] [sliceop] -sliceop: ':' [test] -exprlist: (expr|star_expr) (',' (expr|star_expr))* [','] -testlist: test (',' test)* [','] -dictorsetmaker: ( ((test ':' test | '**' expr) - (comp_for | (',' (test ':' test | '**' expr))* [','])) | - ((test | star_expr) - (comp_for | (',' (test | star_expr))* [','])) ) - -classdef: 'class' NAME ['(' [arglist] ')'] ':' suite - -arglist: argument (',' argument)* [','] - -# The reason that keywords are test nodes instead of NAME is that using NAME -# results in an ambiguity. ast.c makes sure it's a NAME. -# "test '=' test" is really "keyword '=' test", but we have no such token. -# These need to be in a single rule to avoid grammar that is ambiguous -# to our LL(1) parser. Even though 'test' includes '*expr' in star_expr, -# we explicitly match '*' here, too, to give it proper precedence. -# Illegal combinations and orderings are blocked in ast.c: -# multiple (test comp_for) arguements are blocked; keyword unpackings -# that precede iterable unpackings are blocked; etc. -argument: ( test [comp_for] | - test '=' test | - '**' test | - '*' test ) - -comp_iter: comp_for | comp_if -comp_for: 'for' exprlist 'in' or_test [comp_iter] -comp_if: 'if' test_nocond [comp_iter] - -# not used in grammar, but may appear in "node" passed from Parser to Compiler -encoding_decl: NAME - -yield_expr: 'yield' [yield_arg] -yield_arg: 'from' test | testlist diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/pgen2/__init__.py b/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/pgen2/__init__.py deleted file mode 100644 index 1ddae5f..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/pgen2/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved. -# Licensed to PSF under a Contributor Agreement. - -# Modifications: -# Copyright 2006 Google, Inc. All Rights Reserved. -# Licensed to PSF under a Contributor Agreement. -# Copyright 2014 David Halter. Integration into Jedi. -# Modifications are dual-licensed: MIT and PSF. diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/pgen2/__pycache__/__init__.cpython-35.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/pgen2/__pycache__/__init__.cpython-35.pyc deleted file mode 100644 index c6fa84f..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/pgen2/__pycache__/__init__.cpython-35.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/pgen2/__pycache__/__init__.cpython-36.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/pgen2/__pycache__/__init__.cpython-36.pyc deleted file mode 100644 index 8f1b482..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/pgen2/__pycache__/__init__.cpython-36.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/pgen2/__pycache__/grammar.cpython-35.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/pgen2/__pycache__/grammar.cpython-35.pyc deleted file mode 100644 index 99ca4f6..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/pgen2/__pycache__/grammar.cpython-35.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/pgen2/__pycache__/grammar.cpython-36.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/pgen2/__pycache__/grammar.cpython-36.pyc deleted file mode 100644 index 2c911f1..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/pgen2/__pycache__/grammar.cpython-36.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/pgen2/__pycache__/parse.cpython-35.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/pgen2/__pycache__/parse.cpython-35.pyc deleted file mode 100644 index 7dadbf6..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/pgen2/__pycache__/parse.cpython-35.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/pgen2/__pycache__/parse.cpython-36.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/pgen2/__pycache__/parse.cpython-36.pyc deleted file mode 100644 index f676b20..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/pgen2/__pycache__/parse.cpython-36.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/pgen2/__pycache__/pgen.cpython-35.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/pgen2/__pycache__/pgen.cpython-35.pyc deleted file mode 100644 index b6d18a3..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/pgen2/__pycache__/pgen.cpython-35.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/pgen2/__pycache__/pgen.cpython-36.pyc b/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/pgen2/__pycache__/pgen.cpython-36.pyc deleted file mode 100644 index d0aa20f..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/pgen2/__pycache__/pgen.cpython-36.pyc and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/pgen2/grammar.py b/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/pgen2/grammar.py deleted file mode 100644 index 414c0db..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/pgen2/grammar.py +++ /dev/null @@ -1,125 +0,0 @@ -# Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved. -# Licensed to PSF under a Contributor Agreement. - -# Modifications: -# Copyright 2014 David Halter. Integration into Jedi. -# Modifications are dual-licensed: MIT and PSF. - -"""This module defines the data structures used to represent a grammar. - -These are a bit arcane because they are derived from the data -structures used by Python's 'pgen' parser generator. - -There's also a table here mapping operators to their names in the -token module; the Python tokenize module reports all operators as the -fallback token code OP, but the parser needs the actual token code. - -""" - -# Python imports -import pickle - - -class Grammar(object): - """Pgen parsing tables conversion class. - - Once initialized, this class supplies the grammar tables for the - parsing engine implemented by parse.py. The parsing engine - accesses the instance variables directly. The class here does not - provide initialization of the tables; several subclasses exist to - do this (see the conv and pgen modules). - - The load() method reads the tables from a pickle file, which is - much faster than the other ways offered by subclasses. The pickle - file is written by calling dump() (after loading the grammar - tables using a subclass). The report() method prints a readable - representation of the tables to stdout, for debugging. - - The instance variables are as follows: - - symbol2number -- a dict mapping symbol names to numbers. Symbol - numbers are always 256 or higher, to distinguish - them from token numbers, which are between 0 and - 255 (inclusive). - - number2symbol -- a dict mapping numbers to symbol names; - these two are each other's inverse. - - states -- a list of DFAs, where each DFA is a list of - states, each state is a list of arcs, and each - arc is a (i, j) pair where i is a label and j is - a state number. The DFA number is the index into - this list. (This name is slightly confusing.) - Final states are represented by a special arc of - the form (0, j) where j is its own state number. - - dfas -- a dict mapping symbol numbers to (DFA, first) - pairs, where DFA is an item from the states list - above, and first is a set of tokens that can - begin this grammar rule (represented by a dict - whose values are always 1). - - labels -- a list of (x, y) pairs where x is either a token - number or a symbol number, and y is either None - or a string; the strings are keywords. The label - number is the index in this list; label numbers - are used to mark state transitions (arcs) in the - DFAs. - - start -- the number of the grammar's start symbol. - - keywords -- a dict mapping keyword strings to arc labels. - - tokens -- a dict mapping token numbers to arc labels. - - """ - - def __init__(self): - self.symbol2number = {} - self.number2symbol = {} - self.states = [] - self.dfas = {} - self.labels = [(0, "EMPTY")] - self.keywords = {} - self.tokens = {} - self.symbol2label = {} - self.start = 256 - - def dump(self, filename): - """Dump the grammar tables to a pickle file.""" - with open(filename, "wb") as f: - pickle.dump(self.__dict__, f, 2) - - def load(self, filename): - """Load the grammar tables from a pickle file.""" - with open(filename, "rb") as f: - d = pickle.load(f) - self.__dict__.update(d) - - def copy(self): - """ - Copy the grammar. - """ - new = self.__class__() - for dict_attr in ("symbol2number", "number2symbol", "dfas", "keywords", - "tokens", "symbol2label"): - setattr(new, dict_attr, getattr(self, dict_attr).copy()) - new.labels = self.labels[:] - new.states = self.states[:] - new.start = self.start - return new - - def report(self): - """Dump the grammar tables to standard output, for debugging.""" - from pprint import pprint - print("s2n") - pprint(self.symbol2number) - print("n2s") - pprint(self.number2symbol) - print("states") - pprint(self.states) - print("dfas") - pprint(self.dfas) - print("labels") - pprint(self.labels) - print("start", self.start) diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/pgen2/parse.py b/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/pgen2/parse.py deleted file mode 100644 index 9e74838..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/pgen2/parse.py +++ /dev/null @@ -1,213 +0,0 @@ -# Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved. -# Licensed to PSF under a Contributor Agreement. - -# Modifications: -# Copyright 2014 David Halter. Integration into Jedi. -# Modifications are dual-licensed: MIT and PSF. - -""" -Parser engine for the grammar tables generated by pgen. - -The grammar table must be loaded first. - -See Parser/parser.c in the Python distribution for additional info on -how this parsing engine works. -""" - -# Local imports -from jedi.parser import tokenize - - -class InternalParseError(Exception): - """ - Exception to signal the parser is stuck and error recovery didn't help. - Basically this shouldn't happen. It's a sign that something is really - wrong. - """ - - def __init__(self, msg, type, value, start_pos): - Exception.__init__(self, "%s: type=%r, value=%r, start_pos=%r" % - (msg, tokenize.tok_name[type], value, start_pos)) - self.msg = msg - self.type = type - self.value = value - self.start_pos = start_pos - - -def token_to_ilabel(grammar, type_, value): - # Map from token to label - if type_ == tokenize.NAME: - # Check for reserved words (keywords) - try: - return grammar.keywords[value] - except KeyError: - pass - - try: - return grammar.tokens[type_] - except KeyError: - return None - - -class PgenParser(object): - """Parser engine. - - The proper usage sequence is: - - p = Parser(grammar, [converter]) # create instance - p.setup([start]) # prepare for parsing - : - if p.addtoken(...): # parse a token - break - root = p.rootnode # root of abstract syntax tree - - A Parser instance may be reused by calling setup() repeatedly. - - A Parser instance contains state pertaining to the current token - sequence, and should not be used concurrently by different threads - to parse separate token sequences. - - See driver.py for how to get input tokens by tokenizing a file or - string. - - Parsing is complete when addtoken() returns True; the root of the - abstract syntax tree can then be retrieved from the rootnode - instance variable. When a syntax error occurs, error_recovery() - is called. There is no error recovery; the parser cannot be used - after a syntax error was reported (but it can be reinitialized by - calling setup()). - - """ - - def __init__(self, grammar, convert_node, convert_leaf, error_recovery, start): - """Constructor. - - The grammar argument is a grammar.Grammar instance; see the - grammar module for more information. - - The parser is not ready yet for parsing; you must call the - setup() method to get it started. - - The optional convert argument is a function mapping concrete - syntax tree nodes to abstract syntax tree nodes. If not - given, no conversion is done and the syntax tree produced is - the concrete syntax tree. If given, it must be a function of - two arguments, the first being the grammar (a grammar.Grammar - instance), and the second being the concrete syntax tree node - to be converted. The syntax tree is converted from the bottom - up. - - A concrete syntax tree node is a (type, nodes) tuple, where - type is the node type (a token or symbol number) and nodes - is a list of children for symbols, and None for tokens. - - An abstract syntax tree node may be anything; this is entirely - up to the converter function. - - """ - self.grammar = grammar - self.convert_node = convert_node - self.convert_leaf = convert_leaf - - # Each stack entry is a tuple: (dfa, state, node). - # A node is a tuple: (type, children), - # where children is a list of nodes or None - newnode = (start, []) - stackentry = (self.grammar.dfas[start], 0, newnode) - self.stack = [stackentry] - self.rootnode = None - self.error_recovery = error_recovery - - def parse(self, tokenizer): - for type_, value, start_pos, prefix in tokenizer: - if self.addtoken(type_, value, start_pos, prefix): - break - else: - # We never broke out -- EOF is too soon -- Unfinished statement. - # However, the error recovery might have added the token again, if - # the stack is empty, we're fine. - if self.stack: - raise InternalParseError("incomplete input", type_, value, start_pos) - return self.rootnode - - def addtoken(self, type_, value, start_pos, prefix): - """Add a token; return True if this is the end of the program.""" - ilabel = token_to_ilabel(self.grammar, type_, value) - - # Loop until the token is shifted; may raise exceptions - while True: - dfa, state, node = self.stack[-1] - states, first = dfa - arcs = states[state] - # Look for a state with this label - for i, newstate in arcs: - t, v = self.grammar.labels[i] - if ilabel == i: - # Look it up in the list of labels - assert t < 256 - # Shift a token; we're done with it - self.shift(type_, value, newstate, prefix, start_pos) - # Pop while we are in an accept-only state - state = newstate - while states[state] == [(0, state)]: - self.pop() - if not self.stack: - # Done parsing! - return True - dfa, state, node = self.stack[-1] - states, first = dfa - # Done with this token - return False - elif t >= 256: - # See if it's a symbol and if we're in its first set - itsdfa = self.grammar.dfas[t] - itsstates, itsfirst = itsdfa - if ilabel in itsfirst: - # Push a symbol - self.push(t, itsdfa, newstate) - break # To continue the outer while loop - else: - if (0, state) in arcs: - # An accepting state, pop it and try something else - self.pop() - if not self.stack: - # Done parsing, but another token is input - raise InternalParseError("too much input", type_, value, start_pos) - else: - self.error_recovery(self.grammar, self.stack, arcs, type_, - value, start_pos, prefix, self.addtoken) - break - - def shift(self, type_, value, newstate, prefix, start_pos): - """Shift a token. (Internal)""" - dfa, state, node = self.stack[-1] - newnode = self.convert_leaf(self.grammar, type_, value, prefix, start_pos) - node[-1].append(newnode) - self.stack[-1] = (dfa, newstate, node) - - def push(self, type_, newdfa, newstate): - """Push a nonterminal. (Internal)""" - dfa, state, node = self.stack[-1] - newnode = (type_, []) - self.stack[-1] = (dfa, newstate, node) - self.stack.append((newdfa, 0, newnode)) - - def pop(self): - """Pop a nonterminal. (Internal)""" - popdfa, popstate, (type_, children) = self.stack.pop() - # If there's exactly one child, return that child instead of creating a - # new node. We still create expr_stmt and file_input though, because a - # lot of Jedi depends on its logic. - if len(children) == 1: - newnode = children[0] - else: - newnode = self.convert_node(self.grammar, type_, children) - - try: - # Equal to: - # dfa, state, node = self.stack[-1] - # symbol, children = node - self.stack[-1][2][1].append(newnode) - except IndexError: - # Stack is empty, set the rootnode. - self.rootnode = newnode diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/pgen2/pgen.py b/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/pgen2/pgen.py deleted file mode 100644 index fa2742d..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/pgen2/pgen.py +++ /dev/null @@ -1,394 +0,0 @@ -# Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved. -# Licensed to PSF under a Contributor Agreement. - -# Modifications: -# Copyright 2014 David Halter. Integration into Jedi. -# Modifications are dual-licensed: MIT and PSF. - -# Pgen imports -from . import grammar -from jedi.parser import token -from jedi.parser import tokenize - - -class ParserGenerator(object): - def __init__(self, filename, stream=None): - close_stream = None - if stream is None: - stream = open(filename) - close_stream = stream.close - self.filename = filename - self.stream = stream - self.generator = tokenize.generate_tokens(stream.readline) - self.gettoken() # Initialize lookahead - self.dfas, self.startsymbol = self.parse() - if close_stream is not None: - close_stream() - self.first = {} # map from symbol name to set of tokens - self.addfirstsets() - - def make_grammar(self): - c = grammar.Grammar() - names = list(self.dfas.keys()) - names.sort() - names.remove(self.startsymbol) - names.insert(0, self.startsymbol) - for name in names: - i = 256 + len(c.symbol2number) - c.symbol2number[name] = i - c.number2symbol[i] = name - for name in names: - dfa = self.dfas[name] - states = [] - for state in dfa: - arcs = [] - for label, next in state.arcs.items(): - arcs.append((self.make_label(c, label), dfa.index(next))) - if state.isfinal: - arcs.append((0, dfa.index(state))) - states.append(arcs) - c.states.append(states) - c.dfas[c.symbol2number[name]] = (states, self.make_first(c, name)) - c.start = c.symbol2number[self.startsymbol] - return c - - def make_first(self, c, name): - rawfirst = self.first[name] - first = {} - for label in rawfirst: - ilabel = self.make_label(c, label) - ##assert ilabel not in first # XXX failed on <> ... != - first[ilabel] = 1 - return first - - def make_label(self, c, label): - # XXX Maybe this should be a method on a subclass of converter? - ilabel = len(c.labels) - if label[0].isalpha(): - # Either a symbol name or a named token - if label in c.symbol2number: - # A symbol name (a non-terminal) - if label in c.symbol2label: - return c.symbol2label[label] - else: - c.labels.append((c.symbol2number[label], None)) - c.symbol2label[label] = ilabel - return ilabel - else: - # A named token (NAME, NUMBER, STRING) - itoken = getattr(token, label, None) - assert isinstance(itoken, int), label - assert itoken in token.tok_name, label - if itoken in c.tokens: - return c.tokens[itoken] - else: - c.labels.append((itoken, None)) - c.tokens[itoken] = ilabel - return ilabel - else: - # Either a keyword or an operator - assert label[0] in ('"', "'"), label - value = eval(label) - if value[0].isalpha(): - # A keyword - if value in c.keywords: - return c.keywords[value] - else: - c.labels.append((token.NAME, value)) - c.keywords[value] = ilabel - return ilabel - else: - # An operator (any non-numeric token) - itoken = token.opmap[value] # Fails if unknown token - if itoken in c.tokens: - return c.tokens[itoken] - else: - c.labels.append((itoken, None)) - c.tokens[itoken] = ilabel - return ilabel - - def addfirstsets(self): - names = list(self.dfas.keys()) - names.sort() - for name in names: - if name not in self.first: - self.calcfirst(name) - #print name, self.first[name].keys() - - def calcfirst(self, name): - dfa = self.dfas[name] - self.first[name] = None # dummy to detect left recursion - state = dfa[0] - totalset = {} - overlapcheck = {} - for label, next in state.arcs.items(): - if label in self.dfas: - if label in self.first: - fset = self.first[label] - if fset is None: - raise ValueError("recursion for rule %r" % name) - else: - self.calcfirst(label) - fset = self.first[label] - totalset.update(fset) - overlapcheck[label] = fset - else: - totalset[label] = 1 - overlapcheck[label] = {label: 1} - inverse = {} - for label, itsfirst in overlapcheck.items(): - for symbol in itsfirst: - if symbol in inverse: - raise ValueError("rule %s is ambiguous; %s is in the" - " first sets of %s as well as %s" % - (name, symbol, label, inverse[symbol])) - inverse[symbol] = label - self.first[name] = totalset - - def parse(self): - dfas = {} - startsymbol = None - # MSTART: (NEWLINE | RULE)* ENDMARKER - while self.type != token.ENDMARKER: - while self.type == token.NEWLINE: - self.gettoken() - # RULE: NAME ':' RHS NEWLINE - name = self.expect(token.NAME) - self.expect(token.OP, ":") - a, z = self.parse_rhs() - self.expect(token.NEWLINE) - #self.dump_nfa(name, a, z) - dfa = self.make_dfa(a, z) - #self.dump_dfa(name, dfa) - # oldlen = len(dfa) - self.simplify_dfa(dfa) - # newlen = len(dfa) - dfas[name] = dfa - #print name, oldlen, newlen - if startsymbol is None: - startsymbol = name - return dfas, startsymbol - - def make_dfa(self, start, finish): - # To turn an NFA into a DFA, we define the states of the DFA - # to correspond to *sets* of states of the NFA. Then do some - # state reduction. Let's represent sets as dicts with 1 for - # values. - assert isinstance(start, NFAState) - assert isinstance(finish, NFAState) - - def closure(state): - base = {} - addclosure(state, base) - return base - - def addclosure(state, base): - assert isinstance(state, NFAState) - if state in base: - return - base[state] = 1 - for label, next in state.arcs: - if label is None: - addclosure(next, base) - - states = [DFAState(closure(start), finish)] - for state in states: # NB states grows while we're iterating - arcs = {} - for nfastate in state.nfaset: - for label, next in nfastate.arcs: - if label is not None: - addclosure(next, arcs.setdefault(label, {})) - for label, nfaset in arcs.items(): - for st in states: - if st.nfaset == nfaset: - break - else: - st = DFAState(nfaset, finish) - states.append(st) - state.addarc(st, label) - return states # List of DFAState instances; first one is start - - def dump_nfa(self, name, start, finish): - print("Dump of NFA for", name) - todo = [start] - for i, state in enumerate(todo): - print(" State", i, state is finish and "(final)" or "") - for label, next in state.arcs: - if next in todo: - j = todo.index(next) - else: - j = len(todo) - todo.append(next) - if label is None: - print(" -> %d" % j) - else: - print(" %s -> %d" % (label, j)) - - def dump_dfa(self, name, dfa): - print("Dump of DFA for", name) - for i, state in enumerate(dfa): - print(" State", i, state.isfinal and "(final)" or "") - for label, next in state.arcs.items(): - print(" %s -> %d" % (label, dfa.index(next))) - - def simplify_dfa(self, dfa): - # This is not theoretically optimal, but works well enough. - # Algorithm: repeatedly look for two states that have the same - # set of arcs (same labels pointing to the same nodes) and - # unify them, until things stop changing. - - # dfa is a list of DFAState instances - changes = True - while changes: - changes = False - for i, state_i in enumerate(dfa): - for j in range(i + 1, len(dfa)): - state_j = dfa[j] - if state_i == state_j: - #print " unify", i, j - del dfa[j] - for state in dfa: - state.unifystate(state_j, state_i) - changes = True - break - - def parse_rhs(self): - # RHS: ALT ('|' ALT)* - a, z = self.parse_alt() - if self.value != "|": - return a, z - else: - aa = NFAState() - zz = NFAState() - aa.addarc(a) - z.addarc(zz) - while self.value == "|": - self.gettoken() - a, z = self.parse_alt() - aa.addarc(a) - z.addarc(zz) - return aa, zz - - def parse_alt(self): - # ALT: ITEM+ - a, b = self.parse_item() - while (self.value in ("(", "[") or - self.type in (token.NAME, token.STRING)): - c, d = self.parse_item() - b.addarc(c) - b = d - return a, b - - def parse_item(self): - # ITEM: '[' RHS ']' | ATOM ['+' | '*'] - if self.value == "[": - self.gettoken() - a, z = self.parse_rhs() - self.expect(token.OP, "]") - a.addarc(z) - return a, z - else: - a, z = self.parse_atom() - value = self.value - if value not in ("+", "*"): - return a, z - self.gettoken() - z.addarc(a) - if value == "+": - return a, z - else: - return a, a - - def parse_atom(self): - # ATOM: '(' RHS ')' | NAME | STRING - if self.value == "(": - self.gettoken() - a, z = self.parse_rhs() - self.expect(token.OP, ")") - return a, z - elif self.type in (token.NAME, token.STRING): - a = NFAState() - z = NFAState() - a.addarc(z, self.value) - self.gettoken() - return a, z - else: - self.raise_error("expected (...) or NAME or STRING, got %s/%s", - self.type, self.value) - - def expect(self, type, value=None): - if self.type != type or (value is not None and self.value != value): - self.raise_error("expected %s/%s, got %s/%s", - type, value, self.type, self.value) - value = self.value - self.gettoken() - return value - - def gettoken(self): - tup = next(self.generator) - while tup[0] in (token.COMMENT, token.NL): - tup = next(self.generator) - self.type, self.value, self.begin, prefix = tup - #print tokenize.tok_name[self.type], repr(self.value) - - def raise_error(self, msg, *args): - if args: - try: - msg = msg % args - except: - msg = " ".join([msg] + list(map(str, args))) - line = open(self.filename).readlines()[self.begin[0]] - raise SyntaxError(msg, (self.filename, self.begin[0], - self.begin[1], line)) - - -class NFAState(object): - def __init__(self): - self.arcs = [] # list of (label, NFAState) pairs - - def addarc(self, next, label=None): - assert label is None or isinstance(label, str) - assert isinstance(next, NFAState) - self.arcs.append((label, next)) - - -class DFAState(object): - def __init__(self, nfaset, final): - assert isinstance(nfaset, dict) - assert isinstance(next(iter(nfaset)), NFAState) - assert isinstance(final, NFAState) - self.nfaset = nfaset - self.isfinal = final in nfaset - self.arcs = {} # map from label to DFAState - - def addarc(self, next, label): - assert isinstance(label, str) - assert label not in self.arcs - assert isinstance(next, DFAState) - self.arcs[label] = next - - def unifystate(self, old, new): - for label, next in self.arcs.items(): - if next is old: - self.arcs[label] = new - - def __eq__(self, other): - # Equality test -- ignore the nfaset instance variable - assert isinstance(other, DFAState) - if self.isfinal != other.isfinal: - return False - # Can't just return self.arcs == other.arcs, because that - # would invoke this method recursively, with cycles... - if len(self.arcs) != len(other.arcs): - return False - for label, next in self.arcs.items(): - if next is not other.arcs.get(label): - return False - return True - - __hash__ = None # For Py3 compatibility. - - -def generate_grammar(filename="Grammar.txt"): - p = ParserGenerator(filename) - return p.make_grammar() diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/token.py b/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/token.py deleted file mode 100644 index 0cb846d..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/token.py +++ /dev/null @@ -1,90 +0,0 @@ -from __future__ import absolute_import - -from jedi._compatibility import is_py3, is_py35 -from token import * - - -COMMENT = N_TOKENS -tok_name[COMMENT] = 'COMMENT' -N_TOKENS += 1 - -NL = N_TOKENS -tok_name[NL] = 'NL' -N_TOKENS += 1 - -if is_py3: - BACKQUOTE = N_TOKENS - tok_name[BACKQUOTE] = 'BACKQUOTE' - N_TOKENS += 1 -else: - RARROW = N_TOKENS - tok_name[RARROW] = 'RARROW' - N_TOKENS += 1 - ELLIPSIS = N_TOKENS - tok_name[ELLIPSIS] = 'ELLIPSIS' - N_TOKENS += 1 - -if not is_py35: - ATEQUAL = N_TOKENS - tok_name[ATEQUAL] = 'ATEQUAL' - N_TOKENS += 1 - - - -# Map from operator to number (since tokenize doesn't do this) - -opmap_raw = """\ -( LPAR -) RPAR -[ LSQB -] RSQB -: COLON -, COMMA -; SEMI -+ PLUS -- MINUS -* STAR -/ SLASH -| VBAR -& AMPER -< LESS -> GREATER -= EQUAL -. DOT -% PERCENT -` BACKQUOTE -{ LBRACE -} RBRACE -@ AT -== EQEQUAL -!= NOTEQUAL -<> NOTEQUAL -<= LESSEQUAL ->= GREATEREQUAL -~ TILDE -^ CIRCUMFLEX -<< LEFTSHIFT ->> RIGHTSHIFT -** DOUBLESTAR -+= PLUSEQUAL --= MINEQUAL -*= STAREQUAL -/= SLASHEQUAL -%= PERCENTEQUAL -&= AMPEREQUAL -|= VBAREQUAL -@= ATEQUAL -^= CIRCUMFLEXEQUAL -<<= LEFTSHIFTEQUAL ->>= RIGHTSHIFTEQUAL -**= DOUBLESTAREQUAL -// DOUBLESLASH -//= DOUBLESLASHEQUAL --> RARROW -... ELLIPSIS -""" - -opmap = {} -for line in opmap_raw.splitlines(): - op, name = line.split() - opmap[op] = globals()[name] diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/tokenize.py b/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/tokenize.py deleted file mode 100644 index 233c6d8..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/tokenize.py +++ /dev/null @@ -1,329 +0,0 @@ -# -*- coding: utf-8 -*- -""" -This tokenizer has been copied from the ``tokenize.py`` standard library -tokenizer. The reason was simple: The standard library tokenizer fails -if the indentation is not right. The fast parser of jedi however requires -"wrong" indentation. - -Basically this is a stripped down version of the standard library module, so -you can read the documentation there. Additionally we included some speed and -memory optimizations here. -""" -from __future__ import absolute_import - -import string -import re -from collections import namedtuple -from io import StringIO - -from jedi.parser.token import (tok_name, N_TOKENS, ENDMARKER, STRING, NUMBER, opmap, - NAME, OP, ERRORTOKEN, NEWLINE, INDENT, DEDENT) -from jedi._compatibility import is_py3 - - -cookie_re = re.compile("coding[:=]\s*([-\w.]+)") - - -if is_py3: - # Python 3 has str.isidentifier() to check if a char is a valid identifier - is_identifier = str.isidentifier -else: - namechars = string.ascii_letters + '_' - is_identifier = lambda s: s in namechars - - -COMMENT = N_TOKENS -tok_name[COMMENT] = 'COMMENT' - - -def group(*choices): - return '(' + '|'.join(choices) + ')' - - -def maybe(*choices): - return group(*choices) + '?' - - -# Note: we use unicode matching for names ("\w") but ascii matching for -# number literals. -whitespace = r'[ \f\t]*' -comment = r'#[^\r\n]*' -name = r'\w+' - -hex_number = r'0[xX][0-9a-fA-F]+' -bin_number = r'0[bB][01]+' -if is_py3: - oct_number = r'0[oO][0-7]+' -else: - oct_number = '0[0-7]+' -dec_number = r'(?:0+|[1-9][0-9]*)' -int_number = group(hex_number, bin_number, oct_number, dec_number) -exponent = r'[eE][-+]?[0-9]+' -point_float = group(r'[0-9]+\.[0-9]*', r'\.[0-9]+') + maybe(exponent) -Expfloat = r'[0-9]+' + exponent -float_number = group(point_float, Expfloat) -imag_number = group(r'[0-9]+[jJ]', float_number + r'[jJ]') -number = group(imag_number, float_number, int_number) - -# Tail end of ' string. -single = r"[^'\\]*(?:\\.[^'\\]*)*'" -# Tail end of " string. -double = r'[^"\\]*(?:\\.[^"\\]*)*"' -# Tail end of ''' string. -single3 = r"[^'\\]*(?:(?:\\.|'(?!''))[^'\\]*)*'''" -# Tail end of """ string. -double3 = r'[^"\\]*(?:(?:\\.|"(?!""))[^"\\]*)*"""' -triple = group("[uUbB]?[rR]?'''", '[uUbB]?[rR]?"""') -# Single-line ' or " string. - -# Because of leftmost-then-longest match semantics, be sure to put the -# longest operators first (e.g., if = came before ==, == would get -# recognized as two instances of =). -operator = group(r"\*\*=?", r">>=?", r"<<=?", r"!=", - r"//=?", r"->", - r"[+\-*@/%&|^=<>]=?", - r"~") - -bracket = '[][(){}]' -special = group(r'\r?\n', r'\.\.\.', r'[:;.,@]') -funny = group(operator, bracket, special) - -# First (or only) line of ' or " string. -cont_str = group(r"[bBuU]?[rR]?'[^\n'\\]*(?:\\.[^\n'\\]*)*" + - group("'", r'\\\r?\n'), - r'[bBuU]?[rR]?"[^\n"\\]*(?:\\.[^\n"\\]*)*' + - group('"', r'\\\r?\n')) -pseudo_extras = group(r'\\\r?\n', comment, triple) -pseudo_token = group(whitespace) + \ - group(pseudo_extras, number, funny, cont_str, name) - - -def _compile(expr): - return re.compile(expr, re.UNICODE) - - -pseudoprog, single3prog, double3prog = map( - _compile, (pseudo_token, single3, double3)) - -endprogs = {"'": _compile(single), '"': _compile(double), - "'''": single3prog, '"""': double3prog, - "r'''": single3prog, 'r"""': double3prog, - "b'''": single3prog, 'b"""': double3prog, - "u'''": single3prog, 'u"""': double3prog, - "R'''": single3prog, 'R"""': double3prog, - "B'''": single3prog, 'B"""': double3prog, - "U'''": single3prog, 'U"""': double3prog, - "br'''": single3prog, 'br"""': double3prog, - "bR'''": single3prog, 'bR"""': double3prog, - "Br'''": single3prog, 'Br"""': double3prog, - "BR'''": single3prog, 'BR"""': double3prog, - "ur'''": single3prog, 'ur"""': double3prog, - "uR'''": single3prog, 'uR"""': double3prog, - "Ur'''": single3prog, 'Ur"""': double3prog, - "UR'''": single3prog, 'UR"""': double3prog, - 'r': None, 'R': None, 'b': None, 'B': None} - -triple_quoted = {} -for t in ("'''", '"""', - "r'''", 'r"""', "R'''", 'R"""', - "b'''", 'b"""', "B'''", 'B"""', - "u'''", 'u"""', "U'''", 'U"""', - "br'''", 'br"""', "Br'''", 'Br"""', - "bR'''", 'bR"""', "BR'''", 'BR"""', - "ur'''", 'ur"""', "Ur'''", 'Ur"""', - "uR'''", 'uR"""', "UR'''", 'UR"""'): - triple_quoted[t] = t -single_quoted = {} -for t in ("'", '"', - "r'", 'r"', "R'", 'R"', - "b'", 'b"', "B'", 'B"', - "u'", 'u"', "U'", 'U"', - "br'", 'br"', "Br'", 'Br"', - "bR'", 'bR"', "BR'", 'BR"', - "ur'", 'ur"', "Ur'", 'Ur"', - "uR'", 'uR"', "UR'", 'UR"'): - single_quoted[t] = t - -del _compile - -tabsize = 8 - -# TODO add with? -ALWAYS_BREAK_TOKENS = (';', 'import', 'class', 'def', 'try', 'except', - 'finally', 'while', 'return') - - -class TokenInfo(namedtuple('Token', ['type', 'string', 'start_pos', 'prefix'])): - def __repr__(self): - annotated_type = tok_name[self.type] - return ('TokenInfo(type=%s, string=%r, start=%r, prefix=%r)' % - self._replace(type=annotated_type)) - - @property - def exact_type(self): - if self.type == OP and self.string in opmap: - return opmap[self.string] - else: - return self.type - - -def source_tokens(source, use_exact_op_types=False): - """Generate tokens from a the source code (string).""" - source = source - readline = StringIO(source).readline - return generate_tokens(readline, use_exact_op_types) - - -def generate_tokens(readline, use_exact_op_types=False): - """ - A heavily modified Python standard library tokenizer. - - Additionally to the default information, yields also the prefix of each - token. This idea comes from lib2to3. The prefix contains all information - that is irrelevant for the parser like newlines in parentheses or comments. - """ - paren_level = 0 # count parentheses - indents = [0] - lnum = 0 - max = 0 - numchars = '0123456789' - contstr = '' - contline = None - # We start with a newline. This makes indent at the first position - # possible. It's not valid Python, but still better than an INDENT in the - # second line (and not in the first). This makes quite a few things in - # Jedi's fast parser possible. - new_line = True - prefix = '' # Should never be required, but here for safety - additional_prefix = '' - while True: # loop over lines in stream - line = readline() # readline returns empty when finished. See StringIO - if not line: - if contstr: - yield TokenInfo(ERRORTOKEN, contstr, contstr_start, prefix) - break - - lnum += 1 - pos, max = 0, len(line) - - if contstr: # continued string - endmatch = endprog.match(line) - if endmatch: - pos = endmatch.end(0) - yield TokenInfo(STRING, contstr + line[:pos], contstr_start, prefix) - contstr = '' - contline = None - else: - contstr = contstr + line - contline = contline + line - continue - - while pos < max: - pseudomatch = pseudoprog.match(line, pos) - if not pseudomatch: # scan for tokens - txt = line[pos] - if line[pos] in '"\'': - # If a literal starts but doesn't end the whole rest of the - # line is an error token. - txt = line[pos:] - yield TokenInfo(ERRORTOKEN, txt, (lnum, pos), prefix) - pos += 1 - continue - - prefix = additional_prefix + pseudomatch.group(1) - additional_prefix = '' - start, pos = pseudomatch.span(2) - spos = (lnum, start) - token, initial = line[start:pos], line[start] - - if new_line and initial not in '\r\n#': - new_line = False - if paren_level == 0: - i = 0 - while line[i] == '\f': - i += 1 - start -= 1 - if start > indents[-1]: - yield TokenInfo(INDENT, '', spos, '') - indents.append(start) - while start < indents[-1]: - yield TokenInfo(DEDENT, '', spos, '') - indents.pop() - - if (initial in numchars or # ordinary number - (initial == '.' and token != '.' and token != '...')): - yield TokenInfo(NUMBER, token, spos, prefix) - elif initial in '\r\n': - if not new_line and paren_level == 0: - yield TokenInfo(NEWLINE, token, spos, prefix) - else: - additional_prefix = prefix + token - new_line = True - elif initial == '#': # Comments - assert not token.endswith("\n") - additional_prefix = prefix + token - elif token in triple_quoted: - endprog = endprogs[token] - endmatch = endprog.match(line, pos) - if endmatch: # all on one line - pos = endmatch.end(0) - token = line[start:pos] - yield TokenInfo(STRING, token, spos, prefix) - else: - contstr_start = (lnum, start) # multiple lines - contstr = line[start:] - contline = line - break - elif initial in single_quoted or \ - token[:2] in single_quoted or \ - token[:3] in single_quoted: - if token[-1] == '\n': # continued string - contstr_start = lnum, start - endprog = (endprogs.get(initial) or endprogs.get(token[1]) - or endprogs.get(token[2])) - contstr = line[start:] - contline = line - break - else: # ordinary string - yield TokenInfo(STRING, token, spos, prefix) - elif is_identifier(initial): # ordinary name - if token in ALWAYS_BREAK_TOKENS: - paren_level = 0 - while True: - indent = indents.pop() - if indent > start: - yield TokenInfo(DEDENT, '', spos, '') - else: - indents.append(indent) - break - yield TokenInfo(NAME, token, spos, prefix) - elif initial == '\\' and line[start:] in ('\\\n', '\\\r\n'): # continued stmt - additional_prefix += prefix + line[start:] - break - else: - if token in '([{': - paren_level += 1 - elif token in ')]}': - paren_level -= 1 - - try: - # This check is needed in any case to check if it's a valid - # operator or just some random unicode character. - exact_type = opmap[token] - except KeyError: - exact_type = typ = ERRORTOKEN - if use_exact_op_types: - typ = exact_type - else: - typ = OP - yield TokenInfo(typ, token, spos, prefix) - - if new_line or additional_prefix[-1:] == '\n': - end_pos = lnum + 1, 0 - else: - end_pos = lnum, max - # As the last position we just take the maximally possible position. We - # remove -1 for the last new line. - for indent in indents[1:]: - yield TokenInfo(DEDENT, '', end_pos, '') - yield TokenInfo(ENDMARKER, '', end_pos, additional_prefix) diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/tree.py b/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/tree.py deleted file mode 100644 index c5a2d55..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/tree.py +++ /dev/null @@ -1,1658 +0,0 @@ -""" -If you know what an abstract syntax tree (AST) is, you'll see that this module -is pretty much that. The classes represent syntax elements like functions and -imports. - -This is the "business logic" part of the parser. There's a lot of logic here -that makes it easier for Jedi (and other libraries to deal with a Python syntax -tree. - -By using `get_code` on a module, you can get back the 1-to-1 representation of -the input given to the parser. This is important if you are using refactoring. - -The easiest way to play with this module is to use :class:`parsing.Parser`. -:attr:`parsing.Parser.module` holds an instance of :class:`Module`: - ->>> from jedi._compatibility import u ->>> from jedi.parser import ParserWithRecovery, load_grammar ->>> parser = ParserWithRecovery(load_grammar(), u('import os'), 'example.py') ->>> submodule = parser.module ->>> submodule - - -Any subclasses of :class:`Scope`, including :class:`Module` has an attribute -:attr:`imports `: - ->>> submodule.imports -[] - -See also :attr:`Scope.subscopes` and :attr:`Scope.statements`. - -For static analysis purposes there exists a method called -``nodes_to_execute`` on all nodes and leaves. It's documented in the static -anaylsis documentation. -""" -import os -import re -from inspect import cleandoc -from itertools import chain -import textwrap -import abc - -from jedi._compatibility import (Python3Method, encoding, is_py3, utf8_repr, - literal_eval, use_metaclass, unicode) -from jedi.parser import token -from jedi.parser.utils import underscore_memoization - - -def is_node(node, *symbol_names): - try: - type = node.type - except AttributeError: - return False - else: - return type in symbol_names - - -class PositionModifier(object): - """A start_pos modifier for the fast parser.""" - def __init__(self): - self.line = 0 - - -zero_position_modifier = PositionModifier() - - -class DocstringMixin(object): - __slots__ = () - - @property - def raw_doc(self): - """ Returns a cleaned version of the docstring token. """ - if isinstance(self, Module): - node = self.children[0] - elif isinstance(self, ClassOrFunc): - node = self.children[self.children.index(':') + 1] - if is_node(node, 'suite'): # Normally a suite - node = node.children[2] # -> NEWLINE INDENT stmt - else: # ExprStmt - simple_stmt = self.parent - c = simple_stmt.parent.children - index = c.index(simple_stmt) - if not index: - return '' - node = c[index - 1] - - if is_node(node, 'simple_stmt'): - node = node.children[0] - - if node.type == 'string': - # TODO We have to check next leaves until there are no new - # leaves anymore that might be part of the docstring. A - # docstring can also look like this: ``'foo' 'bar' - # Returns a literal cleaned version of the ``Token``. - cleaned = cleandoc(literal_eval(node.value)) - # Since we want the docstr output to be always unicode, just - # force it. - if is_py3 or isinstance(cleaned, unicode): - return cleaned - else: - return unicode(cleaned, 'UTF-8', 'replace') - return '' - - -class Base(object): - """ - This is just here to have an isinstance check, which is also used on - evaluate classes. But since they have sometimes a special type of - delegation, it is important for those classes to override this method. - - I know that there is a chance to do such things with __instancecheck__, but - since Python 2.5 doesn't support it, I decided to do it this way. - """ - __slots__ = () - - def isinstance(self, *cls): - return isinstance(self, cls) - - @Python3Method - def get_parent_until(self, classes=(), reverse=False, - include_current=True): - """ - Searches the parent "chain" until the object is an instance of - classes. If classes is empty return the last parent in the chain - (is without a parent). - """ - if type(classes) not in (tuple, list): - classes = (classes,) - scope = self if include_current else self.parent - while scope.parent is not None: - # TODO why if classes? - if classes and reverse != scope.isinstance(*classes): - break - scope = scope.parent - return scope - - def get_parent_scope(self, include_flows=False): - """ - Returns the underlying scope. - """ - scope = self.parent - while scope is not None: - if include_flows and isinstance(scope, Flow): - return scope - if scope.is_scope(): - break - scope = scope.parent - return scope - - def get_definition(self): - if self.type in ('newline', 'dedent', 'indent', 'endmarker'): - raise ValueError('Cannot get the indentation of whitespace or indentation.') - scope = self - while scope.parent is not None: - parent = scope.parent - if scope.isinstance(Node, Leaf) and parent.type != 'simple_stmt': - if scope.type == 'testlist_comp': - try: - if isinstance(scope.children[1], CompFor): - return scope.children[1] - except IndexError: - pass - scope = parent - else: - break - return scope - - def assignment_indexes(self): - """ - Returns an array of tuple(int, node) of the indexes that are used in - tuple assignments. - - For example if the name is ``y`` in the following code:: - - x, (y, z) = 2, '' - - would result in ``[(1, xyz_node), (0, yz_node)]``. - """ - indexes = [] - node = self.parent - compare = self - while node is not None: - if is_node(node, 'testlist_comp', 'testlist_star_expr', 'exprlist'): - for i, child in enumerate(node.children): - if child == compare: - indexes.insert(0, (int(i / 2), node)) - break - else: - raise LookupError("Couldn't find the assignment.") - elif isinstance(node, (ExprStmt, CompFor)): - break - - compare = node - node = node.parent - return indexes - - def is_scope(self): - # Default is not being a scope. Just inherit from Scope. - return False - - @abc.abstractmethod - def nodes_to_execute(self, last_added=False): - raise NotImplementedError() - - def get_next_sibling(self): - """ - The node immediately following the invocant in their parent's children - list. If the invocant does not have a next sibling, it is None - """ - # Can't use index(); we need to test by identity - for i, child in enumerate(self.parent.children): - if child is self: - try: - return self.parent.children[i + 1] - except IndexError: - return None - - def get_previous_sibling(self): - """ - The node/leaf immediately preceding the invocant in their parent's - children list. If the invocant does not have a previous sibling, it is - None. - """ - # Can't use index(); we need to test by identity - for i, child in enumerate(self.parent.children): - if child is self: - if i == 0: - return None - return self.parent.children[i - 1] - - def get_previous_leaf(self): - """ - Returns the previous leaf in the parser tree. - Raises an IndexError if it's the first element. - """ - node = self - while True: - c = node.parent.children - i = c.index(node) - if i == 0: - node = node.parent - if node.parent is None: - raise IndexError('Cannot access the previous element of the first one.') - else: - node = c[i - 1] - break - - while True: - try: - node = node.children[-1] - except AttributeError: # A Leaf doesn't have children. - return node - - def get_next_leaf(self): - """ - Returns the previous leaf in the parser tree. - Raises an IndexError if it's the last element. - """ - node = self - while True: - c = node.parent.children - i = c.index(node) - if i == len(c) - 1: - node = node.parent - if node.parent is None: - raise IndexError('Cannot access the next element of the last one.') - else: - node = c[i + 1] - break - - while True: - try: - node = node.children[0] - except AttributeError: # A Leaf doesn't have children. - return node - - -class Leaf(Base): - __slots__ = ('position_modifier', 'value', 'parent', '_start_pos', 'prefix') - - def __init__(self, position_modifier, value, start_pos, prefix=''): - self.position_modifier = position_modifier - self.value = value - self._start_pos = start_pos - self.prefix = prefix - self.parent = None - - @property - def start_pos(self): - return self._start_pos[0] + self.position_modifier.line, self._start_pos[1] - - @start_pos.setter - def start_pos(self, value): - self._start_pos = value[0] - self.position_modifier.line, value[1] - - def get_start_pos_of_prefix(self): - try: - previous_leaf = self - while True: - previous_leaf = previous_leaf.get_previous_leaf() - if previous_leaf.type not in ('indent', 'dedent'): - return previous_leaf.end_pos - except IndexError: - return 1, 0 # It's the first leaf. - - @property - def end_pos(self): - return (self._start_pos[0] + self.position_modifier.line, - self._start_pos[1] + len(self.value)) - - def move(self, line_offset, column_offset): - self._start_pos = (self._start_pos[0] + line_offset, - self._start_pos[1] + column_offset) - - def first_leaf(self): - return self - - def get_code(self, normalized=False, include_prefix=True): - if normalized: - return self.value - if include_prefix: - return self.prefix + self.value - else: - return self.value - - def nodes_to_execute(self, last_added=False): - return [] - - @utf8_repr - def __repr__(self): - return "<%s: %s>" % (type(self).__name__, self.value) - - -class LeafWithNewLines(Leaf): - __slots__ = () - - @property - def end_pos(self): - """ - Literals and whitespace end_pos are more complicated than normal - end_pos, because the containing newlines may change the indexes. - """ - end_pos_line, end_pos_col = self.start_pos - lines = self.value.split('\n') - end_pos_line += len(lines) - 1 - # Check for multiline token - if self.start_pos[0] == end_pos_line: - end_pos_col += len(lines[-1]) - else: - end_pos_col = len(lines[-1]) - return end_pos_line, end_pos_col - - @utf8_repr - def __repr__(self): - return "<%s: %r>" % (type(self).__name__, self.value) - - -class EndMarker(Leaf): - __slots__ = () - type = 'endmarker' - - -class Newline(LeafWithNewLines): - """Contains NEWLINE and ENDMARKER tokens.""" - __slots__ = () - type = 'newline' - - @utf8_repr - def __repr__(self): - return "<%s: %s>" % (type(self).__name__, repr(self.value)) - - -class Name(Leaf): - """ - A string. Sometimes it is important to know if the string belongs to a name - or not. - """ - type = 'name' - __slots__ = () - - def __str__(self): - return self.value - - def __unicode__(self): - return self.value - - def __repr__(self): - return "<%s: %s@%s,%s>" % (type(self).__name__, self.value, - self.start_pos[0], self.start_pos[1]) - - def is_definition(self): - if self.parent.type in ('power', 'atom_expr'): - # In `self.x = 3` self is not a definition, but x is. - return False - - stmt = self.get_definition() - if stmt.type in ('funcdef', 'classdef', 'file_input', 'param'): - return self == stmt.name - elif stmt.type == 'for_stmt': - return self.start_pos < stmt.children[2].start_pos - elif stmt.type == 'try_stmt': - return self.get_previous_sibling() == 'as' - else: - return stmt.type in ('expr_stmt', 'import_name', 'import_from', - 'comp_for', 'with_stmt') \ - and self in stmt.get_defined_names() - - def nodes_to_execute(self, last_added=False): - if last_added is False: - yield self - - -class Literal(LeafWithNewLines): - __slots__ = () - - def eval(self): - return literal_eval(self.value) - - -class Number(Literal): - type = 'number' - __slots__ = () - - -class String(Literal): - type = 'string' - __slots__ = () - - -class Indent(Leaf): - type = 'indent' - __slots__ = () - - -class Dedent(Leaf): - type = 'dedent' - __slots__ = () - - -class Operator(Leaf): - type = 'operator' - __slots__ = () - - def __str__(self): - return self.value - - def __eq__(self, other): - """ - Make comparisons with strings easy. - Improves the readability of the parser. - """ - if isinstance(other, Operator): - return self is other - else: - return self.value == other - - def __ne__(self, other): - """Python 2 compatibility.""" - return self.value != other - - def __hash__(self): - return hash(self.value) - - -class Keyword(Leaf): - type = 'keyword' - __slots__ = () - - def __eq__(self, other): - """ - Make comparisons with strings easy. - Improves the readability of the parser. - """ - if isinstance(other, Keyword): - return self is other - return self.value == other - - def __ne__(self, other): - """Python 2 compatibility.""" - return not self.__eq__(other) - - def __hash__(self): - return hash(self.value) - - -class BaseNode(Base): - """ - The super class for Scope, Import, Name and Statement. Every object in - the parser tree inherits from this class. - """ - __slots__ = ('children', 'parent') - type = None - - def __init__(self, children): - """ - Initialize :class:`BaseNode`. - - :param children: The module in which this Python object locates. - """ - for c in children: - c.parent = self - self.children = children - self.parent = None - - def move(self, line_offset, column_offset): - """ - Move the Node's start_pos. - """ - for c in self.children: - c.move(line_offset, column_offset) - - @property - def start_pos(self): - return self.children[0].start_pos - - def get_start_pos_of_prefix(self): - return self.children[0].get_start_pos_of_prefix() - - @property - def end_pos(self): - return self.children[-1].end_pos - - def get_code(self, normalized=False, include_prefix=True): - # TODO implement normalized (depending on context). - if include_prefix: - return "".join(c.get_code(normalized) for c in self.children) - else: - first = self.children[0].get_code(include_prefix=False) - return first + "".join(c.get_code(normalized) for c in self.children[1:]) - - @Python3Method - def name_for_position(self, position): - for c in self.children: - if isinstance(c, Leaf): - if isinstance(c, Name) and c.start_pos <= position <= c.end_pos: - return c - else: - result = c.name_for_position(position) - if result is not None: - return result - return None - - def get_leaf_for_position(self, position, include_prefixes=False): - for c in self.children: - if include_prefixes: - start_pos = c.get_start_pos_of_prefix() - else: - start_pos = c.start_pos - - if start_pos <= position <= c.end_pos: - try: - return c.get_leaf_for_position(position, include_prefixes) - except AttributeError: - while c.type in ('indent', 'dedent'): - # We'd rather not have indents and dedents as a leaf, - # because they don't contain indentation information. - c = c.get_next_leaf() - return c - - return None - - @Python3Method - def get_statement_for_position(self, pos): - for c in self.children: - if c.start_pos <= pos <= c.end_pos: - if c.type not in ('decorated', 'simple_stmt', 'suite') \ - and not isinstance(c, (Flow, ClassOrFunc)): - return c - else: - try: - return c.get_statement_for_position(pos) - except AttributeError: - pass # Must be a non-scope - return None - - def first_leaf(self): - try: - return self.children[0].first_leaf() - except AttributeError: - return self.children[0] - - def get_next_leaf(self): - """ - Raises an IndexError if it's the last node. (Would be the module) - """ - c = self.parent.children - index = c.index(self) - if index == len(c) - 1: - # TODO WTF? recursion? - return self.get_next_leaf() - else: - return c[index + 1] - - def last_leaf(self): - try: - return self.children[-1].last_leaf() - except AttributeError: - return self.children[-1] - - def get_following_comment_same_line(self): - """ - returns (as string) any comment that appears on the same line, - after the node, including the # - """ - try: - if self.isinstance(ForStmt): - whitespace = self.children[5].first_leaf().prefix - elif self.isinstance(WithStmt): - whitespace = self.children[3].first_leaf().prefix - else: - whitespace = self.last_leaf().get_next_leaf().prefix - except AttributeError: - return None - except ValueError: - # TODO in some particular cases, the tree doesn't seem to be linked - # correctly - return None - if "#" not in whitespace: - return None - comment = whitespace[whitespace.index("#"):] - if "\r" in comment: - comment = comment[:comment.index("\r")] - if "\n" in comment: - comment = comment[:comment.index("\n")] - return comment - - @utf8_repr - def __repr__(self): - code = self.get_code().replace('\n', ' ').strip() - if not is_py3: - code = code.encode(encoding, 'replace') - return "<%s: %s@%s,%s>" % \ - (type(self).__name__, code, self.start_pos[0], self.start_pos[1]) - - -class Node(BaseNode): - """Concrete implementation for interior nodes.""" - __slots__ = ('type',) - - _IGNORE_EXECUTE_NODES = set([ - 'suite', 'subscriptlist', 'subscript', 'simple_stmt', 'sliceop', - 'testlist_comp', 'dictorsetmaker', 'trailer', 'decorators', - 'decorated', 'arglist', 'argument', 'exprlist', 'testlist', - 'testlist_safe', 'testlist1' - ]) - - def __init__(self, type, children): - """ - Initializer. - - Takes a type constant (a symbol number >= 256), a sequence of - child nodes, and an optional context keyword argument. - - As a side effect, the parent pointers of the children are updated. - """ - super(Node, self).__init__(children) - self.type = type - - def nodes_to_execute(self, last_added=False): - """ - For static analysis. - """ - result = [] - if self.type not in Node._IGNORE_EXECUTE_NODES and not last_added: - result.append(self) - last_added = True - - for child in self.children: - result += child.nodes_to_execute(last_added) - return result - - def __repr__(self): - return "%s(%s, %r)" % (self.__class__.__name__, self.type, self.children) - - -class ErrorNode(BaseNode): - """ - TODO doc - """ - __slots__ = () - type = 'error_node' - - def nodes_to_execute(self, last_added=False): - return [] - - -class ErrorLeaf(LeafWithNewLines): - """ - TODO doc - """ - __slots__ = ('original_type') - type = 'error_leaf' - - def __init__(self, position_modifier, original_type, value, start_pos, prefix=''): - super(ErrorLeaf, self).__init__(position_modifier, value, start_pos, prefix) - self.original_type = original_type - - def __repr__(self): - token_type = token.tok_name[self.original_type] - return "<%s: %s, %s)>" % (type(self).__name__, token_type, self.start_pos) - - -class IsScopeMeta(type): - def __instancecheck__(self, other): - return other.is_scope() - - -class IsScope(use_metaclass(IsScopeMeta)): - pass - - -class Scope(BaseNode, DocstringMixin): - """ - Super class for the parser tree, which represents the state of a python - text file. - A Scope manages and owns its subscopes, which are classes and functions, as - well as variables and imports. It is used to access the structure of python - files. - - :param start_pos: The position (line and column) of the scope. - :type start_pos: tuple(int, int) - """ - __slots__ = ('names_dict',) - - def __init__(self, children): - super(Scope, self).__init__(children) - - @property - def returns(self): - # Needed here for fast_parser, because the fast_parser splits and - # returns will be in "normal" modules. - return self._search_in_scope(ReturnStmt) - - @property - def subscopes(self): - return self._search_in_scope(Scope) - - @property - def flows(self): - return self._search_in_scope(Flow) - - @property - def imports(self): - return self._search_in_scope(Import) - - @Python3Method - def _search_in_scope(self, typ): - def scan(children): - elements = [] - for element in children: - if isinstance(element, typ): - elements.append(element) - if is_node(element, 'suite', 'simple_stmt', 'decorated') \ - or isinstance(element, Flow): - elements += scan(element.children) - return elements - - return scan(self.children) - - @property - def statements(self): - return self._search_in_scope((ExprStmt, KeywordStatement)) - - def is_scope(self): - return True - - def __repr__(self): - try: - name = self.path - except AttributeError: - try: - name = self.name - except AttributeError: - name = self.command - - return "<%s: %s@%s-%s>" % (type(self).__name__, name, - self.start_pos[0], self.end_pos[0]) - - def walk(self): - yield self - for s in self.subscopes: - for scope in s.walk(): - yield scope - - for r in self.statements: - while isinstance(r, Flow): - for scope in r.walk(): - yield scope - r = r.next - - -class Module(Scope): - """ - The top scope, which is always a module. - Depending on the underlying parser this may be a full module or just a part - of a module. - """ - __slots__ = ('path', 'global_names', 'used_names', '_name') - type = 'file_input' - - def __init__(self, children): - """ - Initialize :class:`Module`. - - :type path: str - :arg path: File path to this module. - - .. todo:: Document `top_module`. - """ - super(Module, self).__init__(children) - self.path = None # Set later. - - @property - @underscore_memoization - def name(self): - """ This is used for the goto functions. """ - if self.path is None: - string = '' # no path -> empty name - else: - sep = (re.escape(os.path.sep),) * 2 - r = re.search(r'([^%s]*?)(%s__init__)?(\.py|\.so)?$' % sep, self.path) - # Remove PEP 3149 names - string = re.sub('\.[a-z]+-\d{2}[mud]{0,3}$', '', r.group(1)) - # Positions are not real, but a module starts at (1, 0) - p = (1, 0) - name = Name(zero_position_modifier, string, p) - name.parent = self - return name - - @property - def has_explicit_absolute_import(self): - """ - Checks if imports in this module are explicitly absolute, i.e. there - is a ``__future__`` import. - """ - # TODO this is a strange scan and not fully correct. I think Python's - # parser does it in a different way and scans for the first - # statement/import with a tokenizer (to check for syntax changes like - # the future print statement). - for imp in self.imports: - if imp.type == 'import_from' and imp.level == 0: - for path in imp.paths(): - if [str(name) for name in path] == ['__future__', 'absolute_import']: - return True - return False - - def nodes_to_execute(self, last_added=False): - # Yield itself, class needs to be executed for decorator checks. - result = [] - for child in self.children: - result += child.nodes_to_execute() - return result - - -class Decorator(BaseNode): - type = 'decorator' - __slots__ = () - - def nodes_to_execute(self, last_added=False): - if self.children[-2] == ')': - node = self.children[-3] - if node != '(': - return node.nodes_to_execute() - return [] - - -class ClassOrFunc(Scope): - __slots__ = () - - @property - def name(self): - return self.children[1] - - def get_decorators(self): - decorated = self.parent - if is_node(decorated, 'decorated'): - if is_node(decorated.children[0], 'decorators'): - return decorated.children[0].children - else: - return decorated.children[:1] - else: - return [] - - -class Class(ClassOrFunc): - """ - Used to store the parsed contents of a python class. - - :param name: The Class name. - :type name: str - :param supers: The super classes of a Class. - :type supers: list - :param start_pos: The start position (line, column) of the class. - :type start_pos: tuple(int, int) - """ - type = 'classdef' - __slots__ = () - - def __init__(self, children): - super(Class, self).__init__(children) - - def get_super_arglist(self): - if self.children[2] != '(': # Has no parentheses - return None - else: - if self.children[3] == ')': # Empty parentheses - return None - else: - return self.children[3] - - @property - def doc(self): - """ - Return a document string including call signature of __init__. - """ - docstr = self.raw_doc - for sub in self.subscopes: - if str(sub.name) == '__init__': - return '%s\n\n%s' % ( - sub.get_call_signature(func_name=self.name), docstr) - return docstr - - def nodes_to_execute(self, last_added=False): - # Yield itself, class needs to be executed for decorator checks. - yield self - # Super arguments. - arglist = self.get_super_arglist() - try: - children = arglist.children - except AttributeError: - if arglist is not None: - for node_to_execute in arglist.nodes_to_execute(): - yield node_to_execute - else: - for argument in children: - if argument.type == 'argument': - # metaclass= or list comprehension or */** - raise NotImplementedError('Metaclasses not implemented') - else: - for node_to_execute in argument.nodes_to_execute(): - yield node_to_execute - - # care for the class suite: - for node in self.children[self.children.index(':'):]: - # This could be easier without the fast parser. But we need to find - # the position of the colon, because everything after it can be a - # part of the class, not just its suite. - for node_to_execute in node.nodes_to_execute(): - yield node_to_execute - - -def _create_params(parent, argslist_list): - """ - `argslist_list` is a list that can contain an argslist as a first item, but - most not. It's basically the items between the parameter brackets (which is - at most one item). - This function modifies the parser structure. It generates `Param` objects - from the normal ast. Those param objects do not exist in a normal ast, but - make the evaluation of the ast tree so much easier. - You could also say that this function replaces the argslist node with a - list of Param objects. - """ - def check_python2_nested_param(node): - """ - Python 2 allows params to look like ``def x(a, (b, c))``, which is - basically a way of unpacking tuples in params. Python 3 has ditched - this behavior. Jedi currently just ignores those constructs. - """ - return node.type == 'tfpdef' and node.children[0] == '(' - - try: - first = argslist_list[0] - except IndexError: - return [] - - if first.type in ('name', 'tfpdef'): - if check_python2_nested_param(first): - return [first] - else: - return [Param([first], parent)] - elif first == '*': - return [first] - else: # argslist is a `typedargslist` or a `varargslist`. - children = first.children - new_children = [] - start = 0 - # Start with offset 1, because the end is higher. - for end, child in enumerate(children + [None], 1): - if child is None or child == ',': - param_children = children[start:end] - if param_children: # Could as well be comma and then end. - if check_python2_nested_param(param_children[0]): - new_children += param_children - elif param_children[0] == '*' and param_children[1] == ',': - new_children += param_children - else: - new_children.append(Param(param_children, parent)) - start = end - return new_children - - -class Function(ClassOrFunc): - """ - Used to store the parsed contents of a python function. - - Children: - 0) - 1) - 2) parameter list (including open-paren and close-paren s) - 3) - 4) Node() representing function body - 5) ?? - 6) annotation (if present) - """ - __slots__ = ('listeners',) - type = 'funcdef' - - def __init__(self, children): - super(Function, self).__init__(children) - self.listeners = set() # not used here, but in evaluation. - parameters = self.children[2] # After `def foo` - parameters.children[1:-1] = _create_params(parameters, parameters.children[1:-1]) - - @property - def params(self): - return [p for p in self.children[2].children if p.type == 'param'] - - @property - def name(self): - return self.children[1] # First token after `def` - - @property - def yields(self): - # TODO This is incorrect, yields are also possible in a statement. - return self._search_in_scope(YieldExpr) - - def is_generator(self): - return bool(self.yields) - - def annotation(self): - try: - if self.children[3] == "->": - return self.children[4] - assert self.children[3] == ":" - return None - except IndexError: - return None - - def get_call_signature(self, width=72, func_name=None): - """ - Generate call signature of this function. - - :param width: Fold lines if a line is longer than this value. - :type width: int - :arg func_name: Override function name when given. - :type func_name: str - - :rtype: str - """ - func_name = func_name or self.name - code = unicode(func_name) + self._get_paramlist_code() - return '\n'.join(textwrap.wrap(code, width)) - - def _get_paramlist_code(self): - return self.children[2].get_code() - - @property - def doc(self): - """ Return a document string including call signature. """ - docstr = self.raw_doc - return '%s\n\n%s' % (self.get_call_signature(), docstr) - - def nodes_to_execute(self, last_added=False): - # Yield itself, functions needs to be executed for decorator checks. - yield self - for param in self.params: - if param.default is not None: - yield param.default - # care for the function suite: - for node in self.children[4:]: - # This could be easier without the fast parser. The fast parser - # allows that the 4th position is empty or that there's even a - # fifth element (another function/class). So just scan everything - # after colon. - for node_to_execute in node.nodes_to_execute(): - yield node_to_execute - - -class Lambda(Function): - """ - Lambdas are basically trimmed functions, so give it the same interface. - - Children: - 0) - *) for each argument x - -2) - -1) Node() representing body - """ - type = 'lambda' - __slots__ = () - - def __init__(self, children): - # We don't want to call the Function constructor, call its parent. - super(Function, self).__init__(children) - self.listeners = set() # not used here, but in evaluation. - lst = self.children[1:-2] # Everything between `lambda` and the `:` operator is a parameter. - self.children[1:-2] = _create_params(self, lst) - - @property - def name(self): - # Borrow the position of the AST node. - return Name(self.children[0].position_modifier, '', self.children[0].start_pos) - - def _get_paramlist_code(self): - return '(' + ''.join(param.get_code() for param in self.params).strip() + ')' - - @property - def params(self): - return self.children[1:-2] - - def is_generator(self): - return False - - def annotation(self): - # lambda functions do not support annotations - return None - - @property - def yields(self): - return [] - - def nodes_to_execute(self, last_added=False): - for param in self.params: - if param.default is not None: - yield param.default - # Care for the lambda test (last child): - for node_to_execute in self.children[-1].nodes_to_execute(): - yield node_to_execute - - def __repr__(self): - return "<%s@%s>" % (self.__class__.__name__, self.start_pos) - - -class Flow(BaseNode): - __slots__ = () - - def nodes_to_execute(self, last_added=False): - for child in self.children: - for node_to_execute in child.nodes_to_execute(): - yield node_to_execute - - -class IfStmt(Flow): - type = 'if_stmt' - __slots__ = () - - def check_nodes(self): - """ - Returns all the `test` nodes that are defined as x, here: - - if x: - pass - elif x: - pass - """ - for i, c in enumerate(self.children): - if c in ('elif', 'if'): - yield self.children[i + 1] - - def node_in_which_check_node(self, node): - """ - Returns the check node (see function above) that a node is contained - in. However if it the node is in the check node itself and not in the - suite return None. - """ - start_pos = node.start_pos - for check_node in reversed(list(self.check_nodes())): - if check_node.start_pos < start_pos: - if start_pos < check_node.end_pos: - return None - # In this case the node is within the check_node itself, - # not in the suite - else: - return check_node - - def node_after_else(self, node): - """ - Checks if a node is defined after `else`. - """ - for c in self.children: - if c == 'else': - if node.start_pos > c.start_pos: - return True - else: - return False - - -class WhileStmt(Flow): - type = 'while_stmt' - __slots__ = () - - -class ForStmt(Flow): - type = 'for_stmt' - __slots__ = () - - def get_input_node(self): - """ - Returns the input node ``y`` from: ``for x in y:``. - """ - return self.children[3] - - def defines_one_name(self): - """ - Returns True if only one name is returned: ``for x in y``. - Returns False if the for loop is more complicated: ``for x, z in y``. - - :returns: bool - """ - return self.children[1].type == 'name' - - -class TryStmt(Flow): - type = 'try_stmt' - __slots__ = () - - def except_clauses(self): - """ - Returns the ``test`` nodes found in ``except_clause`` nodes. - Returns ``[None]`` for except clauses without an exception given. - """ - for node in self.children: - if node.type == 'except_clause': - yield node.children[1] - elif node == 'except': - yield None - - def nodes_to_execute(self, last_added=False): - result = [] - for child in self.children[2::3]: - result += child.nodes_to_execute() - for child in self.children[0::3]: - if child.type == 'except_clause': - # Add the test node and ignore the `as NAME` definition. - result += child.children[1].nodes_to_execute() - return result - - -class WithStmt(Flow): - type = 'with_stmt' - __slots__ = () - - def get_defined_names(self): - names = [] - for with_item in self.children[1:-2:2]: - # Check with items for 'as' names. - if is_node(with_item, 'with_item'): - names += _defined_names(with_item.children[2]) - return names - - def node_from_name(self, name): - node = name - while True: - node = node.parent - if is_node(node, 'with_item'): - return node.children[0] - - def nodes_to_execute(self, last_added=False): - result = [] - for child in self.children[1::2]: - if child.type == 'with_item': - # Just ignore the `as EXPR` part - at least for now, because - # most times it's just a name. - child = child.children[0] - result += child.nodes_to_execute() - return result - - -class Import(BaseNode): - __slots__ = () - - def path_for_name(self, name): - try: - # The name may be an alias. If it is, just map it back to the name. - name = self.aliases()[name] - except KeyError: - pass - - for path in self.paths(): - if name in path: - return path[:path.index(name) + 1] - raise ValueError('Name should be defined in the import itself') - - def is_nested(self): - return False # By default, sub classes may overwrite this behavior - - def is_star_import(self): - return self.children[-1] == '*' - - def nodes_to_execute(self, last_added=False): - """ - `nodes_to_execute` works a bit different for imports, because the names - itself cannot directly get resolved (except on itself). - """ - # TODO couldn't we return the names? Would be nicer. - return [self] - - -class ImportFrom(Import): - type = 'import_from' - __slots__ = () - - def get_defined_names(self): - return [alias or name for name, alias in self._as_name_tuples()] - - def aliases(self): - """Mapping from alias to its corresponding name.""" - return dict((alias, name) for name, alias in self._as_name_tuples() - if alias is not None) - - def get_from_names(self): - for n in self.children[1:]: - if n not in ('.', '...'): - break - if is_node(n, 'dotted_name'): # from x.y import - return n.children[::2] - elif n == 'import': # from . import - return [] - else: # from x import - return [n] - - @property - def level(self): - """The level parameter of ``__import__``.""" - level = 0 - for n in self.children[1:]: - if n in ('.', '...'): - level += len(n.value) - else: - break - return level - - def _as_name_tuples(self): - last = self.children[-1] - if last == ')': - last = self.children[-2] - elif last == '*': - return # No names defined directly. - - if is_node(last, 'import_as_names'): - as_names = last.children[::2] - else: - as_names = [last] - for as_name in as_names: - if as_name.type == 'name': - yield as_name, None - else: - yield as_name.children[::2] # yields x, y -> ``x as y`` - - def star_import_name(self): - """ - The last name defined in a star import. - """ - return self.paths()[-1][-1] - - def paths(self): - """ - The import paths defined in an import statement. Typically an array - like this: ``[, ]``. - """ - dotted = self.get_from_names() - - if self.children[-1] == '*': - return [dotted] - return [dotted + [name] for name, alias in self._as_name_tuples()] - - -class ImportName(Import): - """For ``import_name`` nodes. Covers normal imports without ``from``.""" - type = 'import_name' - __slots__ = () - - def get_defined_names(self): - return [alias or path[0] for path, alias in self._dotted_as_names()] - - @property - def level(self): - """The level parameter of ``__import__``.""" - return 0 # Obviously 0 for imports without from. - - def paths(self): - return [path for path, alias in self._dotted_as_names()] - - def _dotted_as_names(self): - """Generator of (list(path), alias) where alias may be None.""" - dotted_as_names = self.children[1] - if is_node(dotted_as_names, 'dotted_as_names'): - as_names = dotted_as_names.children[::2] - else: - as_names = [dotted_as_names] - - for as_name in as_names: - if is_node(as_name, 'dotted_as_name'): - alias = as_name.children[2] - as_name = as_name.children[0] - else: - alias = None - if as_name.type == 'name': - yield [as_name], alias - else: - # dotted_names - yield as_name.children[::2], alias - - def is_nested(self): - """ - This checks for the special case of nested imports, without aliases and - from statement:: - - import foo.bar - """ - return [1 for path, alias in self._dotted_as_names() - if alias is None and len(path) > 1] - - def aliases(self): - return dict((alias, path[-1]) for path, alias in self._dotted_as_names() - if alias is not None) - - -class KeywordStatement(BaseNode): - """ - For the following statements: `assert`, `del`, `global`, `nonlocal`, - `raise`, `return`, `yield`, `return`, `yield`. - - `pass`, `continue` and `break` are not in there, because they are just - simple keywords and the parser reduces it to a keyword. - """ - __slots__ = () - - @property - def type(self): - """ - Keyword statements start with the keyword and end with `_stmt`. You can - crosscheck this with the Python grammar. - """ - return '%s_stmt' % self.keyword - - @property - def keyword(self): - return self.children[0].value - - def nodes_to_execute(self, last_added=False): - result = [] - for child in self.children: - result += child.nodes_to_execute() - return result - - -class AssertStmt(KeywordStatement): - __slots__ = () - - def assertion(self): - return self.children[1] - - -class GlobalStmt(KeywordStatement): - __slots__ = () - - def get_defined_names(self): - return [] - - def get_global_names(self): - return self.children[1::2] - - def nodes_to_execute(self, last_added=False): - """ - The global keyword allows to define any name. Even if it doesn't - exist. - """ - return [] - - -class ReturnStmt(KeywordStatement): - __slots__ = () - - -class YieldExpr(BaseNode): - __slots__ = () - - @property - def type(self): - return 'yield_expr' - - def nodes_to_execute(self, last_added=False): - if len(self.children) > 1: - return self.children[1].nodes_to_execute() - else: - return [] - - -def _defined_names(current): - """ - A helper function to find the defined names in statements, for loops and - list comprehensions. - """ - names = [] - if is_node(current, 'testlist_star_expr', 'testlist_comp', 'exprlist'): - for child in current.children[::2]: - names += _defined_names(child) - elif is_node(current, 'atom', 'star_expr'): - names += _defined_names(current.children[1]) - elif is_node(current, 'power', 'atom_expr'): - if current.children[-2] != '**': # Just if there's no operation - trailer = current.children[-1] - if trailer.children[0] == '.': - names.append(trailer.children[1]) - else: - names.append(current) - return names - - -class ExprStmt(BaseNode, DocstringMixin): - type = 'expr_stmt' - __slots__ = () - - def get_defined_names(self): - return list(chain.from_iterable(_defined_names(self.children[i]) - for i in range(0, len(self.children) - 2, 2) - if '=' in self.children[i + 1].value)) - - def get_rhs(self): - """Returns the right-hand-side of the equals.""" - return self.children[-1] - - def first_operation(self): - """ - Returns `+=`, `=`, etc or None if there is no operation. - """ - try: - return self.children[1] - except IndexError: - return None - - def nodes_to_execute(self, last_added=False): - # I think evaluating the statement (and possibly returned arrays), - # should be enough for static analysis. - result = [self] - for child in self.children: - result += child.nodes_to_execute(last_added=True) - return result - - -class Param(BaseNode): - """ - It's a helper class that makes business logic with params much easier. The - Python grammar defines no ``param`` node. It defines it in a different way - that is not really suited to working with parameters. - """ - type = 'param' - - def __init__(self, children, parent): - super(Param, self).__init__(children) - self.parent = parent - for child in children: - child.parent = self - - @property - def stars(self): - first = self.children[0] - if first in ('*', '**'): - return len(first.value) - return 0 - - @property - def default(self): - try: - return self.children[int(self.children[0] in ('*', '**')) + 2] - except IndexError: - return None - - def annotation(self): - tfpdef = self._tfpdef() - if is_node(tfpdef, 'tfpdef'): - assert tfpdef.children[1] == ":" - assert len(tfpdef.children) == 3 - annotation = tfpdef.children[2] - return annotation - else: - return None - - def _tfpdef(self): - """ - tfpdef: see grammar.txt. - """ - offset = int(self.children[0] in ('*', '**')) - return self.children[offset] - - @property - def name(self): - if is_node(self._tfpdef(), 'tfpdef'): - return self._tfpdef().children[0] - else: - return self._tfpdef() - - @property - def position_nr(self): - return self.parent.children.index(self) - 1 - - @property - def parent_function(self): - return self.get_parent_until(IsScope) - - def __repr__(self): - default = '' if self.default is None else '=%s' % self.default - return '<%s: %s>' % (type(self).__name__, str(self._tfpdef()) + default) - - -class CompFor(BaseNode): - type = 'comp_for' - __slots__ = () - - def get_comp_fors(self): - yield self - last = self.children[-1] - while True: - if isinstance(last, CompFor): - yield last - elif not is_node(last, 'comp_if'): - break - last = last.children[-1] - - def is_scope(self): - return True - - @property - def names_dict(self): - dct = {} - for name in self.get_defined_names(): - arr = dct.setdefault(name.value, []) - arr.append(name) - return dct - - def names_dicts(self, search_global): - yield self.names_dict - - def get_defined_names(self): - return _defined_names(self.children[1]) - - def nodes_to_execute(self, last_added=False): - last = self.children[-1] - if last.type == 'comp_if': - for node in last.children[-1].nodes_to_execute(): - yield node - last = self.children[-2] - elif last.type == 'comp_for': - for node in last.nodes_to_execute(): - yield node - last = self.children[-2] - for node in last.nodes_to_execute(): - yield node diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/utils.py b/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/utils.py deleted file mode 100644 index 9098b09..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/parser/utils.py +++ /dev/null @@ -1,198 +0,0 @@ -import inspect -import time -import os -import sys -import json -import hashlib -import gc -import shutil -import pickle - -from jedi import settings -from jedi import debug - - -def underscore_memoization(func): - """ - Decorator for methods:: - - class A(object): - def x(self): - if self._x: - self._x = 10 - return self._x - - Becomes:: - - class A(object): - @underscore_memoization - def x(self): - return 10 - - A now has an attribute ``_x`` written by this decorator. - """ - name = '_' + func.__name__ - - def wrapper(self): - try: - return getattr(self, name) - except AttributeError: - result = func(self) - if inspect.isgenerator(result): - result = list(result) - setattr(self, name, result) - return result - - return wrapper - - -# for fast_parser, should not be deleted -parser_cache = {} - - -class ParserCacheItem(object): - def __init__(self, parser, change_time=None): - self.parser = parser - if change_time is None: - change_time = time.time() - self.change_time = change_time - - -def load_parser(path): - """ - Returns the module or None, if it fails. - """ - p_time = os.path.getmtime(path) if path else None - try: - parser_cache_item = parser_cache[path] - if not path or p_time <= parser_cache_item.change_time: - return parser_cache_item.parser - except KeyError: - if settings.use_filesystem_cache: - return ParserPickling.load_parser(path, p_time) - - -def save_parser(path, parser, pickling=True): - try: - p_time = None if path is None else os.path.getmtime(path) - except OSError: - p_time = None - pickling = False - - item = ParserCacheItem(parser, p_time) - parser_cache[path] = item - if settings.use_filesystem_cache and pickling: - ParserPickling.save_parser(path, item) - - -class ParserPickling(object): - - version = 26 - """ - Version number (integer) for file system cache. - - Increment this number when there are any incompatible changes in - parser representation classes. For example, the following changes - are regarded as incompatible. - - - Class name is changed. - - Class is moved to another module. - - Defined slot of the class is changed. - """ - - def __init__(self): - self.__index = None - self.py_tag = 'cpython-%s%s' % sys.version_info[:2] - """ - Short name for distinguish Python implementations and versions. - - It's like `sys.implementation.cache_tag` but for Python < 3.3 - we generate something similar. See: - http://docs.python.org/3/library/sys.html#sys.implementation - - .. todo:: Detect interpreter (e.g., PyPy). - """ - - def load_parser(self, path, original_changed_time): - try: - pickle_changed_time = self._index[path] - except KeyError: - return None - if original_changed_time is not None \ - and pickle_changed_time < original_changed_time: - # the pickle file is outdated - return None - - with open(self._get_hashed_path(path), 'rb') as f: - try: - gc.disable() - parser_cache_item = pickle.load(f) - finally: - gc.enable() - - debug.dbg('pickle loaded: %s', path) - parser_cache[path] = parser_cache_item - return parser_cache_item.parser - - def save_parser(self, path, parser_cache_item): - self.__index = None - try: - files = self._index - except KeyError: - files = {} - self._index = files - - with open(self._get_hashed_path(path), 'wb') as f: - pickle.dump(parser_cache_item, f, pickle.HIGHEST_PROTOCOL) - files[path] = parser_cache_item.change_time - - self._flush_index() - - @property - def _index(self): - if self.__index is None: - try: - with open(self._get_path('index.json')) as f: - data = json.load(f) - except (IOError, ValueError): - self.__index = {} - else: - # 0 means version is not defined (= always delete cache): - if data.get('version', 0) != self.version: - self.clear_cache() - else: - self.__index = data['index'] - return self.__index - - def _remove_old_modules(self): - # TODO use - change = False - if change: - self._flush_index(self) - self._index # reload index - - def _flush_index(self): - data = {'version': self.version, 'index': self._index} - with open(self._get_path('index.json'), 'w') as f: - json.dump(data, f) - self.__index = None - - def clear_cache(self): - shutil.rmtree(self._cache_directory()) - self.__index = {} - - def _get_hashed_path(self, path): - return self._get_path('%s.pkl' % hashlib.md5(path.encode("utf-8")).hexdigest()) - - def _get_path(self, file): - dir = self._cache_directory() - if not os.path.exists(dir): - os.makedirs(dir) - return os.path.join(dir, file) - - def _cache_directory(self): - return os.path.join(settings.cache_directory, self.py_tag) - - -# is a singleton -ParserPickling = ParserPickling() diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/refactoring.py b/vim-plugins/bundle/jedi-vim/jedi/jedi/refactoring.py deleted file mode 100644 index a342f08..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/refactoring.py +++ /dev/null @@ -1,202 +0,0 @@ -""" -Introduce some basic refactoring functions to |jedi|. This module is still in a -very early development stage and needs much testing and improvement. - -.. warning:: I won't do too much here, but if anyone wants to step in, please - do. Refactoring is none of my priorities - -It uses the |jedi| `API `_ and supports currently the -following functions (sometimes bug-prone): - -- rename -- extract variable -- inline variable -""" -import difflib - -from jedi import common -from jedi.evaluate import helpers -from jedi.parser import tree as pt - - -class Refactoring(object): - def __init__(self, change_dct): - """ - :param change_dct: dict(old_path=(new_path, old_lines, new_lines)) - """ - self.change_dct = change_dct - - def old_files(self): - dct = {} - for old_path, (new_path, old_l, new_l) in self.change_dct.items(): - dct[new_path] = '\n'.join(new_l) - return dct - - def new_files(self): - dct = {} - for old_path, (new_path, old_l, new_l) in self.change_dct.items(): - dct[new_path] = '\n'.join(new_l) - return dct - - def diff(self): - texts = [] - for old_path, (new_path, old_l, new_l) in self.change_dct.items(): - if old_path: - udiff = difflib.unified_diff(old_l, new_l) - else: - udiff = difflib.unified_diff(old_l, new_l, old_path, new_path) - texts.append('\n'.join(udiff)) - return '\n'.join(texts) - - -def rename(script, new_name): - """ The `args` / `kwargs` params are the same as in `api.Script`. - :param operation: The refactoring operation to execute. - :type operation: str - :type source: str - :return: list of changed lines/changed files - """ - return Refactoring(_rename(script.usages(), new_name)) - - -def _rename(names, replace_str): - """ For both rename and inline. """ - order = sorted(names, key=lambda x: (x.module_path, x.line, x.column), - reverse=True) - - def process(path, old_lines, new_lines): - if new_lines is not None: # goto next file, save last - dct[path] = path, old_lines, new_lines - - dct = {} - current_path = object() - new_lines = old_lines = None - for name in order: - if name.in_builtin_module(): - continue - if current_path != name.module_path: - current_path = name.module_path - - process(current_path, old_lines, new_lines) - if current_path is not None: - # None means take the source that is a normal param. - with open(current_path) as f: - source = f.read() - - new_lines = common.splitlines(common.source_to_unicode(source)) - old_lines = new_lines[:] - - nr, indent = name.line, name.column - line = new_lines[nr - 1] - new_lines[nr - 1] = line[:indent] + replace_str + \ - line[indent + len(name.name):] - process(current_path, old_lines, new_lines) - return dct - - -def extract(script, new_name): - """ The `args` / `kwargs` params are the same as in `api.Script`. - :param operation: The refactoring operation to execute. - :type operation: str - :type source: str - :return: list of changed lines/changed files - """ - new_lines = common.splitlines(common.source_to_unicode(script.source)) - old_lines = new_lines[:] - - user_stmt = script._parser.user_stmt() - - # TODO care for multiline extracts - dct = {} - if user_stmt: - pos = script._pos - line_index = pos[0] - 1 - arr, index = helpers.array_for_pos(user_stmt, pos) - if arr is not None: - start_pos = arr[index].start_pos - end_pos = arr[index].end_pos - - # take full line if the start line is different from end line - e = end_pos[1] if end_pos[0] == start_pos[0] else None - start_line = new_lines[start_pos[0] - 1] - text = start_line[start_pos[1]:e] - for l in range(start_pos[0], end_pos[0] - 1): - text += '\n' + l - if e is None: - end_line = new_lines[end_pos[0] - 1] - text += '\n' + end_line[:end_pos[1]] - - # remove code from new lines - t = text.lstrip() - del_start = start_pos[1] + len(text) - len(t) - - text = t.rstrip() - del_end = len(t) - len(text) - if e is None: - new_lines[end_pos[0] - 1] = end_line[end_pos[1] - del_end:] - e = len(start_line) - else: - e = e - del_end - start_line = start_line[:del_start] + new_name + start_line[e:] - new_lines[start_pos[0] - 1] = start_line - new_lines[start_pos[0]:end_pos[0] - 1] = [] - - # add parentheses in multiline case - open_brackets = ['(', '[', '{'] - close_brackets = [')', ']', '}'] - if '\n' in text and not (text[0] in open_brackets and text[-1] == - close_brackets[open_brackets.index(text[0])]): - text = '(%s)' % text - - # add new line before statement - indent = user_stmt.start_pos[1] - new = "%s%s = %s" % (' ' * indent, new_name, text) - new_lines.insert(line_index, new) - dct[script.path] = script.path, old_lines, new_lines - return Refactoring(dct) - - -def inline(script): - """ - :type script: api.Script - """ - new_lines = common.splitlines(common.source_to_unicode(script.source)) - - dct = {} - - definitions = script.goto_assignments() - with common.ignored(AssertionError): - assert len(definitions) == 1 - stmt = definitions[0]._definition - usages = script.usages() - inlines = [r for r in usages - if not stmt.start_pos <= (r.line, r.column) <= stmt.end_pos] - inlines = sorted(inlines, key=lambda x: (x.module_path, x.line, x.column), - reverse=True) - expression_list = stmt.expression_list() - # don't allow multiline refactorings for now. - assert stmt.start_pos[0] == stmt.end_pos[0] - index = stmt.start_pos[0] - 1 - - line = new_lines[index] - replace_str = line[expression_list[0].start_pos[1]:stmt.end_pos[1] + 1] - replace_str = replace_str.strip() - # tuples need parentheses - if expression_list and isinstance(expression_list[0], pr.Array): - arr = expression_list[0] - if replace_str[0] not in ['(', '[', '{'] and len(arr) > 1: - replace_str = '(%s)' % replace_str - - # if it's the only assignment, remove the statement - if len(stmt.get_defined_names()) == 1: - line = line[:stmt.start_pos[1]] + line[stmt.end_pos[1]:] - - dct = _rename(inlines, replace_str) - # remove the empty line - new_lines = dct[script.path][2] - if line.strip(): - new_lines[index] = line - else: - new_lines.pop(index) - - return Refactoring(dct) diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/settings.py b/vim-plugins/bundle/jedi-vim/jedi/jedi/settings.py deleted file mode 100644 index 13dcfd4..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/settings.py +++ /dev/null @@ -1,233 +0,0 @@ -""" -This module contains variables with global |jedi| settings. To change the -behavior of |jedi|, change the variables defined in :mod:`jedi.settings`. - -Plugins should expose an interface so that the user can adjust the -configuration. - - -Example usage:: - - from jedi import settings - settings.case_insensitive_completion = True - - -Completion output -~~~~~~~~~~~~~~~~~ - -.. autodata:: case_insensitive_completion -.. autodata:: add_dot_after_module -.. autodata:: add_bracket_after_function -.. autodata:: no_completion_duplicates - - -Filesystem cache -~~~~~~~~~~~~~~~~ - -.. autodata:: cache_directory -.. autodata:: use_filesystem_cache - - -Parser -~~~~~~ - -.. autodata:: fast_parser - - -Dynamic stuff -~~~~~~~~~~~~~ - -.. autodata:: dynamic_array_additions -.. autodata:: dynamic_params -.. autodata:: dynamic_params_for_other_modules -.. autodata:: additional_dynamic_modules -.. autodata:: auto_import_modules - - -.. _settings-recursion: - -Recursions -~~~~~~~~~~ - -Recursion settings are important if you don't want extremly -recursive python code to go absolutely crazy. First of there is a -global limit :data:`max_executions`. This limit is important, to set -a maximum amount of time, the completion may use. - -The default values are based on experiments while completing the |jedi| library -itself (inception!). But I don't think there's any other Python library that -uses recursion in a similarly extreme way. These settings make the completion -definitely worse in some cases. But a completion should also be fast. - -.. autodata:: max_until_execution_unique -.. autodata:: max_function_recursion_level -.. autodata:: max_executions_without_builtins -.. autodata:: max_executions -.. autodata:: max_dynamic_params_depth -.. autodata:: scale_call_signatures - - -Caching -~~~~~~~ - -.. autodata:: star_import_cache_validity -.. autodata:: call_signatures_validity - - -""" -import os -import platform - -# ---------------- -# completion output settings -# ---------------- - -case_insensitive_completion = True -""" -The completion is by default case insensitive. -""" - -add_bracket_after_function = False -""" -Adds an opening bracket after a function, because that's normal behaviour. -Removed it again, because in VIM that is not very practical. -""" - -no_completion_duplicates = True -""" -If set, completions with the same name don't appear in the output anymore, -but are in the `same_name_completions` attribute. -""" - -# ---------------- -# Filesystem cache -# ---------------- - -use_filesystem_cache = True -""" -Use filesystem cache to save once parsed files with pickle. -""" - -if platform.system().lower() == 'windows': - _cache_directory = os.path.join(os.getenv('APPDATA') or '~', 'Jedi', - 'Jedi') -elif platform.system().lower() == 'darwin': - _cache_directory = os.path.join('~', 'Library', 'Caches', 'Jedi') -else: - _cache_directory = os.path.join(os.getenv('XDG_CACHE_HOME') or '~/.cache', - 'jedi') -cache_directory = os.path.expanduser(_cache_directory) -""" -The path where all the caches can be found. - -On Linux, this defaults to ``~/.cache/jedi/``, on OS X to -``~/Library/Caches/Jedi/`` and on Windows to ``%APPDATA%\\Jedi\\Jedi\\``. -On Linux, if environment variable ``$XDG_CACHE_HOME`` is set, -``$XDG_CACHE_HOME/jedi`` is used instead of the default one. -""" - -# ---------------- -# parser -# ---------------- - -fast_parser = True -""" -Use the fast parser. This means that reparsing is only being done if -something has been changed e.g. to a function. If this happens, only the -function is being reparsed. -""" - -# ---------------- -# dynamic stuff -# ---------------- - -dynamic_array_additions = True -""" -check for `append`, etc. on arrays: [], {}, () as well as list/set calls. -""" - -dynamic_params = True -""" -A dynamic param completion, finds the callees of the function, which define -the params of a function. -""" - -dynamic_params_for_other_modules = True -""" -Do the same for other modules. -""" - -additional_dynamic_modules = [] -""" -Additional modules in which |jedi| checks if statements are to be found. This -is practical for IDEs, that want to administrate their modules themselves. -""" - -dynamic_flow_information = True -""" -Check for `isinstance` and other information to infer a type. -""" - -auto_import_modules = [ - 'hashlib', # setattr -] -""" -Modules that are not analyzed but imported, although they contain Python code. -This improves autocompletion for libraries that use ``setattr`` or -``globals()`` modifications a lot. -""" - -# ---------------- -# recursions -# ---------------- - -max_until_execution_unique = 50 -""" -This limit is probably the most important one, because if this limit is -exceeded, functions can only be one time executed. So new functions will be -executed, complex recursions with the same functions again and again, are -ignored. -""" - -max_function_recursion_level = 5 -""" -`max_function_recursion_level` is more about whether the recursions are -stopped in deepth or in width. The ratio beetween this and -`max_until_execution_unique` is important here. It stops a recursion (after -the number of function calls in the recursion), if it was already used -earlier. -""" - -max_executions_without_builtins = 200 -""" -.. todo:: Document this. -""" - -max_executions = 250 -""" -A maximum amount of time, the completion may use. -""" - -scale_call_signatures = 0.1 -""" -Because call_signatures is normally used on every single key hit, it has -to be faster than a normal completion. This is the factor that is used to -scale `max_executions` and `max_until_execution_unique`: -""" - -# ---------------- -# caching validity (time) -# ---------------- - -star_import_cache_validity = 60.0 -""" -In huge packages like numpy, checking all star imports on every completion -might be slow, therefore we do a star import caching, that lasts a certain -time span (in seconds). -""" - -call_signatures_validity = 3.0 -""" -Finding function calls might be slow (0.1-0.5s). This is not acceptible for -normal writing. Therefore cache it for a short time. -""" diff --git a/vim-plugins/bundle/jedi-vim/jedi/jedi/utils.py b/vim-plugins/bundle/jedi-vim/jedi/jedi/utils.py deleted file mode 100644 index 44f7c0d..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/jedi/utils.py +++ /dev/null @@ -1,131 +0,0 @@ -""" -Utilities for end-users. -""" - -from __future__ import absolute_import -import __main__ -from collections import namedtuple -import logging -import traceback -import re -import os -import sys - -from jedi import Interpreter -from jedi.api.helpers import get_on_completion_name -from jedi import common - - -READLINE_DEBUG = False - - -def setup_readline(namespace_module=__main__): - """ - Install Jedi completer to :mod:`readline`. - - This function setups :mod:`readline` to use Jedi in Python interactive - shell. If you want to use a custom ``PYTHONSTARTUP`` file (typically - ``$HOME/.pythonrc.py``), you can add this piece of code:: - - try: - from jedi.utils import setup_readline - setup_readline() - except ImportError: - # Fallback to the stdlib readline completer if it is installed. - # Taken from http://docs.python.org/2/library/rlcompleter.html - print("Jedi is not installed, falling back to readline") - try: - import readline - import rlcompleter - readline.parse_and_bind("tab: complete") - except ImportError: - print("Readline is not installed either. No tab completion is enabled.") - - This will fallback to the readline completer if Jedi is not installed. - The readline completer will only complete names in the global namespace, - so for example:: - - ran - - will complete to ``range`` - - with both Jedi and readline, but:: - - range(10).cou - - will show complete to ``range(10).count`` only with Jedi. - - You'll also need to add ``export PYTHONSTARTUP=$HOME/.pythonrc.py`` to - your shell profile (usually ``.bash_profile`` or ``.profile`` if you use - bash). - - """ - if READLINE_DEBUG: - logging.basicConfig( - filename='/tmp/jedi.log', - filemode='a', - level=logging.DEBUG - ) - - class JediRL(object): - def complete(self, text, state): - """ - This complete stuff is pretty weird, a generator would make - a lot more sense, but probably due to backwards compatibility - this is still the way how it works. - - The only important part is stuff in the ``state == 0`` flow, - everything else has been copied from the ``rlcompleter`` std. - library module. - """ - if state == 0: - sys.path.insert(0, os.getcwd()) - # Calling python doesn't have a path, so add to sys.path. - try: - logging.debug("Start REPL completion: " + repr(text)) - interpreter = Interpreter(text, [namespace_module.__dict__]) - - lines = common.splitlines(text) - position = (len(lines), len(lines[-1])) - name = get_on_completion_name(interpreter._get_module(), lines, position) - before = text[:len(text) - len(name)] - completions = interpreter.completions() - except: - logging.error("REPL Completion error:\n" + traceback.format_exc()) - raise - finally: - sys.path.pop(0) - - self.matches = [before + c.name_with_symbols for c in completions] - try: - return self.matches[state] - except IndexError: - return None - - try: - import readline - except ImportError: - print("Jedi: Module readline not available.") - else: - readline.set_completer(JediRL().complete) - readline.parse_and_bind("tab: complete") - # jedi itself does the case matching - readline.parse_and_bind("set completion-ignore-case on") - # because it's easier to hit the tab just once - readline.parse_and_bind("set show-all-if-unmodified") - readline.parse_and_bind("set show-all-if-ambiguous on") - # don't repeat all the things written in the readline all the time - readline.parse_and_bind("set completion-prefix-display-length 2") - # No delimiters, Jedi handles that. - readline.set_completer_delims('') - - -def version_info(): - """ - Returns a namedtuple of Jedi's version, similar to Python's - ``sys.version_info``. - """ - Version = namedtuple('Version', 'major, minor, micro') - from jedi import __version__ - tupl = re.findall('[a-z]+|\d+', __version__) - return Version(*[x if i == 3 else int(x) for i, x in enumerate(tupl)]) diff --git a/vim-plugins/bundle/jedi-vim/jedi/pytest.ini b/vim-plugins/bundle/jedi-vim/jedi/pytest.ini deleted file mode 100644 index 6fafa94..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/pytest.ini +++ /dev/null @@ -1,10 +0,0 @@ -[pytest] -addopts = --doctest-modules - -# Ignore broken files in blackbox test directories -norecursedirs = .* docs completion refactor absolute_import namespace_package scripts extensions speed static_analysis not_in_sys_path buildout_project sample_venvs init_extension_module - -# Activate `clean_jedi_cache` fixture for all tests. This should be -# fine as long as we are using `clean_jedi_cache` as a session scoped -# fixture. -usefixtures = clean_jedi_cache diff --git a/vim-plugins/bundle/jedi-vim/jedi/scripts/memory_check.py b/vim-plugins/bundle/jedi-vim/jedi/scripts/memory_check.py deleted file mode 100755 index 7bbcad2..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/scripts/memory_check.py +++ /dev/null @@ -1,58 +0,0 @@ -#! /usr/bin/env python -""" -This is a convenience script to test the speed and memory usage of Jedi with -large libraries. - -Each library is preloaded by jedi, recording the time and memory consumed by -each operation. - -You can provide additional libraries via command line arguments. - -Note: This requires the psutil library, available on PyPI. -""" -import time -import sys -import os -import psutil -sys.path.insert(0, os.path.abspath(os.path.dirname(__file__) + '/..')) -import jedi - - -def used_memory(): - """Return the total MB of System Memory in use.""" - return psutil.virtual_memory().used / 2 ** 20 - - -def profile_preload(mod): - """Preload a module into Jedi, recording time and memory used.""" - base = used_memory() - t0 = time.time() - jedi.preload_module(mod) - elapsed = time.time() - t0 - used = used_memory() - base - return elapsed, used - - -def main(mods): - """Preload the modules, and print the time and memory used.""" - t0 = time.time() - baseline = used_memory() - print('Time (s) | Mem (MB) | Package') - print('------------------------------') - for mod in mods: - elapsed, used = profile_preload(mod) - if used > 0: - print('%8.2f | %8d | %s' % (elapsed, used, mod)) - print('------------------------------') - elapsed = time.time() - t0 - used = used_memory() - baseline - print('%8.2f | %8d | %s' % (elapsed, used, 'Total')) - - -if __name__ == '__main__': - if sys.argv[1:]: - mods = sys.argv[1:] - else: - mods = ['re', 'numpy', 'scipy', 'scipy.sparse', 'scipy.stats', - 'wx', 'decimal', 'PyQt4.QtGui', 'PySide.QtGui', 'Tkinter'] - main(mods) diff --git a/vim-plugins/bundle/jedi-vim/jedi/scripts/profile.py b/vim-plugins/bundle/jedi-vim/jedi/scripts/profile.py deleted file mode 100755 index 44028b0..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/scripts/profile.py +++ /dev/null @@ -1,49 +0,0 @@ -#!/usr/bin/env python -""" -Profile a piece of Python code with ``cProfile``. Tries a completion on a -certain piece of code. - -Usage: - profile.py [] [-n ] [-d] [-o] [-s ] - profile.py -h | --help - -Options: - -h --help Show this screen. - -n Number of passes before profiling [default: 1]. - -d --debug Enable Jedi internal debugging. - -o --omit Omit profiler, just do a normal run. - -s Sort the profile results, e.g. cum, name [default: time]. -""" - -import time -import cProfile - -from docopt import docopt -import jedi - - -def run(code, index): - start = time.time() - result = jedi.Script(code).completions() - print('Used %ss for the %sth run.' % (time.time() - start, index + 1)) - return result - - -def main(args): - code = args[''] - n = int(args['-n']) - for i in range(n): - run(code, i) - - jedi.set_debug_function(notices=args['--debug']) - if args['--omit']: - run(code, n) - else: - cProfile.runctx('run(code, n)', globals(), locals(), sort=args['-s']) - - -if __name__ == '__main__': - args = docopt(__doc__) - if args[''] is None: - args[''] = 'import numpy; numpy.array([0])' - main(args) diff --git a/vim-plugins/bundle/jedi-vim/jedi/scripts/wx_check.py b/vim-plugins/bundle/jedi-vim/jedi/scripts/wx_check.py deleted file mode 100755 index 1e48c39..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/scripts/wx_check.py +++ /dev/null @@ -1,61 +0,0 @@ -#! /usr/bin/env python -""" -Depends: ``objgraph`` (third party Python library) - -``wx._core`` is a very nice module to test Jedi's speed and memory performance -on big Python modules. Its size is ~16kLOC (one file). It also seems to look -like a typical big Python modules. A mix between a lot of different Python -things. - -You can view a markup version of it here: -http://svn.wxwidgets.org/viewvc/wx/wxPython/trunk/src/gtk/_core.py?view=markup -""" - -import resource -import time -import sys -try: - import urllib.request as urllib2 -except ImportError: - import urllib2 -import gc -from os.path import abspath, dirname - -import objgraph - -sys.path.insert(0, dirname(dirname(abspath(__file__)))) -import jedi - - -def process_memory(): - """ - In kB according to - http://stackoverflow.com/questions/938733/total-memory-used-by-python-process - """ - return resource.getrusage(resource.RUSAGE_SELF).ru_maxrss - -uri = 'http://svn.wxwidgets.org/viewvc/wx/wxPython/trunk/src/gtk/_core.py?revision=74740&content-type=text%2Fplain&view=co' - -wx_core = urllib2.urlopen(uri).read() - - -def run(): - start = time.time() - print('Process Memory before: %skB' % process_memory()) - # After this the module should be cached. - # Need to invent a path so that it's really cached. - jedi.Script(wx_core, path='foobar.py').completions() - - gc.collect() # make sure that it's all fair and the gc did its job. - print('Process Memory after: %skB' % process_memory()) - - print(objgraph.most_common_types(limit=50)) - print('\nIt took %s seconds to parse the file.' % (time.time() - start)) - - -print('First pass') -run() -print('\nSecond pass') -run() -print('\nThird pass') -run() diff --git a/vim-plugins/bundle/jedi-vim/jedi/setup.py b/vim-plugins/bundle/jedi-vim/jedi/setup.py deleted file mode 100755 index 89ff880..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/setup.py +++ /dev/null @@ -1,50 +0,0 @@ -#!/usr/bin/env python - -from __future__ import with_statement -try: - from setuptools import setup -except ImportError: - # Distribute is not actually required to install - from distutils.core import setup - -__AUTHOR__ = 'David Halter' -__AUTHOR_EMAIL__ = 'davidhalter88@gmail.com' - -readme = open('README.rst').read() + '\n\n' + open('CHANGELOG.rst').read() -packages = ['jedi', 'jedi.parser', 'jedi.parser.pgen2', - 'jedi.evaluate', 'jedi.evaluate.compiled', 'jedi.api'] - -import jedi - -setup(name='jedi', - version=jedi.__version__, - description='An autocompletion tool for Python that can be used for text editors.', - author=__AUTHOR__, - author_email=__AUTHOR_EMAIL__, - maintainer=__AUTHOR__, - maintainer_email=__AUTHOR_EMAIL__, - url='https://github.com/davidhalter/jedi', - license='MIT', - keywords='python completion refactoring vim', - long_description=readme, - packages=packages, - package_data={'jedi': ['evaluate/compiled/fake/*.pym', 'parser/grammar*.txt']}, - platforms=['any'], - classifiers=[ - 'Development Status :: 4 - Beta', - 'Environment :: Plugins', - 'Intended Audience :: Developers', - 'License :: OSI Approved :: MIT License', - 'Operating System :: OS Independent', - 'Programming Language :: Python :: 2', - 'Programming Language :: Python :: 2.6', - 'Programming Language :: Python :: 2.7', - 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.3', - 'Programming Language :: Python :: 3.4', - 'Programming Language :: Python :: 3.5', - 'Topic :: Software Development :: Libraries :: Python Modules', - 'Topic :: Text Editors :: Integrated Development Environments (IDE)', - 'Topic :: Utilities', - ], - ) diff --git a/vim-plugins/bundle/jedi-vim/jedi/sith.py b/vim-plugins/bundle/jedi-vim/jedi/sith.py deleted file mode 100755 index 903ef0e..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/sith.py +++ /dev/null @@ -1,220 +0,0 @@ -#!/usr/bin/env python - -""" -Sith attacks (and helps debugging) Jedi. - -Randomly search Python files and run Jedi on it. Exception and used -arguments are recorded to ``./record.json`` (specified by --record):: - - ./sith.py random /path/to/sourcecode - -Redo recorded exception:: - - ./sith.py redo - -Show recorded exception:: - - ./sith.py show - -Run a specific operation - - ./sith.py run - -Where operation is one of completions, goto_assignments, goto_definitions, -usages, or call_signatures. - -Note: Line numbers start at 1; columns start at 0 (this is consistent with -many text editors, including Emacs). - -Usage: - sith.py [--pdb|--ipdb|--pudb] [-d] [-n=] [-f] [--record=] random [-s] [] - sith.py [--pdb|--ipdb|--pudb] [-d] [-f] [--record=] redo - sith.py [--pdb|--ipdb|--pudb] [-d] [-f] run - sith.py show [--record=] - sith.py -h | --help - -Options: - -h --help Show this screen. - --record= Exceptions are recorded in here [default: record.json]. - -f, --fs-cache By default, file system cache is off for reproducibility. - -n, --maxtries= Maximum of random tries [default: 100] - -d, --debug Jedi print debugging when an error is raised. - -s Shows the path/line numbers of every completion before it starts. - --pdb Launch pdb when error is raised. - --ipdb Launch ipdb when error is raised. - --pudb Launch pudb when error is raised. -""" - -from __future__ import print_function, division, unicode_literals -from docopt import docopt - -import json -import os -import random -import sys -import traceback - -import jedi - - -class SourceFinder(object): - _files = None - - @staticmethod - def fetch(file_path): - if not os.path.isdir(file_path): - yield file_path - return - for root, dirnames, filenames in os.walk(file_path): - for name in filenames: - if name.endswith('.py'): - yield os.path.join(root, name) - - @classmethod - def files(cls, file_path): - if cls._files is None: - cls._files = list(cls.fetch(file_path)) - return cls._files - - -class TestCase(object): - def __init__(self, operation, path, line, column, traceback=None): - if operation not in self.operations: - raise ValueError("%s is not a valid operation" % operation) - - # Set other attributes - self.operation = operation - self.path = path - self.line = line - self.column = column - self.traceback = traceback - - @classmethod - def from_cache(cls, record): - with open(record) as f: - args = json.load(f) - return cls(*args) - - operations = [ - 'completions', 'goto_assignments', 'goto_definitions', 'usages', - 'call_signatures'] - - @classmethod - def generate(cls, file_path): - operation = random.choice(cls.operations) - - path = random.choice(SourceFinder.files(file_path)) - with open(path) as f: - source = f.read() - lines = source.splitlines() - - if not lines: - lines = [''] - line = random.randint(1, len(lines)) - column = random.randint(0, len(lines[line - 1])) - return cls(operation, path, line, column) - - def run(self, debugger, record=None, print_result=False): - try: - with open(self.path) as f: - self.script = jedi.Script(f.read(), self.line, self.column, self.path) - kwargs = {} - if self.operation == 'goto_assignments': - kwargs['follow_imports'] = random.choice([False, True]) - - self.objects = getattr(self.script, self.operation)(**kwargs) - if print_result: - print("{path}: Line {line} column {column}".format(**self.__dict__)) - self.show_location(self.line, self.column) - self.show_operation() - except jedi.NotFoundError: - pass - except Exception: - self.traceback = traceback.format_exc() - if record is not None: - call_args = (self.operation, self.path, self.line, self.column, self.traceback) - with open(record, 'w') as f: - json.dump(call_args, f) - self.show_errors() - if debugger: - einfo = sys.exc_info() - pdb = __import__(debugger) - if debugger == 'pudb': - pdb.post_mortem(einfo[2], einfo[0], einfo[1]) - else: - pdb.post_mortem(einfo[2]) - exit(1) - - def show_location(self, lineno, column, show=3): - # Three lines ought to be enough - lower = lineno - show if lineno - show > 0 else 0 - prefix = ' |' - for i, line in enumerate(self.script.source.split('\n')[lower:lineno]): - print(prefix, lower + i + 1, line) - print(prefix, ' ', ' ' * (column + len(str(lineno))), '^') - - def show_operation(self): - print("%s:\n" % self.operation.capitalize()) - if self.operation == 'completions': - self.show_completions() - else: - self.show_definitions() - - def show_completions(self): - for completion in self.objects: - print(completion.name) - - def show_definitions(self): - for completion in self.objects: - print(completion.desc_with_module) - if completion.module_path is None: - continue - if os.path.abspath(completion.module_path) == os.path.abspath(self.path): - self.show_location(completion.line, completion.column) - - def show_errors(self): - print(self.traceback) - print(("Error with running Script(...).{operation}() with\n" - "\tpath: {path}\n" - "\tline: {line}\n" - "\tcolumn: {column}").format(**self.__dict__)) - - -def main(arguments): - debugger = 'pdb' if arguments['--pdb'] else \ - 'ipdb' if arguments['--ipdb'] else \ - 'pudb' if arguments['--pudb'] else None - record = arguments['--record'] - - jedi.settings.use_filesystem_cache = arguments['--fs-cache'] - if arguments['--debug']: - jedi.set_debug_function() - - if arguments['redo'] or arguments['show']: - t = TestCase.from_cache(record) - if arguments['show']: - t.show_errors() - else: - t.run(debugger) - elif arguments['run']: - TestCase( - arguments[''], arguments[''], - int(arguments['']), int(arguments['']) - ).run(debugger, print_result=True) - else: - for _ in range(int(arguments['--maxtries'])): - t = TestCase.generate(arguments[''] or '.') - if arguments['-s']: - print('%s %s %s %s ' % (t.operation, t.path, t.line, t.column)) - sys.stdout.flush() - else: - print('.', end='') - t.run(debugger, record) - - sys.stdout.flush() - print() - - -if __name__ == '__main__': - arguments = docopt(__doc__) - main(arguments) diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/__init__.py b/vim-plugins/bundle/jedi-vim/jedi/test/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/blabla_test_documentation.py b/vim-plugins/bundle/jedi-vim/jedi/test/blabla_test_documentation.py deleted file mode 100644 index db31bf0..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/blabla_test_documentation.py +++ /dev/null @@ -1,30 +0,0 @@ -# todo probably remove test_integration_keyword - -def test_keyword_doc(): - r = list(Script("or", 1, 1).goto_definitions()) - assert len(r) == 1 - assert len(r[0].doc) > 100 - - r = list(Script("asfdasfd", 1, 1).goto_definitions()) - assert len(r) == 0 - - k = Script("fro").completions()[0] - imp_start = '\nThe ``import' - assert k.raw_doc.startswith(imp_start) - assert k.doc.startswith(imp_start) - - -def test_blablabla(): - defs = Script("import").goto_definitions() - assert len(defs) == 1 and [1 for d in defs if d.doc] - # unrelated to #44 - - -def test_operator_doc(self): - r = list(Script("a == b", 1, 3).goto_definitions()) - assert len(r) == 1 - assert len(r[0].doc) > 100 - -def test_lambda(): - defs = Script('lambda x: x', column=0).goto_definitions() - assert [d.type for d in defs] == ['keyword'] diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/completion/__init__.py b/vim-plugins/bundle/jedi-vim/jedi/test/completion/__init__.py deleted file mode 100644 index 374dd94..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/completion/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -""" needed for some modules to test against packages. """ - -some_variable = 1 diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/completion/arrays.py b/vim-plugins/bundle/jedi-vim/jedi/test/completion/arrays.py deleted file mode 100644 index dcbbe37..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/completion/arrays.py +++ /dev/null @@ -1,430 +0,0 @@ -# ----------------- -# basic array lookups -# ----------------- - - -#? int() -[1,""][0] -#? str() -[1,""][1] -#? int() str() -[1,""][2] -#? int() str() -[1,""][20] -#? int() str() -[1,""][str(hello)] - -a = list() -#? list() -[a][0] - -#? list() -[[a,a,a]][2][100] - -c = [[a,""]] -#? str() -c[0][1] - -b = [6,7] - -#? int() -b[8-7] - -# ----------------- -# Slices -# ----------------- -#? list() -b[8:] - -#? list() -b[int():] - -#? list() -b[:] - - -class _StrangeSlice(): - def __getitem__(self, sliced): - return sliced - -# Should not result in an error, just because the slice itself is returned. -#? slice() -_StrangeSlice()[1:2] - - -# ----------------- -# iterable multiplication -# ----------------- -a = ['']*2 -#? list() -a - -# ----------------- -# tuple assignments -# ----------------- -a1, b1 = (1, "") -#? int() -a1 -#? str() -b1 - -(a2, b2) = (1, "") -#? int() -a2 -#? str() -b2 - -# list assignment -[list1, list2] = (1, "") -#? int() -list1 -#? str() -list2 - -[list3, list4] = [1, ""] -#? int() -list3 -#? str() -list4 - -# ----------------- -# subtuple assignment -# ----------------- -(a3, (b3, c3)) = (1, ("", list)) -#? list -c3 - -a4, (b4, c4) = (1, ("", list)) -#? list -c4 -#? int() -a4 -#? str() -b4 - - -# ----------------- -# multiple assignments -# ----------------- -a = b = 1 -#? int() -a -#? int() -b - -(a, b) = (c, (e, f)) = ('2', (3, 4)) -#? str() -a -#? tuple() -b -#? str() -c -#? int() -e -#? int() -f - - -# ----------------- -# unnessecary braces -# ----------------- -a = (1) -#? int() -a -#? int() -(1) -#? int() -((1)) -#? int() -((1)+1) - -u, v = 1, "" -#? int() -u - -((u1, v1)) = 1, "" -#? int() -u1 -#? int() -(u1) - -(a), b = 1, '' -#? int() -a - -def a(): return '' -#? str() -(a)() -#? str() -(a)().replace() -#? int() -(tuple).index() -#? int() -(tuple)().index() - -class C(): - def __init__(self): - self.a = (str()).upper() - -#? str() -C().a - -# ----------------- -# imbalanced sides -# ----------------- -(f, g) = (1,) -#? int() -f -#? [] -g. - -(f, g, h) = (1,'') -#? int() -f -#? str() -g -#? [] -h. - -(f1, g1) = 1 -#? [] -f1. -#? [] -g1. - -(f, g) = (1,'',1.0) -#? int() -f -#? str() -g - -# ----------------- -# dicts -# ----------------- -dic2 = {'asdf': 3, 'b': 'str'} -#? int() -dic2['asdf'] - -# string literal -#? int() -dic2[r'asdf'] -#? int() -dic2[r'asdf'] -#? int() -dic2[r'as' 'd' u'f'] -#? int() str() -dic2['just_something'] - -# unpacking -a, b = dic2 -#? str() -a -a, b = {1: 'x', 2.0: 1j} -#? int() float() -a -#? int() float() -b - - -def f(): - """ github #83 """ - r = {} - r['status'] = (200, 'ok') - return r - -#? dict() -f() - -# completion within dicts -#? 9 ['str'] -{str: str} - -# iteration problem (detected with sith) -d = dict({'a':''}) -def y(a): - return a -#? -y(**d) - -# problem with more complicated casts -dic = {str(key): ''} -#? str() -dic[''] - - -for x in {1: 3.0, '': 1j}: - #? int() str() - x - -# ----------------- -# with variable as index -# ----------------- -a = (1, "") -index = 1 -#? str() -a[index] - -# these should just ouput the whole array -index = int -#? int() str() -a[index] -index = int() -#? int() str() -a[index] - -# dicts -index = 'asdf' - -dic2 = {'asdf': 3, 'b': 'str'} -#? int() -dic2[index] - -# ----------------- -# __getitem__ -# ----------------- - -class GetItem(): - def __getitem__(self, index): - return 1.0 - -#? float() -GetItem()[0] - -class GetItem(): - def __init__(self, el): - self.el = el - - def __getitem__(self, index): - return self.el - -#? str() -GetItem("")[1] - -class GetItemWithList(): - def __getitem__(self, index): - return [1, 1.0, 's'][index] - -#? float() -GetItemWithList()[1] - -for i in 0, 2: - #? int() str() - GetItemWithList()[i] - - -# With super -class SuperYeah(list): - def __getitem__(self, index): - return super()[index] - -#? -SuperYeah([1])[0] -#? -SuperYeah()[0] - -# ----------------- -# conversions -# ----------------- - -a = [1, ""] -#? int() str() -list(a)[1] - -#? int() str() -list(a)[0] -#? -set(a)[0] - -#? int() str() -list(set(a))[1] -#? int() str() -list(list(set(a)))[1] - -# does not yet work, because the recursion catching is not good enough (catches # to much) -#? int() str() -list(set(list(set(a))))[1] -#? int() str() -list(set(set(a)))[1] - -# frozenset -#? int() str() -list(frozenset(a))[1] -#? int() str() -list(set(frozenset(a)))[1] - -# iter -#? int() str() -list(iter(a))[1] -#? int() str() -list(iter(list(set(a))))[1] - -# tuple -#? int() str() -tuple(a)[1] -#? int() str() -tuple(list(set(a)))[1] - -#? int() -tuple({1})[0] -#? int() -tuple((1,))[0] - -# implementation detail for lists, should not be visible -#? [] -list().__iterable - -# With a list comprehension. -for i in set(a for a in [1]): - #? int() - i - - -# ----------------- -# Merged Arrays -# ----------------- - -for x in [1] + ['']: - #? int() str() - x - -# ----------------- -# For loops with attribute assignment. -# ----------------- -def test_func(): - x = 'asdf' - for x.something in [6,7,8]: - pass - #? str() - x - - for x.something, b in [[6, 6.0]]: - pass - #? str() - x - - -# ----------------- -# PEP 3132 Extended Iterable Unpacking (star unpacking) -# ----------------- - -a, *b, c = [1, 'b', list, dict] -#? int() -a -#? str() -b -#? list -c - -# Not valid syntax -a, *b, *c = [1, 'd', list] -#? int() -a -#? str() -b -#? list -c - -lc = [x for a, *x in [(1, '', 1.0)]] - -#? -lc[0][0] diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/completion/basic.py b/vim-plugins/bundle/jedi-vim/jedi/test/completion/basic.py deleted file mode 100644 index 5b4f909..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/completion/basic.py +++ /dev/null @@ -1,293 +0,0 @@ -# ----------------- -# cursor position -# ----------------- -#? 0 int -int() -#? 3 int -int() -#? 4 str -int(str) - - -# ----------------- -# should not complete -# ----------------- -#? [] -. -#? [] -str.. -#? [] -a(0):. - -# ----------------- -# if/else/elif -# ----------------- - -if (random.choice([0, 1])): - 1 -elif(random.choice([0, 1])): - a = 3 -else: - a = '' -#? int() str() -a -def func(): - if random.choice([0, 1]): - 1 - elif(random.choice([0, 1])): - a = 3 - else: - a = '' - #? int() str() - return a -#? int() str() -func() - -# ----------------- -# keywords -# ----------------- - -#? list() -assert [] - -def focus_return(): - #? list() - return [] - - -# ----------------- -# for loops -# ----------------- - -for a in [1,2]: - #? int() - a - -for a1 in 1,"": - #? int() str() - a1 - -for a3, b3 in (1,""), (1,""), (1,""): - #? int() - a3 - #? str() - b3 - -for a4, (b4, c4) in (1,("", list)), (1,("", list)): - #? int() - a4 - #? str() - b4 - #? list - c4 - -a = [] -for i in [1,'']: - #? int() str() - i - a += [i] - -#? int() str() -a[0] - -for i in list([1,'']): - #? int() str() - i - -#? int() str() -for x in [1,'']: x - -a = [] -b = [1.0,''] -for i in b: - a += [i] - -#? float() str() -a[0] - -for i in [1,2,3]: - #? int() - i -else: - i - - -# ----------------- -# range() -# ----------------- -for i in range(10): - #? int() - i - -# ----------------- -# ternary operator -# ----------------- - -a = 3 -b = '' if a else set() -#? str() set() -b - -def ret(a): - return ['' if a else set()] - -#? str() set() -ret(1)[0] -#? str() set() -ret()[0] - -# ----------------- -# with statements -# ----------------- - -with open('') as f: - #? ['closed'] - f.closed - for line in f: - #? str() - line - -with open('') as f1, open('') as f2: - #? ['closed'] - f1.closed - #? ['closed'] - f2.closed - - -# ----------------- -# global vars -# ----------------- - -def global_define(): - global global_var_in_func - global_var_in_func = 3 - -#? int() -global_var_in_func - - -def funct1(): - # From issue #610 - global global_dict_var - global_dict_var = dict() -def funct2(): - global global_dict_var - #? dict() - global_dict_var - - -# ----------------- -# within docstrs -# ----------------- - -def a(): - """ - #? ['global_define'] - global_define - """ - pass - -#? -# str literals in comment """ upper - -def completion_in_comment(): - #? ['Exception'] - # might fail because the comment is not a leaf: Exception - pass - -some_word -#? ['Exception'] -# Very simple comment completion: Exception -# Commment after it - -# ----------------- -# magic methods -# ----------------- - -class A(object): pass -class B(): pass - -#? ['__init__'] -A.__init__ -#? ['__init__'] -B.__init__ - -#? ['__init__'] -int().__init__ - -# ----------------- -# comments -# ----------------- - -class A(): - def __init__(self): - self.hello = {} # comment shouldn't be a string -#? dict() -A().hello - -# ----------------- -# unicode -# ----------------- -a = 'smörbröd' -#? str() -a -xyz = 'smörbröd.py' -if 1: - #? str() - xyz - -#? -¹. - -# ----------------- -# exceptions -# ----------------- -try: - import math -except ImportError as i_a: - #? ['i_a'] - i_a - #? ImportError() - i_a -try: - import math -except ImportError, i_b: - # TODO check this only in Python2 - ##? ['i_b'] - i_b - ##? ImportError() - i_b - - -class MyException(Exception): - def __init__(self, my_attr): - self.my_attr = my_attr - -try: - raise MyException(1) -except MyException as e: - #? ['my_attr'] - e.my_attr - #? 22 ['my_attr'] - for x in e.my_attr: - pass - - -# ----------------- -# continuations -# ----------------- - -foo = \ -1 -#? int() -foo - -# ----------------- -# module attributes -# ----------------- - -# Don't move this to imports.py, because there's a star import. -#? str() -__file__ -#? ['__file__'] -__file__ diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/completion/classes.py b/vim-plugins/bundle/jedi-vim/jedi/test/completion/classes.py deleted file mode 100644 index 6aa226b..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/completion/classes.py +++ /dev/null @@ -1,470 +0,0 @@ -def find_class(): - """ This scope is special, because its in front of TestClass """ - #? ['ret'] - TestClass.ret - if 1: - #? ['ret'] - TestClass.ret - -class FindClass(): - #? [] - TestClass.ret - if a: - #? [] - TestClass.ret - - def find_class(self): - #? ['ret'] - TestClass.ret - if 1: - #? ['ret'] - TestClass.ret - -#? [] -FindClass().find_class.self -#? [] -FindClass().find_class.self.find_class - -# set variables, which should not be included, because they don't belong to the -# class -second = 1 -second = "" -class TestClass(object): - var_class = TestClass(1) - - def __init__(self2, first_param, second_param, third=1.0): - self2.var_inst = first_param - self2.second = second_param - self2.first = first_param - a = 3 - - def var_func(self): - return 1 - - def get_first(self): - # traversal - self.second_new = self.second - return self.var_inst - - def values(self): - self.var_local = 3 - #? ['var_class', 'var_func', 'var_inst', 'var_local'] - self.var_ - - def ret(self, a1): - # should not know any class functions! - #? [] - values - #? ['return'] - ret - return a1 - -# should not work -#? [] -var_local -#? [] -var_inst -#? [] -var_func - -# instance -inst = TestClass(1) - -#? ['var_class', 'var_func', 'var_inst', 'var_local'] -inst.var - -#? ['var_class', 'var_func'] -TestClass.var - -#? int() -inst.var_local -#? [] -TestClass.var_local. - -#? int() -TestClass().ret(1) -# Should not return int(), because we want the type before `.ret(1)`. -#? 11 TestClass() -TestClass().ret(1) -#? int() -inst.ret(1) - -myclass = TestClass(1, '', 3.0) -#? int() -myclass.get_first() -#? [] -myclass.get_first.real - -# too many params -#? int() -TestClass(1,1,1).var_inst - -# too few params -#? int() -TestClass(1).first -#? [] -TestClass(1).second. - -# complicated variable settings in class -#? str() -myclass.second -#? str() -myclass.second_new - -# multiple classes / ordering -ints = TestClass(1, 1.0) -strs = TestClass("", '') -#? float() -ints.second -#? str() -strs.second - -#? ['var_class'] -TestClass.var_class.var_class.var_class.var_class - -# operations (+, *, etc) shouldn't be InstanceElements - #246 -class A(): - def __init__(self): - self.addition = 1 + 2 -#? int() -A().addition - -# should also work before `=` -#? 8 int() -A().addition = None -#? 8 int() -A(1).addition = None -#? 1 A -A(1).addition = None -a = A() -#? 8 int() -a.addition = None - - -# ----------------- -# inheritance -# ----------------- - -class Base(object): - def method_base(self): - return 1 - -class SuperClass(Base): - class_super = 3 - def __init__(self): - self.var_super = '' - def method_super(self): - self.var2_super = list - -class Mixin(SuperClass): - def method_mixin(self): - return int - -#? 20 SuperClass -class SubClass(SuperClass): - class_sub = 3 - def __init__(self): - self.var_sub = '' - def method_sub(self): - self.var_sub = list - return tuple - -instance = SubClass() - -#? ['method_base', 'method_sub', 'method_super'] -instance.method_ -#? ['var2_super', 'var_sub', 'var_super'] -instance.var -#? ['class_sub', 'class_super'] -instance.class_ - -#? ['method_base', 'method_sub', 'method_super'] -SubClass.method_ -#? [] -SubClass.var -#? ['class_sub', 'class_super'] -SubClass.class_ - -# ----------------- -# inheritance of builtins -# ----------------- - -class Base(str): - pass - -#? ['upper'] -Base.upper -#? ['upper'] -Base().upper - -# ----------------- -# dynamic inheritance -# ----------------- - -class Angry(object): - def shout(self): - return 'THIS IS MALARKEY!' - -def classgetter(): - return Angry - -class Dude(classgetter()): - def react(self): - #? ['shout'] - self.s - -# ----------------- -# __call__ -# ----------------- - -class CallClass(): - def __call__(self): - return 1 - -#? int() -CallClass()() - -# ----------------- -# variable assignments -# ----------------- - -class V: - def __init__(self, a): - self.a = a - - def ret(self): - return self.a - - d = b - b = ret - if 1: - c = b - -#? int() -V(1).b() -#? int() -V(1).c() -#? -V(1).d() -# Only keywords should be possible to complete. -#? ['is', 'in', 'not', 'and', 'or', 'if'] -V(1).d() - - -# ----------------- -# ordering -# ----------------- -class A(): - def b(self): - #? int() - a_func() - #? str() - self.a_func() - return a_func() - - def a_func(self): - return "" - -def a_func(): - return 1 - -#? int() -A().b() -#? str() -A().a_func() - -# ----------------- -# nested classes -# ----------------- -class A(): - class B(): - pass - def b(self): - return 1.0 - -#? float() -A().b() - -class A(): - def b(self): - class B(): - def b(self): - return [] - return B().b() - -#? list() -A().b() - -# ----------------- -# ducktyping -# ----------------- - -def meth(self): - return self.a, self.b - -class WithoutMethod(): - a = 1 - def __init__(self): - self.b = 1.0 - def blub(self): - return self.b - m = meth - -class B(): - b = '' - -a = WithoutMethod().m() -#? int() -a[0] -#? float() -a[1] - -#? float() -WithoutMethod.blub(WithoutMethod()) -#? str() -WithoutMethod.blub(B()) - -# ----------------- -# __getattr__ / getattr() / __getattribute__ -# ----------------- - -#? str().upper -getattr(str(), 'upper') -#? str.upper -getattr(str, 'upper') - -# some strange getattr calls -#? -getattr(str, 1) -#? -getattr() -#? -getattr(str) -#? -getattr(getattr, 1) -#? -getattr(str, []) - - -class Base(): - def ret(self, b): - return b - -class Wrapper(): - def __init__(self, obj): - self.obj = obj - - def __getattr__(self, name): - return getattr(self.obj, name) - -class Wrapper2(): - def __getattribute__(self, name): - return getattr(Base(), name) - -#? int() -Wrapper(Base()).ret(3) - -#? int() -Wrapper2(Base()).ret(3) - -class GetattrArray(): - def __getattr__(self, name): - return [1] - -#? int() -GetattrArray().something[0] - - -# ----------------- -# private vars -# ----------------- -class PrivateVar(): - def __init__(self): - self.__var = 1 - #? int() - self.__var - #? ['__var'] - self.__var -#? [] -PrivateVar().__var -#? -PrivateVar().__var - -# ----------------- -# super -# ----------------- -class Super(object): - a = 3 - def return_sup(self): - return 1 - -class TestSuper(Super): - #? - super() - def test(self): - #? Super() - super() - #? ['a'] - super().a - if 1: - #? Super() - super() - def a(): - #? - super() - - def return_sup(self): - #? int() - return super().return_sup() - -#? int() -TestSuper().return_sup() - - -# ----------------- -# if flow at class level -# ----------------- -class TestX(object): - def normal_method(self): - return 1 - - if True: - def conditional_method(self): - var = self.normal_method() - #? int() - var - return 2 - - def other_method(self): - var = self.conditional_method() - #? int() - var - -# ----------------- -# mro method -# ----------------- - -class A(object): - a = 3 - -#? ['mro'] -A.mro -#? [] -A().mro - - -# ----------------- -# mro resolution -# ----------------- - -class B(A()): - b = 3 - -#? -B.a -#? -B().a -#? int() -B.b -#? int() -B().b diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/completion/completion.py b/vim-plugins/bundle/jedi-vim/jedi/test/completion/completion.py deleted file mode 100644 index 91bc2aa..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/completion/completion.py +++ /dev/null @@ -1,26 +0,0 @@ -""" -Special cases of completions (typically special positions that caused issues -with context parsing. -""" - -def pass_decorator(func): - return func - - -def x(): - return ( - 1, -#? ["tuple"] -tuple - ) - - # Comment just somewhere - - -class MyClass: - @pass_decorator - def x(foo, -#? 5 ["tuple"] -tuple, - ): - return 1 diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/completion/complex.py b/vim-plugins/bundle/jedi-vim/jedi/test/completion/complex.py deleted file mode 100644 index 3ea8327..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/completion/complex.py +++ /dev/null @@ -1,14 +0,0 @@ -""" Mostly for stupid error reports of @dbrgn. :-) """ - -import time - -class Foo(object): - global time - asdf = time - -def asdfy(): - return Foo - -xorz = getattr(asdfy()(), 'asdf') -#? time -xorz diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/completion/comprehensions.py b/vim-plugins/bundle/jedi-vim/jedi/test/completion/comprehensions.py deleted file mode 100644 index a0a709c..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/completion/comprehensions.py +++ /dev/null @@ -1,200 +0,0 @@ -# ----------------- -# list comprehensions -# ----------------- - -# basics: - -a = ['' for a in [1]] -#? str() -a[0] -#? ['insert'] -a.insert - -a = [a for a in [1]] -#? int() -a[0] - -y = 1.0 -# Should not leak. -[y for y in [3]] -#? float() -y - -a = [a for a in (1, 2)] -#? int() -a[0] - -a = [a for a,b in [(1,'')]] -#? int() -a[0] - -arr = [1,''] -a = [a for a in arr] -#? int() -a[0] -#? str() -a[1] -#? int() str() -a[2] - -a = [a if 1.0 else '' for a in [1] if [1.0]] -#? int() str() -a[0] - -# name resolve should be correct -left, right = 'a', 'b' -left, right = [x for x in (left, right)] -#? str() -left - -# with a dict literal -#? int() -[a for a in {1:'x'}][0] - -# list comprehensions should also work in combination with functions -def listen(arg): - for x in arg: - #? str() - x - -listen(['' for x in [1]]) -#? -([str for x in []])[0] - -# with a set literal -#? int() -[a for a in {1, 2, 3}][0] - -# ----------------- -# nested list comprehensions -# ----------------- - -b = [a for arr in [[1]] for a in arr] -#? int() -b[0] - -b = [a for arr in [[1]] if '' for a in arr if ''] -#? int() -b[0] - -b = [b for arr in [[[1.0]]] for a in arr for b in a] -#? float() -b[0] - -# jedi issue #26 -#? list() -a = [[int(v) for v in line.strip().split() if v] for line in ["123", "123", "123"] if line] -#? list() -a[0] -#? int() -a[0][0] - -# ----------------- -# generator comprehensions -# ----------------- - -left, right = (i for i in (1, '')) - -#? int() -left -#? str() -right - -gen = (i for i in (1,)) - -#? int() -next(gen) -#? -gen[0] - -gen = (a for arr in [[1.0]] for a in arr) -#? float() -next(gen) - -#? int() -(i for i in (1,)).send() - -# issues with different formats -left, right = (i for i in - ('1', 2)) -#? str() -left -#? int() -right - -# ----------------- -# dict comprehensions -# ----------------- - -#? int() -list({a - 1: 3 for a in [1]})[0] - -d = {a - 1: b for a, b in {1: 'a', 3: 1.0}.items()} -#? int() -list(d)[0] -#? str() float() -d.values()[0] -#? str() -d[0] -#? float() str() -d[1] -#? float() -d[2] - -# ----------------- -# set comprehensions -# ----------------- - -#? set() -{a - 1 for a in [1]} - -#? set() -{a for a in range(10)} - -#? int() -[x for x in {a for a in range(10)}][0] - -#? int() -{a for a in range(10)}.pop() -#? float() str() -{b for a in [[3.0], ['']] for b in a}.pop() - -#? int() -next(iter({a for a in range(10)})) - - -# ----------------- -# name resolution in comprehensions. -# ----------------- - -def x(): - """Should not try to resolve to the if hio, which was a bug.""" - #? 22 - [a for a in h if hio] - if hio: pass - -# ----------------- -# slices -# ----------------- - -#? list() -foo = [x for x in [1, '']][:1] -#? int() -foo[0] - -# ----------------- -# In class -# ----------------- - -class X(): - def __init__(self, bar): - self.bar = bar - - def foo(self): - x = [a for a in self.bar][0] - #? int() - x - return x - -#? int() -X([1]).foo() diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/completion/context.py b/vim-plugins/bundle/jedi-vim/jedi/test/completion/context.py deleted file mode 100644 index 0f0b288..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/completion/context.py +++ /dev/null @@ -1,32 +0,0 @@ -class Base(): - myfoobar = 3 - - -class X(Base): - def func(self, foo): - pass - - -class Y(X): - def actual_function(self): - pass - - #? [] - def actual_function - #? ['func'] - def f - - #? [] - def __class__ - - #? ['__repr__'] - def __repr__ - - #? [] - def mro - - #? ['myfoobar'] - myfoobar - -#? [] -myfoobar diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/completion/decorators.py b/vim-plugins/bundle/jedi-vim/jedi/test/completion/decorators.py deleted file mode 100644 index 702c3f3..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/completion/decorators.py +++ /dev/null @@ -1,306 +0,0 @@ -# ----------------- -# normal decorators -# ----------------- - -def decorator(func): - def wrapper(*args): - return func(1, *args) - return wrapper - -@decorator -def decorated(a,b): - return a,b - -exe = decorated(set, '') - -#? set -exe[1] - -#? int() -exe[0] - -# more complicated with args/kwargs -def dec(func): - def wrapper(*args, **kwargs): - return func(*args, **kwargs) - return wrapper - -@dec -def fu(a, b, c, *args, **kwargs): - return a, b, c, args, kwargs - -exe = fu(list, c=set, b=3, d='') - -#? list -exe[0] -#? int() -exe[1] -#? set -exe[2] -#? [] -exe[3][0]. -#? str() -exe[4]['d'] - - -exe = fu(list, set, 3, '', d='') - -#? str() -exe[3][0] - -# ----------------- -# multiple decorators -# ----------------- -def dec2(func2): - def wrapper2(first_arg, *args2, **kwargs2): - return func2(first_arg, *args2, **kwargs2) - return wrapper2 - -@dec2 -@dec -def fu2(a, b, c, *args, **kwargs): - return a, b, c, args, kwargs - -exe = fu2(list, c=set, b=3, d='str') - -#? list -exe[0] -#? int() -exe[1] -#? set -exe[2] -#? [] -exe[3][0]. -#? str() -exe[4]['d'] - - -# ----------------- -# Decorator is a class -# ----------------- -def same_func(func): - return func - -class Decorator(object): - def __init__(self, func): - self.func = func - - def __call__(self, *args, **kwargs): - return self.func(1, *args, **kwargs) - -@Decorator -def nothing(a,b,c): - return a,b,c - -#? int() -nothing("")[0] -#? str() -nothing("")[1] - - -@same_func -@Decorator -def nothing(a,b,c): - return a,b,c - -#? int() -nothing("")[0] - -class MethodDecoratorAsClass(): - class_var = 3 - @Decorator - def func_without_self(arg, arg2): - return arg, arg2 - - @Decorator - def func_with_self(self, arg): - return self.class_var - -#? int() -MethodDecoratorAsClass().func_without_self('')[0] -#? str() -MethodDecoratorAsClass().func_without_self('')[1] -#? -MethodDecoratorAsClass().func_with_self(1) - - -class SelfVars(): - """Init decorator problem as an instance, #247""" - @Decorator - def __init__(self): - """ - __init__ decorators should be ignored when looking up variables in the - class. - """ - self.c = list - - @Decorator - def shouldnt_expose_var(not_self): - """ - Even though in real Python this shouldn't expose the variable, in this - case Jedi exposes the variable, because these kind of decorators are - normally descriptors, which SHOULD be exposed (at least 90%). - """ - not_self.b = 1.0 - - def other_method(self): - #? float() - self.b - #? list - self.c - -# ----------------- -# not found decorators (are just ignored) -# ----------------- -@not_found_decorator -def just_a_func(): - return 1 - -#? int() -just_a_func() - -#? ['__closure__'] -just_a_func.__closure__ - - -class JustAClass: - @not_found_decorator2 - def a(self): - return 1 - -#? ['__call__'] -JustAClass().a.__call__ -#? int() -JustAClass().a() -#? ['__call__'] -JustAClass.a.__call__ -#? int() -JustAClass.a() - -# ----------------- -# illegal decorators -# ----------------- - -class DecoratorWithoutCall(): - def __init__(self, func): - self.func = func - -@DecoratorWithoutCall -def f(): - return 1 - -# cannot be resolved - should be ignored -@DecoratorWithoutCall(None) -def g(): - return 1 - -#? -f() -#? int() -g() - - -class X(): - @str - def x(self): - pass - - def y(self): - #? str() - self.x - #? - self.x() - -# ----------------- -# method decorators -# ----------------- - -def dec(f): - def wrapper(s): - return f(s) - return wrapper - -class MethodDecorators(): - _class_var = 1 - def __init__(self): - self._method_var = '' - - @dec - def constant(self): - return 1.0 - - @dec - def class_var(self): - return self._class_var - - @dec - def method_var(self): - return self._method_var - -#? float() -MethodDecorators().constant() -#? int() -MethodDecorators().class_var() -#? str() -MethodDecorators().method_var() - - -class Base(): - @not_existing - def __init__(self): - pass - @not_existing - def b(self): - return '' - @dec - def c(self): - return 1 - -class MethodDecoratorDoesntExist(Base): - """#272 github: combination of method decorators and super()""" - def a(self): - #? - super().__init__() - #? str() - super().b() - #? int() - super().c() - #? float() - self.d() - - @doesnt_exist - def d(self): - return 1.0 - -# ----------------- -# others -# ----------------- -def memoize(function): - def wrapper(*args): - if random.choice([0, 1]): - pass - else: - rv = function(*args) - return rv - return wrapper - -@memoize -def follow_statement(stmt): - return stmt - -# here we had problems with the else clause, because the parent was not right. -#? int() -follow_statement(1) - -# ----------------- -# class decorators -# ----------------- - -# class decorators should just be ignored -@should_ignore -class A(): - def ret(self): - return 1 - -#? int() -A().ret() diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/completion/definition.py b/vim-plugins/bundle/jedi-vim/jedi/test/completion/definition.py deleted file mode 100644 index f896984..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/completion/definition.py +++ /dev/null @@ -1,68 +0,0 @@ -""" -Fallback to callee definition when definition not found. -- https://github.com/davidhalter/jedi/issues/131 -- https://github.com/davidhalter/jedi/pull/149 -""" - -"""Parenthesis closed at next line.""" - -# Ignore these definitions for a little while, not sure if we really want them. -# python <= 2.5 - -#? isinstance -isinstance( -) - -#? isinstance -isinstance( -) - -#? isinstance -isinstance(None, -) - -#? isinstance -isinstance(None, -) - -"""Parenthesis closed at same line.""" - -# Note: len('isinstance(') == 11 -#? 11 isinstance -isinstance() - -# Note: len('isinstance(None,') == 16 -##? 16 isinstance -isinstance(None,) - -# Note: len('isinstance(None,') == 16 -##? 16 isinstance -isinstance(None, ) - -# Note: len('isinstance(None, ') == 17 -##? 17 isinstance -isinstance(None, ) - -# Note: len('isinstance( ') == 12 -##? 12 isinstance -isinstance( ) - -"""Unclosed parenthesis.""" - -#? isinstance -isinstance( - -def x(): pass # acts like EOF - -##? isinstance -isinstance( - -def x(): pass # acts like EOF - -#? isinstance -isinstance(None, - -def x(): pass # acts like EOF - -##? isinstance -isinstance(None, diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/completion/descriptors.py b/vim-plugins/bundle/jedi-vim/jedi/test/completion/descriptors.py deleted file mode 100644 index 4741778..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/completion/descriptors.py +++ /dev/null @@ -1,219 +0,0 @@ -class RevealAccess(object): - """ - A data descriptor that sets and returns values - normally and prints a message logging their access. - """ - def __init__(self, initval=None, name='var'): - self.val = initval - self.name = name - - def __get__(self, obj, objtype): - print('Retrieving', self.name) - return self.val - - def __set__(self, obj, val): - print('Updating', self.name) - self.val = val - - def just_a_method(self): - pass - -class C(object): - x = RevealAccess(10, 'var "x"') - #? RevealAccess() - x - #? ['just_a_method'] - x.just_a_method - y = 5.0 - def __init__(self): - #? int() - self.x - - #? [] - self.just_a_method - #? [] - C.just_a_method - -m = C() -#? int() -m.x -#? float() -m.y -#? int() -C.x - -#? [] -m.just_a_method -#? [] -C.just_a_method - -# ----------------- -# properties -# ----------------- -class B(): - @property - def r(self): - return 1 - @r.setter - def r(self, value): - return '' - def t(self): - return '' - p = property(t) - -#? [] -B().r(). -#? int() -B().r - -#? str() -B().p -#? [] -B().p(). - -class PropClass(): - def __init__(self, a): - self.a = a - @property - def ret(self): - return self.a - - @ret.setter - def ret(self, value): - return 1.0 - - def ret2(self): - return self.a - ret2 = property(ret2) - - @property - def nested(self): - """ causes recusions in properties, should work """ - return self.ret - - @property - def nested2(self): - """ causes recusions in properties, should not work """ - return self.nested2 - - @property - def join1(self): - """ mutual recusion """ - return self.join2 - - @property - def join2(self): - """ mutual recusion """ - return self.join1 - -#? str() -PropClass("").ret -#? [] -PropClass().ret. - -#? str() -PropClass("").ret2 -#? -PropClass().ret2 - -#? int() -PropClass(1).nested -#? [] -PropClass().nested. - -#? -PropClass(1).nested2 -#? [] -PropClass().nested2. - -#? -PropClass(1).join1 -# ----------------- -# staticmethod/classmethod -# ----------------- - -class E(object): - a = '' - def __init__(self, a): - self.a = a - - def f(x): - return x - f = staticmethod(f) - - @staticmethod - def g(x): - return x - - def s(cls, x): - return x - s = classmethod(s) - - @classmethod - def t(cls, x): - return x - - @classmethod - def u(cls, x): - return cls.a - -e = E(1) -#? int() -e.f(1) -#? int() -E.f(1) -#? int() -e.g(1) -#? int() -E.g(1) - -#? int() -e.s(1) -#? int() -E.s(1) -#? int() -e.t(1) -#? int() -E.t(1) - -#? str() -e.u(1) -#? str() -E.u(1) - -# ----------------- -# Conditions -# ----------------- - -from functools import partial - - -class Memoize(): - def __init__(self, func): - self.func = func - - def __get__(self, obj, objtype): - if obj is None: - return self.func - - return partial(self, obj) - - def __call__(self, *args, **kwargs): - # We don't do caching here, but that's what would normally happen. - return self.func(*args, **kwargs) - - -class MemoizeTest(): - def __init__(self, x): - self.x = x - - @Memoize - def some_func(self): - return self.x - - -#? int() -MemoizeTest(10).some_func() -# Now also call the same function over the class (see if clause above). -#? float() -MemoizeTest.some_func(MemoizeTest(10.0)) diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/completion/docstring.py b/vim-plugins/bundle/jedi-vim/jedi/test/completion/docstring.py deleted file mode 100644 index 338080a..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/completion/docstring.py +++ /dev/null @@ -1,235 +0,0 @@ -""" Test docstrings in functions and classes, which are used to infer types """ - -# ----------------- -# sphinx style -# ----------------- -def sphinxy(a, b, c, d, x): - """ asdfasdf - :param a: blablabla - :type a: str - :type b: (str, int) - :type c: random.Random - :type d: :class:`random.Random` - :param str x: blablabla - :rtype: dict - """ - #? str() - a - #? str() - b[0] - #? int() - b[1] - #? ['seed'] - c.seed - #? ['seed'] - d.seed - #? ['lower'] - x.lower - -#? dict() -sphinxy() - -# wrong declarations -def sphinxy2(a, b, x): - """ - :param a: Forgot type declaration - :type a: - :param b: Just something - :type b: `` - :param x: Just something without type - :rtype: - """ - #? - a - #? - b - #? - x - -#? -sphinxy2() - -# local classes -> github #370 -class ProgramNode(): - pass - -def local_classes(node, node2): - """ - :type node: ProgramNode - ... and the class definition after this func definition: - :type node2: ProgramNode2 - """ - #? ProgramNode() - node - #? ProgramNode2() - node2 - -class ProgramNode2(): - pass - - -def list_with_non_imports(lst): - """ - Should be able to work with tuples and lists and still import stuff. - - :type lst: (random.Random, [collections.defaultdict, ...]) - """ - #? ['seed'] - lst[0].seed - - import collections as col - # use some weird index - #? col.defaultdict() - lst[1][10] - - -def two_dots(a): - """ - :type a: json.decoder.JSONDecoder - """ - #? ['raw_decode'] - a.raw_decode - - -# sphinx returns -def return_module_object(): - """ - :rtype: :class:`random.Random` - """ - -#? ['seed'] -return_module_object().seed - - -# ----------------- -# epydoc style -# ----------------- -def epydoc(a, b): - """ asdfasdf - @type a: str - @param a: blablabla - @type b: (str, int) - @param b: blablah - @rtype: list - """ - #? str() - a - #? str() - b[0] - - #? int() - b[1] - -#? list() -epydoc() - - -# Returns with param type only -def rparam(a,b): - """ - @type a: str - """ - return a - -#? str() -rparam() - - -# Composite types -def composite(): - """ - @rtype: (str, int, dict) - """ - -x, y, z = composite() -#? str() -x -#? int() -y -#? dict() -z - - -# Both docstring and calculated return type -def both(): - """ - @rtype: str - """ - return 23 - -#? str() int() -both() - -class Test(object): - def __init__(self): - self.teststr = "" - """ - # jedi issue #210 - """ - def test(self): - #? ['teststr'] - self.teststr - -# ----------------- -# statement docstrings -# ----------------- -d = '' -""" bsdf """ -#? str() -d.upper() - -# ----------------- -# class docstrings -# ----------------- - -class InInit(): - def __init__(self, foo): - """ - :type foo: str - """ - #? str() - foo - - -class InClass(): - """ - :type foo: str - """ - def __init__(self, foo): - #? str() - foo - - -class InBoth(): - """ - :type foo: str - """ - def __init__(self, foo): - """ - :type foo: int - """ - #? str() int() - foo - - -def __init__(foo): - """ - :type foo: str - """ - #? str() - foo - - -# ----------------- -# Renamed imports (#507) -# ----------------- - -import datetime -from datetime import datetime as datetime_imported - -def import_issues(foo): - """ - @type foo: datetime_imported - """ - #? datetime.datetime() - foo diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/completion/dynamic_arrays.py b/vim-plugins/bundle/jedi-vim/jedi/test/completion/dynamic_arrays.py deleted file mode 100644 index 19cb920..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/completion/dynamic_arrays.py +++ /dev/null @@ -1,306 +0,0 @@ -""" -Checking for ``list.append`` and all the other possible array modifications. -""" -# ----------------- -# list.append -# ----------------- -arr = [] -for a in [1,2]: - arr.append(a); - -arr.append # should not cause an exception -arr.append() # should not cause an exception - -#? int() -arr[10] - -arr = [tuple()] -for a in [1,2]: - arr.append(a); - -#? int() tuple() -arr[10] -#? int() -arr[10].index() - -arr = list([]) -arr.append(1) -#? int() -arr[0] - -# ----------------- -# list.insert -# ----------------- -arr = [""] -arr.insert(0, 1.0) - -# on exception due to this, please! -arr.insert(0) -arr.insert() - -#? float() str() -arr[10] - -for a in arr: - #? float() str() - a - -#? float() str() -list(arr)[10] - -# ----------------- -# set.add -# ----------------- -st = {1.0} -for a in [1,2]: - st.add(a) - -st.append('') # lists should not have an influence - -st.add # should not cause an exception -st.add() - -# ----------------- -# list.extend / set.update -# ----------------- - -arr = [1.0] -arr.extend([1,2,3]) -arr.extend([]) -arr.extend("") # should ignore - -#? float() int() -arr[100] - -a = set(arr) -a.update(list(["", 1])) - -#? float() int() str() -list(a)[0] -# ----------------- -# set/list initialized as functions -# ----------------- - -st = set() -st.add(1) - -#? int() -for s in st: s - -lst = list() -lst.append(1) - -#? int() -for i in lst: i - -# ----------------- -# renames / type changes -# ----------------- -arr = [] -arr2 = arr -arr2.append('') -#? str() -arr2[0] - - -st = {1.0} -st.add(1) -lst = list(st) - -lst.append('') - -#? float() int() str() -lst[0] - -lst = [1] -lst.append(1.0) -s = set(lst) -s.add("") -lst = list(s) -lst.append({}) - -#? dict() int() float() str() -lst[0] - -# should work with tuple conversion, too. -#? dict() int() float() str() -tuple(lst)[0] - -# but not with an iterator -#? -iter(lst)[0] - -# ----------------- -# complex including += -# ----------------- -class C(): pass -class D(): pass -class E(): pass -lst = [1] -lst.append(1.0) -lst += [C] -s = set(lst) -s.add("") -s += [D] -lst = list(s) -lst.append({}) -lst += [E] - -##? dict() int() float() str() C D E -lst[0] - -# ----------------- -# functions -# ----------------- - -def arr_append(arr4, a): - arr4.append(a) - -def add_to_arr(arr2, a): - arr2.append(a) - return arr2 - -def app(a): - arr3.append(a) - -arr3 = [1.0] -res = add_to_arr(arr3, 1) -arr_append(arr3, 'str') -app(set()) - -#? float() str() int() set() -arr3[10] - -#? float() str() int() set() -res[10] - -# ----------------- -# returns, special because the module dicts are not correct here. -# ----------------- -def blub(): - a = [] - a.append(1.0) - #? float() - a[0] - return a - -#? float() -blub()[0] - -# list with default -def blub(): - a = list([1]) - a.append(1.0) - return a - -#? int() float() -blub()[0] - -# empty list -def blub(): - a = list() - a.append(1.0) - return a -#? float() -blub()[0] - -# with if -def blub(): - if 1: - a = [] - a.append(1.0) - return a - -#? float() -blub()[0] - -# with else clause -def blub(): - if random.choice([0, 1]): - 1 - else: - a = [] - a.append(1) - return a - -#? int() -blub()[0] -# ----------------- -# returns, the same for classes -# ----------------- -class C(): - def blub(self, b): - if 1: - a = [] - a.append(b) - return a - - def blub2(self): - """ mapper function """ - a = self.blub(1.0) - #? float() - a[0] - return a - - def literal_arr(self, el): - self.a = [] - self.a.append(el) - #? int() - self.a[0] - return self.a - - def list_arr(self, el): - self.b = list([]) - self.b.append(el) - #? float() - self.b[0] - return self.b - -#? int() -C().blub(1)[0] -#? float() -C().blub2(1)[0] - -#? int() -C().a[0] -#? int() -C().literal_arr(1)[0] - -#? float() -C().b[0] -#? float() -C().list_arr(1.0)[0] - -# ----------------- -# array recursions -# ----------------- - -a = set([1.0]) -a.update(a) -a.update([1]) - -#? float() int() -list(a)[0] - -def first(a): - b = [] - b.append(a) - b.extend(second(a)) - return list(b) - -def second(a): - b = [] - b.extend(first(a)) - return list(b) - -#? float() -first(1.0)[0] - -def third(): - b = [] - b.extend - extend() - b.extend(first()) - return list(b) -#? -third()[0] diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/completion/dynamic_params.py b/vim-plugins/bundle/jedi-vim/jedi/test/completion/dynamic_params.py deleted file mode 100644 index 2afc986..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/completion/dynamic_params.py +++ /dev/null @@ -1,134 +0,0 @@ -""" -This is used for dynamic object completion. -Jedi tries to guess param types with a backtracking approach. -""" -def func(a, default_arg=2): - #? int() - default_arg - #? int() str() - return a - -#? int() -func(1) - -func - -int(1) + (int(2))+ func('') - -# Again the same function, but with another call. -def func(a): - #? float() - return a - -func(1.0) - -# Again the same function, but with no call. -def func(a): - #? - return a - -def func(a): - #? float() - return a -str(func(1.0)) - -# ----------------- -# *args, **args -# ----------------- -def arg(*args): - #? tuple() - args - #? int() - args[0] - -arg(1,"") -# ----------------- -# decorators -# ----------------- -def def_func(f): - def wrapper(*args, **kwargs): - return f(*args, **kwargs) - return wrapper - -@def_func -def func(c): - #? str() - return c - -#? str() -func("str") - -@def_func -def func(c=1): - #? int() float() - return c - -func(1.0) - -def tricky_decorator(func): - def wrapper(*args): - return func(1, *args) - - return wrapper - - -@tricky_decorator -def func(a, b): - #? int() - a - #? float() - b - -func(1.0) - -# Needs to be here, because in this case func is an import -> shouldn't lead to -# exceptions. -import sys as func -func.sys - -# ----------------- -# classes -# ----------------- - -class A(): - def __init__(self, a): - #? str() - a - -A("s") - -class A(): - def __init__(self, a): - #? int() - a - self.a = a - - def test(self, a): - #? float() - a - self.c = self.test2() - - def test2(self): - #? int() - return self.a - - def test3(self): - #? int() - self.test2() - #? int() - self.c - -A(3).test(2.0) -A(3).test2() - - -# ----------------- -# list comprehensions -# ----------------- - -def from_comprehension(foo): - #? int() float() - return foo - -[from_comprehension(1.0) for n in (1,)] -[from_comprehension(n) for n in (1,)] diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/completion/flow_analysis.py b/vim-plugins/bundle/jedi-vim/jedi/test/completion/flow_analysis.py deleted file mode 100644 index 2840d9e..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/completion/flow_analysis.py +++ /dev/null @@ -1,257 +0,0 @@ -def foo(x): - if 1.0: - return 1 - else: - return '' - -#? int() -foo(1) - - -# Exceptions are not analyzed. So check both if branches -def try_except(x): - try: - if 0: - return 1 - else: - return '' - except AttributeError: - return 1.0 - -#? float() str() -try_except(1) - - -# Exceptions are not analyzed. So check both if branches -def try_except(x): - try: - if 0: - return 1 - else: - return '' - except AttributeError: - return 1.0 - -#? float() str() -try_except(1) - - -# ----------------- -# elif -# ----------------- - -def elif_flows1(x): - if False: - return 1 - elif True: - return 1.0 - else: - return '' - -#? float() -elif_flows1(1) - - -def elif_flows2(x): - try: - if False: - return 1 - elif 0: - return 1.0 - else: - return '' - except ValueError: - return set - -#? str() set -elif_flows2(1) - - -def elif_flows3(x): - try: - if True: - return 1 - elif 0: - return 1.0 - else: - return '' - except ValueError: - return set - -#? int() set -elif_flows3(1) - -# ----------------- -# mid-difficulty if statements -# ----------------- -def check(a): - if a is None: - return 1 - return '' - return set - -#? int() -check(None) -#? str() -check('asb') - -a = list -if 2 == True: - a = set -elif 1 == True: - a = 0 - -#? int() -a -if check != 1: - a = '' -#? str() -a -if check == check: - a = list -#? list -a -if check != check: - a = set -else: - a = dict -#? dict -a -if not (check is not check): - a = 1 -#? int() -a - - -# ----------------- -# name resolution -# ----------------- - -a = list -def elif_name(x): - try: - if True: - a = 1 - elif 0: - a = 1.0 - else: - return '' - except ValueError: - a = x - return a - -#? int() set -elif_name(set) - -if 0: - a = '' -else: - a = int - -#? int -a - -# ----------------- -# isinstance -# ----------------- - -class A(): pass - -def isinst(x): - if isinstance(x, A): - return dict - elif isinstance(x, int) and x == 1 or x is True: - return set - elif isinstance(x, (float, reversed)): - return list - elif not isinstance(x, str): - return tuple - return 1 - -#? dict -isinst(A()) -#? set -isinst(True) -#? set -isinst(1) -#? tuple -isinst(2) -#? list -isinst(1.0) -#? tuple -isinst(False) -#? int() -isinst('') - -# ----------------- -# flows that are not reachable should be able to access parent scopes. -# ----------------- - -foobar = '' - -if 0: - within_flow = 1.0 - #? float() - within_flow - #? str() - foobar - if 0: - nested = 1 - #? int() - nested - #? float() - within_flow - #? str() - foobar - #? - nested - -# ----------------- -# True objects like modules -# ----------------- - -class X(): - pass -if X: - a = 1 -else: - a = '' -#? int() -a - - -# ----------------- -# Recursion issues -# ----------------- - -def possible_recursion_error(filename): - if filename == 'a': - return filename - # It seems like without the brackets there wouldn't be a RecursionError. - elif type(filename) == str: - return filename - - -if NOT_DEFINED: - s = str() -else: - s = str() -#? str() -possible_recursion_error(s) - - -# ----------------- -# In combination with imports -# ----------------- - -from import_tree import flow_import - -if 1 == flow_import.env: - a = 1 -elif 2 == flow_import.env: - a = '' -elif 3 == flow_import.env: - a = 1.0 - -#? int() str() -a diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/completion/functions.py b/vim-plugins/bundle/jedi-vim/jedi/test/completion/functions.py deleted file mode 100644 index c1a40e5..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/completion/functions.py +++ /dev/null @@ -1,475 +0,0 @@ -def array(first_param): - #? ['first_param'] - first_param - return list() - -#? [] -array.first_param -#? [] -array.first_param. -func = array -#? [] -func.first_param - -#? list() -array() - -#? ['array'] -arr - - -def inputs(param): - return param - -#? list -inputs(list) - -def variable_middle(): - var = 3 - return var - -#? int() -variable_middle() - -def variable_rename(param): - var = param - return var - -#? int() -variable_rename(1) - -def multi_line_func(a, # comment blabla - - b): - return b - -#? str() -multi_line_func(1,'') - -def multi_line_call(b): - return b - - -multi_line_call( -#? int() - b=1) - - -# nothing after comma -def asdf(a): - return a - -x = asdf(a=1, - ) -#? int() -x - -# ----------------- -# double execution -# ----------------- -def double_exe(param): - return param - -#? str() -variable_rename(double_exe)("") - -# -> shouldn't work (and throw no error) -#? [] -variable_rename(list())(). -#? [] -variable_rename(1)(). - -# ----------------- -# recursions (should ignore) -# ----------------- -def recursion(a, b): - if a: - return b - else: - return recursion(a+".", b+1) - -# Does not also return int anymore, because we now support operators in simple cases. -#? float() -recursion("a", 1.0) - -def other(a): - return recursion2(a) - -def recursion2(a): - if random.choice([0, 1]): - return other(a) - else: - if random.choice([0, 1]): - return recursion2("") - else: - return a - -#? int() str() -recursion2(1) - -# ----------------- -# ordering -# ----------------- - -def a(): - #? int() - b() - return b() - -def b(): - return 1 - -#? int() -a() - -# ----------------- -# keyword arguments -# ----------------- - -def func(a=1, b=''): - return a, b - -exe = func(b=list, a=tuple) -#? tuple -exe[0] - -#? list -exe[1] - -# ----------------- -# default arguments -# ----------------- - -#? int() -func()[0] -#? str() -func()[1] -#? float() -func(1.0)[0] -#? str() -func(1.0)[1] - - -#? float() -func(a=1.0)[0] -#? str() -func(a=1.0)[1] -#? int() -func(b=1.0)[0] -#? float() -func(b=1.0)[1] -#? list -func(a=list, b=set)[0] -#? set -func(a=list, b=set)[1] - - -def func_default(a, b=1): - return a, b - - -def nested_default(**kwargs): - return func_default(**kwargs) - -#? float() -nested_default(a=1.0)[0] -#? int() -nested_default(a=1.0)[1] -#? str() -nested_default(a=1.0, b='')[1] - -# Defaults should only work if they are defined before - not after. -def default_function(a=default): - #? - return a - -#? -default_function() - -default = int() - -def default_function(a=default): - #? int() - return a - -#? int() -default_function() - - -# ----------------- -# closures -# ----------------- -def a(): - l = 3 - def func_b(): - l = '' - #? str() - l - #? ['func_b'] - func_b - #? int() - l - -# ----------------- -# *args -# ----------------- - -def args_func(*args): - #? tuple() - return args - -exe = args_func(1, "") -#? int() -exe[0] -#? str() -exe[1] - -# illegal args (TypeError) -#? -args_func(*1)[0] -# iterator -#? int() -args_func(*iter([1]))[0] - -# different types -e = args_func(*[1+"", {}]) -#? int() str() -e[0] -#? dict() -e[1] - -_list = [1,""] -exe2 = args_func(_list)[0] - -#? str() -exe2[1] - -exe3 = args_func([1,""])[0] - -#? str() -exe3[1] - -def args_func(arg1, *args): - return arg1, args - -exe = args_func(1, "", list) -#? int() -exe[0] -#? tuple() -exe[1] -#? list -exe[1][1] - - -# In a dynamic search, both inputs should be given. -def simple(a): - #? int() str() - return a -def xargs(*args): - return simple(*args) - -xargs(1) -xargs('') - - -# *args without a self symbol -def memoize(func): - def wrapper(*args, **kwargs): - return func(*args, **kwargs) - return wrapper - - -class Something(): - @memoize - def x(self, a, b=1): - return a - -#? int() -Something().x(1) - - -# ----------------- -# ** kwargs -# ----------------- -def kwargs_func(**kwargs): - #? ['keys'] - kwargs.keys - #? dict() - return kwargs - -exe = kwargs_func(a=3,b=4.0) -#? dict() -exe -#? int() -exe['a'] -#? float() -exe['b'] -#? int() float() -exe['c'] - -a = 'a' -exe2 = kwargs_func(**{a:3, - 'b':4.0}) -#? int() -exe2['a'] -#? float() -exe2['b'] -#? int() float() -exe2['c'] - -# ----------------- -# *args / ** kwargs -# ----------------- - -def func_without_call(*args, **kwargs): - #? tuple() - args - #? dict() - kwargs - -def fu(a=1, b="", *args, **kwargs): - return a, b, args, kwargs - -exe = fu(list, 1, "", c=set, d="") - -#? list -exe[0] -#? int() -exe[1] -#? tuple() -exe[2] -#? str() -exe[2][0] -#? dict() -exe[3] -#? set -exe[3]['c'] - - -def kwargs_iteration(**kwargs): - return kwargs - -for x in kwargs_iteration(d=3): - #? float() - {'d': 1.0, 'c': '1'}[x] - - -# ----------------- -# nested *args -# ----------------- -def function_args(a, b, c): - return b - -def nested_args(*args): - return function_args(*args) - -def nested_args2(*args, **kwargs): - return nested_args(*args) - -#? int() -nested_args('', 1, 1.0, list) -#? [] -nested_args(''). - -#? int() -nested_args2('', 1, 1.0) -#? [] -nested_args2(''). - -# ----------------- -# nested **kwargs -# ----------------- -def nested_kw(**kwargs1): - return function_args(**kwargs1) - -def nested_kw2(**kwargs2): - return nested_kw(**kwargs2) - -# invalid command, doesn't need to return anything -#? -nested_kw(b=1, c=1.0, list) -#? int() -nested_kw(b=1) -# invalid command, doesn't need to return anything -#? -nested_kw(d=1.0, b=1, list) -#? int() -nested_kw(a=3.0, b=1) -#? int() -nested_kw(b=1, a=r"") -#? [] -nested_kw(1, ''). -#? [] -nested_kw(a=''). - -#? int() -nested_kw2(b=1) -#? int() -nested_kw2(b=1, c=1.0) -#? int() -nested_kw2(c=1.0, b=1) -#? [] -nested_kw2(''). -#? [] -nested_kw2(a=''). -#? [] -nested_kw2('', b=1). - -# ----------------- -# nested *args/**kwargs -# ----------------- -def nested_both(*args, **kwargs): - return function_args(*args, **kwargs) - -def nested_both2(*args, **kwargs): - return nested_both(*args, **kwargs) - -# invalid commands, may return whatever. -#? list -nested_both('', b=1, c=1.0, list) -#? list -nested_both('', c=1.0, b=1, list) - -#? [] -nested_both(''). - -#? int() -nested_both2('', b=1, c=1.0) -#? int() -nested_both2('', c=1.0, b=1) -#? [] -nested_both2(''). - -# ----------------- -# nested *args/**kwargs with a default arg -# ----------------- -def function_def(a, b, c): - return a, b - -def nested_def(a, *args, **kwargs): - return function_def(a, *args, **kwargs) - -def nested_def2(*args, **kwargs): - return nested_def(*args, **kwargs) - -#? str() -nested_def2('', 1, 1.0)[0] -#? str() -nested_def2('', b=1, c=1.0)[0] -#? str() -nested_def2('', c=1.0, b=1)[0] -#? int() -nested_def2('', 1, 1.0)[1] -#? int() -nested_def2('', b=1, c=1.0)[1] -#? int() -nested_def2('', c=1.0, b=1)[1] -#? [] -nested_def2('')[1]. - -# ----------------- -# magic methods -# ----------------- -def a(): pass -#? ['__closure__'] -a.__closure__ diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/completion/generators.py b/vim-plugins/bundle/jedi-vim/jedi/test/completion/generators.py deleted file mode 100644 index d8eba2d..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/completion/generators.py +++ /dev/null @@ -1,199 +0,0 @@ -# ----------------- -# yield statement -# ----------------- -def gen(): - if random.choice([0, 1]): - yield 1 - else: - yield "" - -gen_exe = gen() -#? int() str() -next(gen_exe) - -#? int() str() list -next(gen_exe, list) - - -def gen_ret(value): - yield value - -#? int() -next(gen_ret(1)) - -#? [] -next(gen_ret()). - -# generators evaluate to true if cast by bool. -a = '' -if gen_ret(): - a = 3 -#? int() -a - - -# ----------------- -# generators should not be indexable -# ----------------- -def get(param): - if random.choice([0, 1]): - yield 1 - else: - yield "" - -#? [] -get()[0]. - -# ----------------- -# __iter__ -# ----------------- -for a in get(): - #? int() str() - a - - -class Get(): - def __iter__(self): - if random.choice([0, 1]): - yield 1 - else: - yield "" - -b = [] -for a in Get(): - #? int() str() - a - b += [a] - -#? list() -b -#? int() str() -b[0] - -g = iter(Get()) -#? int() str() -next(g) - -g = iter([1.0]) -#? float() -next(g) - - -# ----------------- -# __next__ -# ----------------- -class Counter: - def __init__(self, low, high): - self.current = low - self.high = high - - def __iter__(self): - return self - - def next(self): - """ need to have both __next__ and next, because of py2/3 testing """ - return self.__next__() - - def __next__(self): - if self.current > self.high: - raise StopIteration - else: - self.current += 1 - return self.current - 1 - - -for c in Counter(3, 8): - #? int() - print c - - -# ----------------- -# tuples -# ----------------- -def gen(): - if random.choice([0,1]): - yield 1, "" - else: - yield 2, 1.0 - - -a, b = next(gen()) -#? int() -a -#? str() float() -b - - -def simple(): - if random.choice([0, 1]): - yield 1 - else: - yield "" - -a, b = simple() -#? int() str() -a -# For now this is ok. -#? -b - - -def simple2(): - yield 1 - yield "" - -a, b = simple2() -#? int() -a -#? str() -b - - -# ----------------- -# More complicated access -# ----------------- - -# `close` is a method wrapper. -#? ['__call__'] -gen().close.__call__ - -#? -gen().throw() - -#? ['co_consts'] -gen().gi_code.co_consts - -#? [] -gen.gi_code.co_consts - -# `send` is also a method wrapper. -#? ['__call__'] -gen().send.__call__ - -#? tuple() -gen().send() - -#? -gen()() - -# ----------------- -# yield from -# ----------------- - -# python >= 3.3 - -def yield_from(): - yield from iter([1]) - -#? int() -next(yield_from()) - -def yield_from_multiple(): - yield from iter([1]) - yield str() - -x, y = yield_from_multiple() -#? int() -x -#? str() -y diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/completion/goto.py b/vim-plugins/bundle/jedi-vim/jedi/test/completion/goto.py deleted file mode 100644 index ef9938c..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/completion/goto.py +++ /dev/null @@ -1,231 +0,0 @@ -# goto_assignments command tests are different in syntax - -definition = 3 -#! 0 ['a = definition'] -a = definition - -#! [] -b -#! ['a = definition'] -a - -b = a -c = b -#! ['c = b'] -c - -cd = 1 -#! 1 ['cd = c'] -cd = c -#! 0 ['cd = e'] -cd = e - -#! ['module math'] -import math -#! ['import math'] -math - -#! ['import math'] -b = math -#! ['b = math'] -b - -#! 18 ['foo = 10'] -foo = 10;print(foo) - -# ----------------- -# classes -# ----------------- -class C(object): - def b(self): - #! ['b = math'] - b - #! ['def b'] - self.b - #! 14 ['def b'] - self.b() - #! 11 ['self'] - self.b - return 1 - - #! ['def b'] - b - -#! ['b = math'] -b - -#! ['def b'] -C.b -#! ['def b'] -C().b -#! 0 ['class C'] -C().b -#! 0 ['class C'] -C().b - -D = C -#! ['def b'] -D.b -#! ['def b'] -D().b - -#! 0 ['D = C'] -D().b -#! 0 ['D = C'] -D().b - -def c(): - return '' - -#! ['def c'] -c -#! 0 ['def c'] -c() - - -class ClassVar(): - x = 3 - -#! ['x = 3'] -ClassVar.x -#! ['x = 3'] -ClassVar().x - -# before assignments -#! 10 ['x = 3'] -ClassVar.x = '' -#! 12 ['x = 3'] -ClassVar().x = '' - -# Recurring use of the same var name, github #315 -def f(t=None): - #! 9 ['t=None'] - t = t or 1 - - -class X(): - pass - -#! 3 [] -X(foo=x) - -# ----------------- -# imports -# ----------------- - -#! ['module import_tree'] -import import_tree -#! ["a = ''"] -import_tree.a - -#! ['module mod1'] -import import_tree.mod1 -#! ['a = 1'] -import_tree.mod1.a - -#! ['module pkg'] -import import_tree.pkg -#! ['a = list'] -import_tree.pkg.a - -#! ['module mod1'] -import import_tree.pkg.mod1 -#! ['a = 1.0'] -import_tree.pkg.mod1.a -#! ["a = ''"] -import_tree.a - -#! ['module mod1'] -from import_tree.pkg import mod1 -#! ['a = 1.0'] -mod1.a - -#! ['module mod1'] -from import_tree import mod1 -#! ['a = 1'] -mod1.a - -#! ['a = 1.0'] -from import_tree.pkg.mod1 import a - -#! ['import os'] -from .imports import os - -#! ['some_variable = 1'] -from . import some_variable - -# ----------------- -# anonymous classes -# ----------------- -def func(): - class A(): - def b(self): - return 1 - return A() - -#! 8 ['def b'] -func().b() - -# ----------------- -# on itself -# ----------------- - -#! 7 ['class ClassDef'] -class ClassDef(): - """ abc """ - pass - -# ----------------- -# params -# ----------------- - -param = ClassDef -#! 8 ['param'] -def ab1(param): pass -#! 9 ['param'] -def ab2(param): pass -#! 11 ['param = ClassDef'] -def ab3(a=param): pass - -ab1(ClassDef);ab2(ClassDef);ab3(ClassDef) - -# ----------------- -# for loops -# ----------------- - -for i in range(1): - #! ['for i in range(1): i'] - i - -for key, value in [(1,2)]: - #! ['for key, value in [(1,2)]: key'] - key - -for i in []: - #! ['for i in []: i'] - i - -# ----------------- -# decorator -# ----------------- -def dec(dec_param=3): - pass - -#! 8 ['dec_param=3'] -@dec(dec_param=5) -def y(): - pass - -class ClassDec(): - def class_func(func): - return func - -#! 14 ['def class_func'] -@ClassDec.class_func -def x(): - pass - -#! 2 ['class ClassDec'] -@ClassDec.class_func -def z(): - pass diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/completion/import_tree/__init__.py b/vim-plugins/bundle/jedi-vim/jedi/test/completion/import_tree/__init__.py deleted file mode 100644 index 5cbbcd7..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/completion/import_tree/__init__.py +++ /dev/null @@ -1,7 +0,0 @@ -a = '' - -from . import invisible_pkg - -the_pkg = invisible_pkg - -invisible_pkg = 1 diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/completion/import_tree/flow_import.py b/vim-plugins/bundle/jedi-vim/jedi/test/completion/import_tree/flow_import.py deleted file mode 100644 index a0a779e..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/completion/import_tree/flow_import.py +++ /dev/null @@ -1,4 +0,0 @@ -if name: - env = 1 -else: - env = 2 diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/completion/import_tree/invisible_pkg.py b/vim-plugins/bundle/jedi-vim/jedi/test/completion/import_tree/invisible_pkg.py deleted file mode 100644 index 9c78ce2..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/completion/import_tree/invisible_pkg.py +++ /dev/null @@ -1,7 +0,0 @@ -""" -It should not be possible to import this pkg except for the import_tree itself, -because it is overwritten there. (It would be possible with a sys.path -modification, though). -""" - -foo = 1.0 diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/completion/import_tree/mod1.py b/vim-plugins/bundle/jedi-vim/jedi/test/completion/import_tree/mod1.py deleted file mode 100644 index bd696d6..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/completion/import_tree/mod1.py +++ /dev/null @@ -1,4 +0,0 @@ -a = 1 -from import_tree.random import a as c - -foobarbaz = 3.0 diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/completion/import_tree/mod2.py b/vim-plugins/bundle/jedi-vim/jedi/test/completion/import_tree/mod2.py deleted file mode 100644 index 19914f5..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/completion/import_tree/mod2.py +++ /dev/null @@ -1 +0,0 @@ -from . import mod1 as fake diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/completion/import_tree/pkg/__init__.py b/vim-plugins/bundle/jedi-vim/jedi/test/completion/import_tree/pkg/__init__.py deleted file mode 100644 index 480f222..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/completion/import_tree/pkg/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -a = list - -from math import * diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/completion/import_tree/pkg/mod1.py b/vim-plugins/bundle/jedi-vim/jedi/test/completion/import_tree/pkg/mod1.py deleted file mode 100644 index 2b6777c..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/completion/import_tree/pkg/mod1.py +++ /dev/null @@ -1 +0,0 @@ -a = 1.0 diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/completion/import_tree/random.py b/vim-plugins/bundle/jedi-vim/jedi/test/completion/import_tree/random.py deleted file mode 100644 index a63ed05..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/completion/import_tree/random.py +++ /dev/null @@ -1,4 +0,0 @@ -""" -Here because random is also a builtin module. -""" -a = set diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/completion/import_tree/recurse_class1.py b/vim-plugins/bundle/jedi-vim/jedi/test/completion/import_tree/recurse_class1.py deleted file mode 100644 index 773408c..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/completion/import_tree/recurse_class1.py +++ /dev/null @@ -1,5 +0,0 @@ -import recurse_class2 - -class C(recurse_class2.C): - def a(self): - pass diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/completion/import_tree/recurse_class2.py b/vim-plugins/bundle/jedi-vim/jedi/test/completion/import_tree/recurse_class2.py deleted file mode 100644 index 42f84ef..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/completion/import_tree/recurse_class2.py +++ /dev/null @@ -1,4 +0,0 @@ -import recurse_class1 - -class C(recurse_class1.C): - pass diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/completion/import_tree/rename1.py b/vim-plugins/bundle/jedi-vim/jedi/test/completion/import_tree/rename1.py deleted file mode 100644 index bdc3315..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/completion/import_tree/rename1.py +++ /dev/null @@ -1,3 +0,0 @@ -""" used for renaming tests """ - -abc = 3 diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/completion/import_tree/rename2.py b/vim-plugins/bundle/jedi-vim/jedi/test/completion/import_tree/rename2.py deleted file mode 100644 index 8423895..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/completion/import_tree/rename2.py +++ /dev/null @@ -1,6 +0,0 @@ -""" used for renaming tests """ - - -from rename1 import abc - -abc diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/completion/imports.py b/vim-plugins/bundle/jedi-vim/jedi/test/completion/imports.py deleted file mode 100644 index 246b91e..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/completion/imports.py +++ /dev/null @@ -1,285 +0,0 @@ -# ----------------- -# own structure -# ----------------- - -# do separate scopes -def scope_basic(): - from import_tree import mod1 - - #? int() - mod1.a - - #? [] - import_tree.a - - #? [] - import_tree.mod1 - - import import_tree - #? str() - import_tree.a - - -def scope_pkg(): - import import_tree.mod1 - - #? str() - import_tree.a - - #? ['mod1'] - import_tree.mod1 - - #? int() - import_tree.mod1.a - -def scope_nested(): - import import_tree.pkg.mod1 - - #? str() - import_tree.a - - #? list - import_tree.pkg.a - - #? ['sqrt'] - import_tree.pkg.sqrt - - #? ['pkg'] - import_tree.p - - #? float() - import_tree.pkg.mod1.a - #? ['a', '__name__', '__package__', '__file__', '__doc__'] - a = import_tree.pkg.mod1. - - import import_tree.random - #? set - import_tree.random.a - -def scope_nested2(): - """Multiple modules should be indexable, if imported""" - import import_tree.mod1 - import import_tree.pkg - #? ['mod1'] - import_tree.mod1 - #? ['pkg'] - import_tree.pkg - - # With the latest changes this completion also works, because submodules - # are always included (some nested import structures lead to this, - # typically). - #? ['rename1'] - import_tree.rename1 - -def scope_from_import_variable(): - """ - All of them shouldn't work, because "fake" imports don't work in python - without the use of ``sys.modules`` modifications (e.g. ``os.path`` see also - github issue #213 for clarification. - """ - a = 3 - #? - from import_tree.mod2.fake import a - #? - from import_tree.mod2.fake import c - - #? - a - #? - c - -def scope_from_import_variable_with_parenthesis(): - from import_tree.mod2.fake import ( - a, foobarbaz - ) - - #? - a - #? - foobarbaz - # shouldn't complete, should still list the name though. - #? ['foobarbaz'] - foobarbaz - - -def as_imports(): - from import_tree.mod1 import a as xyz - #? int() - xyz - import not_existant, import_tree.mod1 as foo - #? int() - foo.a - import import_tree.mod1 as bar - #? int() - bar.a - - -def test_import_priorities(): - """ - It's possible to overwrite import paths in an ``__init__.py`` file, by - just assigining something there. - - See also #536. - """ - from import_tree import the_pkg, invisible_pkg - #? int() - invisible_pkg - # In real Python, this would be the module, but it's not, because Jedi - # doesn't care about most stateful issues such as __dict__, which it would - # need to, to do this in a correct way. - #? int() - the_pkg - # Importing foo is still possible, even though inivisible_pkg got changed. - #? float() - from import_tree.invisible_pkg import foo - - -# ----------------- -# std lib modules -# ----------------- -import tokenize -#? ['tok_name'] -tokenize.tok_name - -from pyclbr import * - -#? ['readmodule_ex'] -readmodule_ex -import os - -#? ['dirname'] -os.path.dirname - -from os.path import ( - expanduser -) - -#? os.path.expanduser -expanduser - -from itertools import (tee, - islice) -#? ['islice'] -islice - -from functools import (partial, wraps) -#? ['wraps'] -wraps - -from keyword import kwlist, \ - iskeyword -#? ['kwlist'] -kwlist - -#? [] -from keyword import not_existing1, not_existing2 - -from tokenize import io -tokenize.generate_tokens - -# ----------------- -# builtins -# ----------------- - -import sys -#? ['prefix'] -sys.prefix - -#? ['append'] -sys.path.append - -from math import * -#? ['cos', 'cosh'] -cos - -def func_with_import(): - import time - return time - -#? ['sleep'] -func_with_import().sleep - -# ----------------- -# relative imports -# ----------------- - -from .import_tree import mod1 -#? int() -mod1.a - -from ..import_tree import mod1 -#? -mod1.a - -from .......import_tree import mod1 -#? -mod1.a - -from .. import helpers -#? int() -helpers.sample_int - -from ..helpers import sample_int as f -#? int() -f - -from . import run -#? [] -run. - -from . import import_tree as imp_tree -#? str() -imp_tree.a - -from . import datetime as mod1 -#? [] -mod1. - -# self import -# this can cause recursions -from imports import * - -# ----------------- -# packages -# ----------------- - -from import_tree.mod1 import c -#? set -c - -from import_tree import recurse_class1 - -#? ['a'] -recurse_class1.C.a -# github #239 RecursionError -#? ['a'] -recurse_class1.C().a - -# ----------------- -# Jedi debugging -# ----------------- - -# memoizing issues (check git history for the fix) -import not_existing_import - -if not_existing_import: - a = not_existing_import -else: - a = not_existing_import -#? -a - -# ----------------- -# module underscore descriptors -# ----------------- - -def underscore(): - import keyword - #? ['__file__'] - keyword.__file__ - #? str() - keyword.__file__ - - # Does that also work for the our own module? - #? ['__file__'] - __file__ diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/completion/invalid.py b/vim-plugins/bundle/jedi-vim/jedi/test/completion/invalid.py deleted file mode 100644 index 7c047e6..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/completion/invalid.py +++ /dev/null @@ -1,214 +0,0 @@ -""" -This file is less about the results and much more about the fact, that no -exception should be thrown. - -Basically this file could change depending on the current implementation. But -there should never be any errors. -""" - -# wait until keywords are out of definitions (pydoc function). -##? 5 -'s'() - -#? [] -str()).upper - -# ----------------- -# funcs -# ----------------- -def asdf(a or b): # multiple param names - return a - -#? -asdf(2) - -asdf = '' - -from a import (b -def blub(): - return 0 -def wrong_indents(): - asdf = 3 - asdf - asdf( - # TODO this seems to be wrong now? - ##? int() - asdf -def openbrace(): - asdf = 3 - asdf( - #? int() - asdf - return 1 - -#? int() -openbrace() - -blub([ -#? int() -openbrace() - -def indentfault(): - asd( - indentback - -#? [] -indentfault(). - -def openbrace2(): - asd( -def normalfunc(): - return 1 - -#? int() -normalfunc() - -# dots in param -def f(seq1...=None): - return seq1 -#? -f(1) - -@ -def test_empty_decorator(): - return 1 - -#? int() -test_empty_decorator() - -def invalid_param(param=): - #? - param -# ----------------- -# flows -# ----------------- - -# first part not complete (raised errors) -if a - a -else: - #? ['AttributeError'] - AttributeError - -try -#? ['AttributeError'] -except AttributeError - pass -finally: - pass - -#? ['isinstance'] -if isi -try: - except TypeError: - #? str() - str() - -def break(): pass -# wrong ternary expression -a = '' -a = 1 if -#? str() -a - -# No completions for for loops without the right syntax -for for_local in : - for_local -#? [] -for_local -#? -for_local - - -# ----------------- -# list comprehensions -# ----------------- - -a2 = [for a2 in [0]] -#? -a2[0] - -a3 = [for xyz in] -#? -a3[0] - -a3 = [a4 for in 'b'] -#? -a3[0] - -a3 = [a4 for a in for x in y] -#? -a3[0] - -a = [for a in -def break(): pass - -#? -a[0] - -a = [a for a in [1,2] -def break(): pass -#? -a[0] - -#? [] -int()).real - -# ----------------- -# keywords -# ----------------- - -#! [] -as - -def empty_assert(): - x = 3 - assert - #? int() - x - -import datetime as - - -# ----------------- -# statements -# ----------------- - -call = '' -invalid = .call -#? -invalid - -invalid = call?.call -#? str() -invalid - -# comma -invalid = ,call -#? str() -invalid - - -# ----------------- -# classes -# ----------------- - -class BrokenPartsOfClass(): - def foo(self): - # This construct contains two places where Jedi with Python 3 can fail. - # It should just ignore those constructs and still execute `bar`. - pass - if 2: - try: - pass - except ValueError, e: - raise TypeError, e - else: - pass - - def bar(self): - self.x = 3 - return '' - -#? str() -BrokenPartsOfClass().bar() diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/completion/isinstance.py b/vim-plugins/bundle/jedi-vim/jedi/test/completion/isinstance.py deleted file mode 100644 index 7101150..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/completion/isinstance.py +++ /dev/null @@ -1,100 +0,0 @@ -if isinstance(i, str): - #? str() - i - -if isinstance(j, (str, int)): - #? str() int() - j - -while isinstance(k, (str, int)): - #? str() int() - k - -if not isinstance(k, (str, int)): - #? - k - -while not isinstance(k, (str, int)): - #? - k - -assert isinstance(ass, int) -#? int() -ass - -assert isinstance(ass, str) -assert not isinstance(ass, int) - -if 2: - #? str() - ass - -# ----------------- -# invalid arguments -# ----------------- - -if isinstance(wrong, str()): - #? - wrong - -# ----------------- -# in functions -# ----------------- - -import datetime - - -def fooooo(obj): - if isinstance(obj, datetime.datetime): - #? datetime.datetime() - obj - - -def fooooo2(obj): - if isinstance(obj, datetime.date): - return obj - else: - return 1 - -a -# In earlier versions of Jedi, this returned both datetime and int, but now -# Jedi does flow checks and realizes that the top return isn't executed. -#? int() -fooooo2('') - - -def isinstance_func(arr): - for value in arr: - if isinstance(value, dict): - # Shouldn't fail, even with the dot. - #? 17 dict() - value. - elif isinstance(value, int): - x = value - #? int() - x - -# ----------------- -# Names with multiple indices. -# ----------------- - -class Test(): - def __init__(self, testing): - if isinstance(testing, str): - self.testing = testing - else: - self.testing = 10 - - def boo(self): - if isinstance(self.testing, str): - #? str() - self.testing - #? Test() - self - -# ----------------- -# Syntax -# ----------------- - -#? -isinstance(1, int()) diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/completion/keywords.py b/vim-plugins/bundle/jedi-vim/jedi/test/completion/keywords.py deleted file mode 100644 index 9631e8d..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/completion/keywords.py +++ /dev/null @@ -1,59 +0,0 @@ - -#? ['raise'] -raise - -#? ['Exception'] -except - -#? [] -b + continu - -#? [] -b + continue - -#? ['continue'] -b; continue - -#? ['continue'] -b; continu - -#? [] -c + brea - -#? [] -a + break - -#? ['break'] -b; break - -# ----------------- -# Keywords should not appear everywhere. -# ----------------- - -#? [] -with open() as f -#? [] -def i -#? [] -class i - -#? [] -continue i - -# More syntax details, e.g. while only after newline, but not after semicolon, -# continue also after semicolon -#? ['while'] -while -#? [] -x while -#? [] -x; while -#? ['continue'] -x; continue - -#? [] -and -#? ['and'] -x and -#? [] -x * and diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/completion/lambdas.py b/vim-plugins/bundle/jedi-vim/jedi/test/completion/lambdas.py deleted file mode 100644 index d739169..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/completion/lambdas.py +++ /dev/null @@ -1,106 +0,0 @@ -# ----------------- -# lambdas -# ----------------- -a = lambda: 3 -#? int() -a() - -x = [] -a = lambda x: x -#? int() -a(0) - -#? float() -(lambda x: x)(3.0) - -arg_l = lambda x, y: y, x -#? float() -arg_l[0]('', 1.0) -#? list() -arg_l[1] - -arg_l = lambda x, y: (y, x) -args = 1,"" -result = arg_l(*args) -#? tuple() -result -#? str() -result[0] -#? int() -result[1] - -def with_lambda(callable_lambda, *args, **kwargs): - return callable_lambda(1, *args, **kwargs) - -#? int() -with_lambda(arg_l, 1.0)[1] -#? float() -with_lambda(arg_l, 1.0)[0] -#? float() -with_lambda(arg_l, y=1.0)[0] -#? int() -with_lambda(lambda x: x) -#? float() -with_lambda(lambda x, y: y, y=1.0) - -arg_func = lambda *args, **kwargs: (args[0], kwargs['a']) -#? int() -arg_func(1, 2, a='', b=10)[0] -#? list() -arg_func(1, 2, a=[], b=10)[1] - -# magic method -a = lambda: 3 -#? ['__closure__'] -a.__closure__ - -class C(): - def __init__(self, foo=1.0): - self.a = lambda: 1 - self.foo = foo - - def ret(self): - return lambda: self.foo - - def with_param(self): - return lambda x: x + self.a() - -#? int() -C().a() - -#? str() -C('foo').ret()() - -index = C().with_param()(1) -#? float() -['', 1, 1.0][index] - - -def xy(param): - def ret(a, b): - return a + b - - return lambda b: ret(param, b) - -#? int() -xy(1)(2) - -# ----------------- -# lambda param (#379) -# ----------------- -class Test(object): - def __init__(self, pred=lambda a, b: a): - self.a = 1 - #? int() - self.a - #? float() - pred(1.0, 2) - -# ----------------- -# test_nocond in grammar (happens in list comprehensions with `if`) -# ----------------- -# Doesn't need to do anything yet. It should just not raise an error. These -# nocond lambdas make no sense at all. - -#? int() -[a for a in [1,2] if lambda: 3][0] diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/completion/named_param.py b/vim-plugins/bundle/jedi-vim/jedi/test/completion/named_param.py deleted file mode 100644 index b420df1..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/completion/named_param.py +++ /dev/null @@ -1,48 +0,0 @@ -""" -Named Params: ->>> def a(abc): pass -... ->>> a(abc=3) # <- this stuff (abc) -""" - -def a(abc): - pass - -#? 5 ['abc'] -a(abc) - - -def a(*some_args, **some_kwargs): - pass - -#? 11 [] -a(some_args) - -#? 13 [] -a(some_kwargs) - -def multiple(foo, bar): - pass - -#? 17 ['bar'] -multiple(foo, bar) - -#? ['bar'] -multiple(foo, bar - -my_lambda = lambda lambda_param: lambda_param + 1 -#? 22 ['lambda_param'] -my_lambda(lambda_param) - -# __call__ -class Test(object): - def __init__(self, hello_other): - pass - - def __call__(self, hello): - pass - -#? 12 ['hello'] -Test()(hello=) -#? 11 [] -Test()(self=) diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/completion/on_import.py b/vim-plugins/bundle/jedi-vim/jedi/test/completion/on_import.py deleted file mode 100644 index dfaad45..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/completion/on_import.py +++ /dev/null @@ -1,108 +0,0 @@ -def from_names(): - #? ['mod1'] - from import_tree.pkg. - #? ['path'] - from os. - -def from_names_goto(): - from import_tree import pkg - #? pkg - from import_tree.pkg - -def builtin_test(): - #? ['math'] - import math - -# ----------------- -# completions within imports -# ----------------- - -#? ['sqlite3'] -import sqlite3 - -#? ['classes'] -import classes - -#? ['timedelta'] -from datetime import timedel -#? 21 [] -from datetime.timedel import timedel - -# should not be possible, because names can only be looked up 1 level deep. -#? [] -from datetime.timedelta import resolution -#? [] -from datetime.timedelta import - -#? ['Cursor'] -from sqlite3 import Cursor - -#? ['some_variable'] -from . import some_variable -#? ['arrays'] -from . import arrays -#? [] -from . import import_tree as ren - -import os -#? os.path.join -from os.path import join - -# ----------------- -# special positions -> edge cases -# ----------------- -import datetime - -#? 6 datetime -from datetime.time import time - -#? [] -import datetime. -#? [] -import datetime.date - -#? 21 ['import'] -from import_tree.pkg import pkg -#? 49 ['a', '__name__', '__doc__', '__file__', '__package__'] -from import_tree.pkg.mod1 import not_existant, # whitespace before -#? ['a', '__name__', '__doc__', '__file__', '__package__'] -from import_tree.pkg.mod1 import not_existant, -#? 22 ['mod1'] -from import_tree.pkg. import mod1 -#? 17 ['mod1', 'mod2', 'random', 'pkg', 'rename1', 'rename2', 'recurse_class1', 'recurse_class2', 'invisible_pkg', 'flow_import'] -from import_tree. import pkg - -#? 18 ['pkg'] -from import_tree.p import pkg - -#? 17 ['import_tree'] -from .import_tree import -#? 10 ['run'] -from ..run import -#? ['run'] -from ..run -#? 10 ['run'] -from ..run. -#? [] -from ..run. - -#? ['run'] -from .. import run - -#? [] -from not_a_module import - - -#137 -import json -#? 23 json.dump -from json import load, dump -#? 17 json.load -from json import load, dump -# without the from clause: -import json, datetime -#? 7 json -import json, datetime -#? 13 datetime -import json, datetime - diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/completion/ordering.py b/vim-plugins/bundle/jedi-vim/jedi/test/completion/ordering.py deleted file mode 100644 index 61eb192..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/completion/ordering.py +++ /dev/null @@ -1,195 +0,0 @@ -# ----------------- -# normal -# ----------------- -a = "" -a = 1 - -#? int() -a -#? [] -a.append - -a = list - -b = 1; b = "" -#? str() -b - -# temp should not be accessible before definition -#? [] -temp - -a = 1 -temp = b; -b = a -a = temp -#? int() -b -#? int() -b -#? str() -a - -a = tuple -if 1: - a = list - -#? ['append'] -a.append -#? ['index'] -a.index - -# ----------------- -# tuples exchanges -# ----------------- -a, b = 1, "" -#? int() -a -#? str() -b - -b, a = a, b -#? int() -b -#? str() -a - -b, a = a, b -#? int() -a -#? str() -b - -# ----------------- -# function -# ----------------- -def a(a=3): - #? int() - a - #? [] - a.func - return a - -#? int() -a(2) -#? [] -a(2).func - -a_param = 3 -def func(a_param): - # should not be int - #? [] - a_param. - -from os import path - - -# should not return a function, because `a` is a function above -def f(b, a): return a -#? [] -f(b=3). - -# ----------------- -# closure -# ----------------- - -def x(): - a = 0 - - def x(): - return a - - a = 3.0 - return x() - -#? float() -x() - -# ----------------- -# class -# ----------------- -class A(object): - a = "" - a = 3 - #? int() - a - a = list() - def __init__(self): - self.b = "" - - def before(self): - self.b = 3 - # TODO should this be so? include entries after cursor? - #? int() str() list - self.b - self.b = list - - self.a = 1 - #? str() int() - self.a - - #? ['after'] - self.after - - self.c = 3 - #? int() - self.c - - def after(self): - self.a = '' - - c = set() - -#? list() -A.a - -a = A() -#? ['after'] -a.after -#? [] -a.upper -#? [] -a.append -#? [] -a.real - -#? str() int() -a.a - -a = 3 -class a(): - def __init__(self, a): - self.a = a - -#? float() -a(1.0).a -#? -a().a - -# ----------------- -# imports -# ----------------- - -math = 3 -import math -#? ['cosh'] -math.cosh -#? [] -math.real - -math = 3 -#? int() -math -#? [] -math.cos - -# do the same for star imports -cosh = 3 -from math import * -# cosh doesn't work, but that's not a problem, star imports should be at the -# start of EVERY script! -cosh.real - -cosh = 3 -#? int() -cosh diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/completion/parser.py b/vim-plugins/bundle/jedi-vim/jedi/test/completion/parser.py deleted file mode 100644 index 68793f4..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/completion/parser.py +++ /dev/null @@ -1,43 +0,0 @@ -""" -Issues with the parser and not the type inference should be part of this file. -""" - -class IndentIssues(): - """ - issue jedi-vim#288 - Which is really a fast parser issue. It used to start a new block at the - parentheses, because it had problems with the indentation. - """ - def one_param( - self, - ): - return 1 - - def with_param( - self, - y): - return y - - - -#? int() -IndentIssues().one_param() - -#? str() -IndentIssues().with_param('') - - -""" -Just because there's a def keyword, doesn't mean it should not be able to -complete to definition. -""" -definition = 0 -#? ['definition'] -str(def - - -# It might be hard to determine the context -class Foo(object): - @property - #? ['str'] - def bar(str diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/completion/pep0484.py b/vim-plugins/bundle/jedi-vim/jedi/test/completion/pep0484.py deleted file mode 100644 index b944cd1..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/completion/pep0484.py +++ /dev/null @@ -1,160 +0,0 @@ -""" Pep-0484 type hinting """ - -# python >= 3.2 - - -class A(): - pass - - -def function_parameters(a: A, b, c: str, d: int, e: str, f: str, g: int=4): - """ - :param e: if docstring and annotation agree, only one should be returned - :type e: str - :param f: if docstring and annotation disagree, both should be returned - :type f: int - """ - #? A() - a - #? - b - #? str() - c - #? int() - d - #? str() - e - #? int() str() - f - # int() - g - - -def return_unspecified(): - pass - -#? -return_unspecified() - - -def return_none() -> None: - """ - Return type None means the same as no return type as far as jedi - is concerned - """ - pass - -#? -return_none() - - -def return_str() -> str: - pass - -#? str() -return_str() - - -def return_custom_class() -> A: - pass - -#? A() -return_custom_class() - - -def return_annotation_and_docstring() -> str: - """ - :rtype: int - """ - pass - -#? str() int() -return_annotation_and_docstring() - - -def return_annotation_and_docstring_different() -> str: - """ - :rtype: str - """ - pass - -#? str() -return_annotation_and_docstring_different() - - -def annotation_forward_reference(b: "B") -> "B": - #? B() - b - -#? ["test_element"] -annotation_forward_reference(1).t - -class B: - test_element = 1 - pass - -#? B() -annotation_forward_reference(1) - - -class SelfReference: - test_element = 1 - def test_method(self, x: "SelfReference") -> "SelfReference": - #? SelfReference() - x - #? ["test_element", "test_method"] - self.t - #? ["test_element", "test_method"] - x.t - #? ["test_element", "test_method"] - self.test_method(1).t - -#? SelfReference() -SelfReference().test_method() - -def function_with_non_pep_0484_annotation( - x: "I can put anything here", - xx: "", - yy: "\r\n\0;+*&^564835(---^&*34", - y: 3 + 3, - zz: float) -> int("42"): - # infers int from function call - #? int() - x - # infers int from function call - #? int() - xx - # infers int from function call - #? int() - yy - # infers str from function call - #? str() - y - #? float() - zz -#? -function_with_non_pep_0484_annotation(1, 2, 3, "force string") - -def function_forward_reference_dynamic( - x: return_str_type(), - y: "return_str_type()") -> None: - #? - x - #? str() - y - -def return_str_type(): - return str - - -X = str -def function_with_assined_class_in_reference(x: X, y: "Y"): - #? str() - x - #? int() - y -Y = int - -def just_because_we_can(x: "flo" + "at"): - #? float() - x diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/completion/pep0484_comments.py b/vim-plugins/bundle/jedi-vim/jedi/test/completion/pep0484_comments.py deleted file mode 100644 index 7d5f7c2..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/completion/pep0484_comments.py +++ /dev/null @@ -1,109 +0,0 @@ -a = 3 # type: str -#? str() -a - -b = 3 # type: str but I write more -#? int() -b - -c = 3 # type: str # I comment more -#? str() -c - -d = "It should not read comments from the next line" -# type: int -#? str() -d - -# type: int -e = "It should not read comments from the previous line" -#? str() -e - -class BB: pass - -def test(a, b): - a = a # type: BB - c = a # type: str - d = a - # type: str - e = a # type: str # Should ignore long whitespace - - #? BB() - a - #? str() - c - #? BB() - d - #? str() - e - -a,b = 1, 2 # type: str, float -#? str() -a -#? float() -b - -class Employee: - pass - -# The typing library is not installable for Python 2.6, therefore ignore the -# following tests. -# python >= 2.7 - -from typing import List -x = [] # type: List[Employee] -#? Employee() -x[1] -x, y, z = [], [], [] # type: List[int], List[int], List[str] -#? int() -y[2] -x, y, z = [], [], [] # type: (List[float], List[float], List[BB]) -for zi in z: - #? BB() - zi - -x = [ - 1, - 2, -] # type: List[str] - -#? str() -x[1] - - -for bar in foo(): # type: str - #? str() - bar - -for bar, baz in foo(): # type: int, float - #? int() - bar - #? float() - baz - -for bar, baz in foo(): - # type: str, str - """ type hinting on next line should not work """ - #? - bar - #? - baz - -with foo(): # type: int - ... - -with foo() as f: # type: str - #? str() - f - -with foo() as f: - # type: str - """ type hinting on next line should not work """ - #? - f - -aaa = some_extremely_long_function_name_that_doesnt_leave_room_for_hints() \ - # type: float # We should be able to put hints on the next line with a \ -#? float() -aaa diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/completion/pep0484_typing.py b/vim-plugins/bundle/jedi-vim/jedi/test/completion/pep0484_typing.py deleted file mode 100644 index 75c1c0b..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/completion/pep0484_typing.py +++ /dev/null @@ -1,263 +0,0 @@ -""" -Test the typing library, with docstrings. This is needed since annotations -are not supported in python 2.7 else then annotating by comment (and this is -still TODO at 2016-01-23) -""" -# There's no Python 2.6 typing module. -# python >= 2.7 -import typing -class B: - pass - -def we_can_has_sequence(p, q, r, s, t, u): - """ - :type p: typing.Sequence[int] - :type q: typing.Sequence[B] - :type r: typing.Sequence[int] - :type s: typing.Sequence["int"] - :type t: typing.MutableSequence[dict] - :type u: typing.List[float] - """ - #? ["count"] - p.c - #? int() - p[1] - #? ["count"] - q.c - #? B() - q[1] - #? ["count"] - r.c - #? int() - r[1] - #? ["count"] - s.c - #? int() - s[1] - #? [] - s.a - #? ["append"] - t.a - #? dict() - t[1] - #? ["append"] - u.a - #? float() - u[1] - -def iterators(ps, qs, rs, ts): - """ - :type ps: typing.Iterable[int] - :type qs: typing.Iterator[str] - :type rs: typing.Sequence["ForwardReference"] - :type ts: typing.AbstractSet["float"] - """ - for p in ps: - #? int() - p - #? - next(ps) - a, b = ps - #? int() - a - ##? int() --- TODO fix support for tuple assignment - # https://github.com/davidhalter/jedi/pull/663#issuecomment-172317854 - # test below is just to make sure that in case it gets fixed by accident - # these tests will be fixed as well the way they should be - #? - b - - for q in qs: - #? str() - q - #? str() - next(qs) - for r in rs: - #? ForwardReference() - r - #? - next(rs) - for t in ts: - #? float() - t - -def sets(p, q): - """ - :type p: typing.AbstractSet[int] - :type q: typing.MutableSet[float] - """ - #? [] - p.a - #? ["add"] - q.a - -def tuple(p, q, r): - """ - :type p: typing.Tuple[int] - :type q: typing.Tuple[int, str, float] - :type r: typing.Tuple[B, ...] - """ - #? int() - p[0] - #? int() - q[0] - #? str() - q[1] - #? float() - q[2] - #? B() - r[0] - #? B() - r[1] - #? B() - r[2] - #? B() - r[10000] - i, s, f = q - #? int() - i - ##? str() --- TODO fix support for tuple assignment - # https://github.com/davidhalter/jedi/pull/663#issuecomment-172317854 - #? - s - ##? float() --- TODO fix support for tuple assignment - # https://github.com/davidhalter/jedi/pull/663#issuecomment-172317854 - #? - f - -class Key: - pass - -class Value: - pass - -def mapping(p, q, d, r, s, t): - """ - :type p: typing.Mapping[Key, Value] - :type q: typing.MutableMapping[Key, Value] - :type d: typing.Dict[Key, Value] - :type r: typing.KeysView[Key] - :type s: typing.ValuesView[Value] - :type t: typing.ItemsView[Key, Value] - """ - #? [] - p.setd - #? ["setdefault"] - q.setd - #? ["setdefault"] - d.setd - #? Value() - p[1] - for key in p: - #? Key() - key - for key in p.keys(): - #? Key() - key - for value in p.values(): - #? Value() - value - for item in p.items(): - #? Key() - item[0] - #? Value() - item[1] - (key, value) = item - #? Key() - key - #? Value() - value - for key, value in p.items(): - #? Key() - key - #? Value() - value - for key in r: - #? Key() - key - for value in s: - #? Value() - value - for key, value in t: - #? Key() - key - #? Value() - value - -def union(p, q, r, s, t): - """ - :type p: typing.Union[int] - :type q: typing.Union[int, int] - :type r: typing.Union[int, str, "int"] - :type s: typing.Union[int, typing.Union[str, "typing.Union['float', 'dict']"]] - :type t: typing.Union[int, None] - """ - #? int() - p - #? int() - q - #? int() str() - r - #? int() str() float() dict() - s - #? int() - t - -def optional(p): - """ - :type p: typing.Optional[int] - Optional does not do anything special. However it should be recognised - as being of that type. Jedi doesn't do anything with the extra into that - it can be None as well - """ - #? int() - p - -class ForwardReference: - pass - -class TestDict(typing.Dict[str, int]): - def setdud(self): - pass - -def testdict(x): - """ - :type x: TestDict - """ - #? ["setdud", "setdefault"] - x.setd - for key in x.keys(): - #? str() - key - for value in x.values(): - #? int() - value - -x = TestDict() -#? ["setdud", "setdefault"] -x.setd -for key in x.keys(): - #? str() - key -for value in x.values(): - #? int() - value -# python >= 3.2 -""" -docstrings have some auto-import, annotations can use all of Python's -import logic -""" -import typing as t -def union2(x: t.Union[int, str]): - #? int() str() - x - -from typing import Union -def union3(x: Union[int, str]): - #? int() str() - x - -from typing import Union as U -def union4(x: U[int, str]): - #? int() str() - x diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/completion/precedence.py b/vim-plugins/bundle/jedi-vim/jedi/test/completion/precedence.py deleted file mode 100644 index 6078115..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/completion/precedence.py +++ /dev/null @@ -1,138 +0,0 @@ -""" -Test Jedi's operation understanding. Jedi should understand simple additions, -multiplications, etc. -""" -# ----------------- -# numbers -# ----------------- -x = [1, 'a', 1.0] - -#? int() str() float() -x[12] - -#? float() -x[1 + 1] - -index = 0 + 1 - -#? str() -x[index] - -#? int() -x[1 + (-1)] - -def calculate(number): - return number + constant - -constant = 1 - -#? float() -x[calculate(1)] - -def calculate(number): - return number + constant - -# ----------------- -# strings -# ----------------- - -x = 'upp' + 'e' - -#? str.upper -getattr(str, x + 'r') - -a = "a"*3 -#? str() -a -a = 3 * "a" -#? str() -a - -a = 3 * "a" -#? str() -a - -#? int() -(3 ** 3) -#? int() str() -(3 ** 'a') - -# ----------------- -# assignments -# ----------------- - -x = [1, 'a', 1.0] - -i = 0 -i += 1 -i += 1 -#? float() -x[i] - -i = 1 -i += 1 -i -= 3 -i += 1 -#? int() -x[i] - -# ----------------- -# in -# ----------------- - -if 'X' in 'Y': - a = 3 -else: - a = '' -# For now don't really check for truth values. So in should return both -# results. -#? str() int() -a - -# ----------------- -# for flow assignments -# ----------------- - -class FooBar(object): - fuu = 0.1 - raboof = 'fourtytwo' - -# targets should be working -target = '' -for char in ['f', 'u', 'u']: - target += char -#? float() -getattr(FooBar, target) - -# github #24 -target = u'' -for char in reversed(['f', 'o', 'o', 'b', 'a', 'r']): - target += char - -#? str() -getattr(FooBar, target) - - -# ----------------- -# repetition problems -> could be very slow and memory expensive - shouldn't -# be. -# ----------------- - -b = [str(1)] -l = list -for x in [l(0), l(1), l(2), l(3), l(4), l(5), l(6), l(7), l(8), l(9), l(10), - l(11), l(12), l(13), l(14), l(15), l(16), l(17), l(18), l(19), l(20), - l(21), l(22), l(23), l(24), l(25), l(26), l(27), l(28), l(29)]: - b += x - -#? str() -b[1] - - -# ----------------- -# undefined names -# ----------------- -a = foobarbaz + 'hello' - -#? int() float() -{'hello': 1, 'bar': 1.0}[a] diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/completion/recursion.py b/vim-plugins/bundle/jedi-vim/jedi/test/completion/recursion.py deleted file mode 100644 index 77e5b24..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/completion/recursion.py +++ /dev/null @@ -1,51 +0,0 @@ -""" -Code that might cause recursion issues (or has caused in the past). -""" - -def Recursion(): - def recurse(self): - self.a = self.a - self.b = self.b.recurse() - -#? -Recursion().a - -#? -Recursion().b - - -class X(): - def __init__(self): - self.recursive = [1, 3] - - def annoying(self): - self.recursive = [self.recursive[0]] - - def recurse(self): - self.recursive = [self.recursive[1]] - -#? int() -X().recursive[0] - - -def to_list(iterable): - return list(set(iterable)) - - -def recursion1(foo): - return to_list(to_list(foo)) + recursion1(foo) - -#? int() -recursion1([1,2])[0] - - -class FooListComp(): - def __init__(self): - self.recursive = [1] - - def annoying(self): - self.recursive = [x for x in self.recursive] - - -#? int() -FooListComp().recursive[0] diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/completion/stdlib.py b/vim-plugins/bundle/jedi-vim/jedi/test/completion/stdlib.py deleted file mode 100644 index 92b7929..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/completion/stdlib.py +++ /dev/null @@ -1,224 +0,0 @@ -""" -std library stuff -""" - -# ----------------- -# builtins -# ----------------- -arr = [''] - -#? str() -sorted(arr)[0] - -#? str() -next(reversed(arr)) -next(reversed(arr)) - -# should not fail if there's no return value. -def yielder(): - yield None - -#? None -next(reversed(yielder())) - -# empty reversed should not raise an error -#? -next(reversed()) - -#? str() -next(open('')) - -#? int() -{'a':2}.setdefault('a', 3) - -# Compiled classes should have the meta class attributes. -#? ['__itemsize__'] -tuple.__itemsize__ - -# ----------------- -# type() calls with one parameter -# ----------------- -#? int -type(1) -#? int -type(int()) -#? type -type(int) -#? type -type(type) -#? list -type([]) - -def x(): - yield 1 -generator = type(x()) -#? generator -type(x for x in []) -#? type(x) -type(lambda: x) - -import math -import os -#? type(os) -type(math) -class X(): pass -#? type -type(X) - -# ----------------- -# enumerate -# ----------------- -for i, j in enumerate(["as", "ad"]): - #? int() - i - #? str() - j - -# ----------------- -# re -# ----------------- -import re -c = re.compile(r'a') -# re.compile should not return str -> issue #68 -#? [] -c.startswith -#? int() -c.match().start() - -#? int() -re.match(r'a', 'a').start() - -for a in re.finditer('a', 'a'): - #? int() - a.start() - -#? str() -re.sub('a', 'a') - -# ----------------- -# ref -# ----------------- -import weakref - -#? int() -weakref.proxy(1) - -#? weakref.ref() -weakref.ref(1) -#? int() -weakref.ref(1)() - -# ----------------- -# functools -# ----------------- -import functools - -basetwo = functools.partial(int, base=2) -#? int() -basetwo() - -def function(a, b): - return a, b -a = functools.partial(function, 0) - -#? int() -a('')[0] -#? str() -a('')[1] - -kw = functools.partial(function, b=1.0) -tup = kw(1) -#? int() -tup[0] -#? float() -tup[1] - -def my_decorator(f): - @functools.wraps(f) - def wrapper(*args, **kwds): - return f(*args, **kwds) - return wrapper - -@my_decorator -def example(a): - return a - -#? str() -example('') - - -# ----------------- -# sqlite3 (#84) -# ----------------- - -import sqlite3 -#? sqlite3.Connection() -con = sqlite3.connect() -#? sqlite3.Cursor() -c = con.cursor() -#? sqlite3.Row() -row = c.fetchall()[0] -#? str() -row.keys()[0] - -def huhu(db): - """ - :type db: sqlite3.Connection - :param db: the db connection - """ - #? sqlite3.Connection() - db - -# ----------------- -# hashlib -# ----------------- - -import hashlib - -#? ['md5'] -hashlib.md5 - -# ----------------- -# copy -# ----------------- - -import copy -#? int() -copy.deepcopy(1) - -#? -copy.copy() - -# ----------------- -# json -# ----------------- - -# We don't want any results for json, because it depends on IO. -import json -#? -json.load('asdf') -#? -json.loads('[1]') - -# ----------------- -# random -# ----------------- - -import random -class A(object): - def say(self): pass -class B(object): - def shout(self): pass -cls = random.choice([A, B]) -#? ['say', 'shout'] -cls().s - -# ----------------- -# random -# ----------------- - -import zipfile -z = zipfile.ZipFile("foo") -# It's too slow. So we don't run it at the moment. -##? ['upper'] -z.read('name').upper diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/completion/sys_path.py b/vim-plugins/bundle/jedi-vim/jedi/test/completion/sys_path.py deleted file mode 100644 index ebaccc2..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/completion/sys_path.py +++ /dev/null @@ -1,25 +0,0 @@ - -import sys -import os -from os import dirname - -sys.path.insert(0, '../../jedi') -sys.path.append(dirname(os.path.abspath('thirdparty' + os.path.sep + 'asdf'))) - -# modifications, that should fail: -# because of sys module -sys.path.append(sys.path[1] + '/thirdparty') -# syntax err -sys.path.append('a' +* '/thirdparty') - -#? ['evaluate'] -import evaluate - -#? ['Evaluator'] -evaluate.Evaluator - -#? ['jedi_'] -import jedi_ - -#? ['el'] -jedi_.el diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/completion/thirdparty/PyQt4_.py b/vim-plugins/bundle/jedi-vim/jedi/test/completion/thirdparty/PyQt4_.py deleted file mode 100644 index f4e4183..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/completion/thirdparty/PyQt4_.py +++ /dev/null @@ -1,19 +0,0 @@ -from PyQt4.QtCore import * -from PyQt4.QtGui import * - -#? ['QActionGroup'] -QActionGroup - -#? ['currentText'] -QStyleOptionComboBox().currentText - -#? [] -QStyleOptionComboBox().currentText. - -from PyQt4 import QtGui - -#? ['currentText'] -QtGui.QStyleOptionComboBox().currentText - -#? [] -QtGui.QStyleOptionComboBox().currentText. diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/completion/thirdparty/django_.py b/vim-plugins/bundle/jedi-vim/jedi/test/completion/thirdparty/django_.py deleted file mode 100644 index 9914a6d..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/completion/thirdparty/django_.py +++ /dev/null @@ -1,11 +0,0 @@ -#! ['class ObjectDoesNotExist'] -from django.core.exceptions import ObjectDoesNotExist -import django - -#? ['get_version'] -django.get_version - -from django.conf import settings - -#? ['configured'] -settings.configured diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/completion/thirdparty/jedi_.py b/vim-plugins/bundle/jedi-vim/jedi/test/completion/thirdparty/jedi_.py deleted file mode 100644 index dc384b1..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/completion/thirdparty/jedi_.py +++ /dev/null @@ -1,52 +0,0 @@ - -from jedi import functions, evaluate, parsing - -el = functions.completions()[0] -#? ['description'] -el.description - -#? str() -el.description - - -scopes, path, dot, like = \ - api._prepare_goto(source, row, column, path, True) - -# has problems with that (sometimes) very deep nesting. -#? set() -el = scopes - -# get_names_for_scope is also recursion stuff -#? tuple() -el = list(evaluate.get_names_for_scope())[0] - -#? int() parsing.Module() -el = list(evaluate.get_names_for_scope(1))[0][0] -#? parsing.Module() -el = list(evaluate.get_names_for_scope())[0][0] - -#? list() -el = list(evaluate.get_names_for_scope(1))[0][1] -#? list() -el = list(evaluate.get_names_for_scope())[0][1] - -#? list() -parsing.Scope((0,0)).get_set_vars() -#? parsing.Import() parsing.Name() -parsing.Scope((0,0)).get_set_vars()[0] -# TODO access parent is not possible, because that is not set in the class -## parsing.Class() -parsing.Scope((0,0)).get_set_vars()[0].parent - -#? parsing.Import() parsing.Name() -el = list(evaluate.get_names_for_scope())[0][1][0] - -#? evaluate.Array() evaluate.Class() evaluate.Function() evaluate.Instance() -list(evaluate.follow_call())[0] - -# With the right recursion settings, this should be possible (and maybe more): -# Array Class Function Generator Instance Module -# However, this was produced with the recursion settings 10/350/10000, and -# lasted 18.5 seconds. So we just have to be content with the results. -#? evaluate.Class() evaluate.Function() -evaluate.get_scopes_for_name()[0] diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/completion/thirdparty/psycopg2_.py b/vim-plugins/bundle/jedi-vim/jedi/test/completion/thirdparty/psycopg2_.py deleted file mode 100644 index 834704b..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/completion/thirdparty/psycopg2_.py +++ /dev/null @@ -1,11 +0,0 @@ -import psycopg2 - -conn = psycopg2.connect('dbname=test') - -#? ['cursor'] -conn.cursor - -cur = conn.cursor() - -#? ['fetchall'] -cur.fetchall diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/completion/thirdparty/pylab_.py b/vim-plugins/bundle/jedi-vim/jedi/test/completion/thirdparty/pylab_.py deleted file mode 100644 index ab132a4..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/completion/thirdparty/pylab_.py +++ /dev/null @@ -1,36 +0,0 @@ -import pylab - -# two gotos -#! ['module numpy'] -import numpy - -#! ['module random'] -import numpy.random - -#? ['array2string'] -numpy.array2string - -#? ['shape'] -numpy.matrix().shape - -#? ['random_integers'] -pylab.random_integers - -#? [] -numpy.random_integers - -#? ['random_integers'] -numpy.random.random_integers -#? ['sample'] -numpy.random.sample - -import numpy -na = numpy.array([1,2]) -#? ['shape'] -na.shape - -# shouldn't raise an error #29, jedi-vim -# doesn't return something, because matplotlib uses __import__ -fig = pylab.figure() -#? -fig.add_subplot diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/completion/types.py b/vim-plugins/bundle/jedi-vim/jedi/test/completion/types.py deleted file mode 100644 index 768b660..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/completion/types.py +++ /dev/null @@ -1,127 +0,0 @@ -# ----------------- -# non array -# ----------------- - -#? ['imag'] -int.imag - -#? [] -int.is_integer - -#? ['is_integer'] -float.is_int - -#? ['is_integer'] -1.0.is_integer - -#? ['upper'] -"".upper - -#? ['upper'] -r"".upper - -# strangely this didn't work, because the = is used for assignments -#? ['upper'] -"=".upper -a = "=" -#? ['upper'] -a.upper - - -# ----------------- -# lists -# ----------------- -arr = [] -#? ['append'] -arr.app - -#? ['append'] -list().app -#? ['append'] -[].append - -arr2 = [1,2,3] -#? ['append'] -arr2.app - -#? int() -arr.count(1) - -x = [] -#? -x.pop() -x = [3] -#? int() -x.pop() -x = [] -x.append(1.0) -#? float() -x.pop() - -# ----------------- -# dicts -# ----------------- -dic = {} - -#? ['copy', 'clear'] -dic.c - -dic2 = dict(a=1, b=2) -#? ['pop', 'popitem'] -dic2.p -#? ['popitem'] -{}.popitem - -dic2 = {'asdf': 3} -#? ['popitem'] -dic2.popitem - -#? int() -dic2['asdf'] - -d = {'a': 3, 1.0: list} - -#? int() list -d.values()[0] -##? int() list -dict(d).values()[0] - -#? str() -d.items()[0][0] -#? int() -d.items()[0][1] - -# ----------------- -# set -# ----------------- -set_t = {1,2} - -#? ['clear', 'copy'] -set_t.c - -set_t2 = set() - -#? ['clear', 'copy'] -set_t2.c - -# ----------------- -# tuples -# ----------------- -tup = ('',2) - -#? ['count'] -tup.c - -tup2 = tuple() -#? ['index'] -tup2.i -#? ['index'] -().i - -tup3 = 1,"" -#? ['index'] -tup3.index - -tup4 = 1,"" -#? ['index'] -tup4.index diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/completion/usages.py b/vim-plugins/bundle/jedi-vim/jedi/test/completion/usages.py deleted file mode 100644 index 3805152..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/completion/usages.py +++ /dev/null @@ -1,275 +0,0 @@ -""" -Renaming tests. This means search for usages. -I always leave a little bit of space to add room for additions, because the -results always contain position informations. -""" -#< 4 (0,4), (3,0), (5,0), (17,0), (12,4), (14,5), (15,0) -def abc(): pass - -#< 0 (-3,4), (0,0), (2,0), (14,0), (9,4), (11,5), (12,0) -abc.d.a.bsaasd.abc.d - -abc -# unicode chars shouldn't be a problem. -x['smörbröd'].abc - -# With the new parser these statements are not recognized as stateents, because -# they are not valid Python. -if 1: - abc = -else: - (abc) = -abc = -#< (-17,4), (-14,0), (-12,0), (0,0), (-2,0), (-3,5), (-5,4) -abc - -abc = 5 - - -Abc = 3 - -#< 6 (0,6), (2,4), (5,8), (17,0) -class Abc(): - #< (-2,6), (0,4), (3,8), (15,0) - Abc - - def Abc(self): - Abc; self.c = 3 - - #< 17 (0,16), (2,8) - def a(self, Abc): - #< 10 (-2,16), (0,8) - Abc - - #< 19 (0,18), (2,8) - def self_test(self): - #< 12 (-2,18), (0,8) - self.b - -Abc.d.Abc - - -#< 4 (0,4), (5,1) -def blubi(): - pass - - -#< (-5,4), (0,1) -@blubi -def a(): pass - - -#< 0 (0,0), (1,0) -set_object_var = object() -set_object_var.var = 1 - - -response = 5 -#< 0 (0,0), (1,0), (2,0), (4,0) -response = HttpResponse(mimetype='application/pdf') -response['Content-Disposition'] = 'attachment; filename=%s.pdf' % id -response.write(pdf) -#< (-4,0), (-3,0), (-2,0), (0,0) -response - - -# ----------------- -# imports -# ----------------- -#< (0,7), (3,0) -import module_not_exists - -#< (-3,7), (0,0) -module_not_exists - - -#< ('rename1', 1,0), (0,24), (3,0), (6,17), ('rename2', 4,5), (10,17), (13,17), ('imports', 72, 16) -from import_tree import rename1 - -#< (0,8), ('rename1',3,0), ('rename2',4,20), ('rename2',6,0), (3,32), (7,32), (4,0) -rename1.abc - -#< (-3,8), ('rename1', 3,0), ('rename2', 4,20), ('rename2', 6,0), (0,32), (4,32), (1,0) -from import_tree.rename1 import abc -abc - -#< 20 ('rename1', 1,0), ('rename2', 4,5), (-10,24), (-7,0), (-4,17), (0,17), (3,17), ('imports', 72, 16) -from import_tree.rename1 import abc - -#< (0, 32), -from import_tree.rename1 import not_existing - -# Shouldn't raise an error or do anything weird. -from not_existing import * - -# ----------------- -# classes -# ----------------- - -class TestMethods(object): - #< 8 (0,8), (2,13) - def a_method(self): - #< 13 (-2,8), (0,13) - self.a_method() - #< 13 (2,8), (0,13), (3,13) - self.b_method() - - def b_method(self): - self.b_method - - -class TestClassVar(object): - #< 4 (0,4), (5,13), (7,21) - class_v = 1 - def a(self): - class_v = 1 - - #< (-5,4), (0,13), (2,21) - self.class_v - #< (-7,4), (-2,13), (0,21) - TestClassVar.class_v - #< (0,8), (-7, 8) - class_v - -class TestInstanceVar(): - def a(self): - #< 13 (4,13), (0,13) - self._instance_var = 3 - - def b(self): - #< (-4,13), (0,13) - self._instance_var - # A call to self used to trigger an error, because it's also a trailer - # with two children. - self() - - -class NestedClass(): - def __getattr__(self, name): - return self - -# Shouldn't find a definition, because there's other `instance`. -# TODO reenable that test -##< (0, 14), -NestedClass().instance - - -# ----------------- -# inheritance -# ----------------- -class Super(object): - #< 4 (0,4), (23,18), (25,13) - base_class = 1 - #< 4 (0,4), - class_var = 1 - - #< 8 (0,8), - def base_method(self): - #< 13 (0,13), (20,13) - self.base_var = 1 - #< 13 (0,13), - self.instance_var = 1 - - #< 8 (0,8), - def just_a_method(self): pass - - -#< 20 (0,16), (-18,6) -class TestClass(Super): - #< 4 (0,4), - class_var = 1 - - def x_method(self): - - #< (0,18), (2,13), (-23,4) - TestClass.base_class - #< (-2,18), (0,13), (-25,4) - self.base_class - #< (-20,13), (0,13) - self.base_var - #< - TestClass.base_var - - - #< 13 (5,13), (0,13) - self.instance_var = 3 - - #< 9 (0,8), - def just_a_method(self): - #< (-5,13), (0,13) - self.instance_var - - -# ----------------- -# properties -# ----------------- -class TestProperty: - - @property - #< 10 (0,8), (5,13) - def prop(self): - return 1 - - def a(self): - #< 13 (-5,8), (0,13) - self.prop - - @property - #< 13 (0,8), (4,5) - def rw_prop(self): - return self._rw_prop - - #< 8 (-4,8), (0,5) - @rw_prop.setter - #< 8 (0,8), (5,13) - def rw_prop(self, value): - self._rw_prop = value - - def b(self): - #< 13 (-5,8), (0,13) - self.rw_prop - -# ----------------- -# *args, **kwargs -# ----------------- -#< 11 (1,11), (0,8) -def f(**kwargs): - return kwargs - - -# ----------------- -# No result -# ----------------- -if isinstance(j, int): - #< - j - -# ----------------- -# Dynamic Param Search -# ----------------- - -class DynamicParam(): - def foo(self): - return - -def check(instance): - #< 13 (-5,8), (0,13) - instance.foo() - -check(DynamicParam()) - -# ----------------- -# Compiled Objects -# ----------------- - -import _sre - -#< 0 (-3,7), (0,0), ('_sre', None, None) -_sre - -# ----------------- -# on syntax -# ----------------- - -#< 0 -import undefined diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/conftest.py b/vim-plugins/bundle/jedi-vim/jedi/test/conftest.py deleted file mode 100644 index ac04e26..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/conftest.py +++ /dev/null @@ -1,130 +0,0 @@ -import os -import re - -import pytest - -from . import helpers -from . import run -from . import refactor - -import jedi -from jedi.evaluate.analysis import Warning -from jedi import settings - - -def pytest_addoption(parser): - parser.addoption( - "--integration-case-dir", - default=os.path.join(helpers.test_dir, 'completion'), - help="Directory in which integration test case files locate.") - parser.addoption( - "--refactor-case-dir", - default=os.path.join(helpers.test_dir, 'refactor'), - help="Directory in which refactoring test case files locate.") - parser.addoption( - "--test-files", "-T", default=[], action='append', - help=( - "Specify test files using FILE_NAME[:LINE[,LINE[,...]]]. " - "For example: -T generators.py:10,13,19. " - "Note that you can use -m to specify the test case by id.")) - parser.addoption( - "--thirdparty", action='store_true', - help="Include integration tests that requires third party modules.") - - -def parse_test_files_option(opt): - """ - Parse option passed to --test-files into a key-value pair. - - >>> parse_test_files_option('generators.py:10,13,19') - ('generators.py', [10, 13, 19]) - """ - opt = str(opt) - if ':' in opt: - (f_name, rest) = opt.split(':', 1) - return (f_name, list(map(int, rest.split(',')))) - else: - return (opt, []) - - -def pytest_generate_tests(metafunc): - """ - :type metafunc: _pytest.python.Metafunc - """ - test_files = dict(map(parse_test_files_option, - metafunc.config.option.test_files)) - if 'case' in metafunc.fixturenames: - base_dir = metafunc.config.option.integration_case_dir - thirdparty = metafunc.config.option.thirdparty - cases = list(run.collect_dir_tests(base_dir, test_files)) - if thirdparty: - cases.extend(run.collect_dir_tests( - os.path.join(base_dir, 'thirdparty'), test_files, True)) - ids = ["%s:%s" % (c.module_name, c.line_nr_test) for c in cases] - metafunc.parametrize('case', cases, ids=ids) - - if 'refactor_case' in metafunc.fixturenames: - base_dir = metafunc.config.option.refactor_case_dir - metafunc.parametrize( - 'refactor_case', - refactor.collect_dir_tests(base_dir, test_files)) - - if 'static_analysis_case' in metafunc.fixturenames: - base_dir = os.path.join(os.path.dirname(__file__), 'static_analysis') - metafunc.parametrize( - 'static_analysis_case', - collect_static_analysis_tests(base_dir, test_files)) - - -def collect_static_analysis_tests(base_dir, test_files): - for f_name in os.listdir(base_dir): - files_to_execute = [a for a in test_files.items() if a[0] in f_name] - if f_name.endswith(".py") and (not test_files or files_to_execute): - path = os.path.join(base_dir, f_name) - yield StaticAnalysisCase(path) - - -class StaticAnalysisCase(object): - """ - Static Analysis cases lie in the static_analysis folder. - The tests also start with `#!`, like the goto_definition tests. - """ - def __init__(self, path): - self._path = path - with open(path) as f: - self._source = f.read() - - self.skip = False - for line in self._source.splitlines(): - self.skip = self.skip or run.skip_python_version(line) - - - def collect_comparison(self): - cases = [] - for line_nr, line in enumerate(self._source.splitlines(), 1): - match = re.match(r'(\s*)#! (\d+ )?(.*)$', line) - if match is not None: - column = int(match.group(2) or 0) + len(match.group(1)) - cases.append((line_nr + 1, column, match.group(3))) - return cases - - def run(self, compare_cb): - analysis = jedi.Script(self._source, path=self._path)._analysis() - typ_str = lambda inst: 'warning ' if isinstance(inst, Warning) else '' - analysis = [(r.line, r.column, typ_str(r) + r.name) - for r in analysis] - compare_cb(self, analysis, self.collect_comparison()) - - def __repr__(self): - return "<%s: %s>" % (self.__class__.__name__, os.path.basename(self._path)) - - -@pytest.fixture() -def isolated_jedi_cache(monkeypatch, tmpdir): - """ - Set `jedi.settings.cache_directory` to a temporary directory during test. - - Same as `clean_jedi_cache`, but create the temporary directory for - each test case (scope='function'). - """ - monkeypatch.setattr(settings, 'cache_directory', str(tmpdir)) diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/helpers.py b/vim-plugins/bundle/jedi-vim/jedi/test/helpers.py deleted file mode 100644 index 111b859..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/helpers.py +++ /dev/null @@ -1,40 +0,0 @@ -""" -A helper module for testing, improves compatibility for testing (as -``jedi._compatibility``) as well as introducing helper functions. -""" - -import sys -if sys.hexversion < 0x02070000: - import unittest2 as unittest -else: - import unittest -TestCase = unittest.TestCase - -import os -from os.path import abspath, dirname -import functools - -test_dir = dirname(abspath(__file__)) -root_dir = dirname(test_dir) - -sample_int = 1 # This is used in completion/imports.py - -def cwd_at(path): - """ - Decorator to run function at `path`. - - :type path: str - :arg path: relative path from repository root (e.g., ``'jedi'``). - """ - def decorator(func): - @functools.wraps(func) - def wrapper(*args, **kwds): - try: - oldcwd = os.getcwd() - repo_root = os.path.dirname(test_dir) - os.chdir(os.path.join(repo_root, path)) - return func(*args, **kwds) - finally: - os.chdir(oldcwd) - return wrapper - return decorator diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/refactor.py b/vim-plugins/bundle/jedi-vim/jedi/test/refactor.py deleted file mode 100755 index 9cc10fd..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/refactor.py +++ /dev/null @@ -1,99 +0,0 @@ -#!/usr/bin/env python -""" -Refactoring tests work a little bit similar to Black Box tests. But the idea is -here to compare two versions of code. **Note: Refactoring is currently not in -active development (and was never stable), the tests are therefore not really -valuable - just ignore them.** -""" -from __future__ import with_statement -import os -import re - -from functools import reduce -import jedi -from jedi import refactoring - - -class RefactoringCase(object): - - def __init__(self, name, source, line_nr, index, path, - new_name, start_line_test, desired): - self.name = name - self.source = source - self.line_nr = line_nr - self.index = index - self.path = path - self.new_name = new_name - self.start_line_test = start_line_test - self.desired = desired - - def refactor(self): - script = jedi.Script(self.source, self.line_nr, self.index, self.path) - f_name = os.path.basename(self.path) - refactor_func = getattr(refactoring, f_name.replace('.py', '')) - args = (self.new_name,) if self.new_name else () - return refactor_func(script, *args) - - def run(self): - refactor_object = self.refactor() - - # try to get the right excerpt of the newfile - f = refactor_object.new_files()[self.path] - lines = f.splitlines()[self.start_line_test:] - - end = self.start_line_test + len(lines) - pop_start = None - for i, l in enumerate(lines): - if l.startswith('# +++'): - end = i - break - elif '#? ' in l: - pop_start = i - lines.pop(pop_start) - self.result = '\n'.join(lines[:end - 1]).strip() - return self.result - - def check(self): - return self.run() == self.desired - - def __repr__(self): - return '<%s: %s:%s>' % (self.__class__.__name__, - self.name, self.line_nr - 1) - - -def collect_file_tests(source, path, lines_to_execute): - r = r'^# --- ?([^\n]*)\n((?:(?!\n# \+\+\+).)*)' \ - r'\n# \+\+\+((?:(?!\n# ---).)*)' - for match in re.finditer(r, source, re.DOTALL | re.MULTILINE): - name = match.group(1).strip() - first = match.group(2).strip() - second = match.group(3).strip() - start_line_test = source[:match.start()].count('\n') + 1 - - # get the line with the position of the operation - p = re.match(r'((?:(?!#\?).)*)#\? (\d*) ?([^\n]*)', first, re.DOTALL) - if p is None: - print("Please add a test start.") - continue - until = p.group(1) - index = int(p.group(2)) - new_name = p.group(3) - - line_nr = start_line_test + until.count('\n') + 2 - if lines_to_execute and line_nr - 1 not in lines_to_execute: - continue - - yield RefactoringCase(name, source, line_nr, index, path, - new_name, start_line_test, second) - - -def collect_dir_tests(base_dir, test_files): - for f_name in os.listdir(base_dir): - files_to_execute = [a for a in test_files.items() if a[0] in f_name] - lines_to_execute = reduce(lambda x, y: x + y[1], files_to_execute, []) - if f_name.endswith(".py") and (not test_files or files_to_execute): - path = os.path.join(base_dir, f_name) - with open(path) as f: - source = f.read() - for case in collect_file_tests(source, path, lines_to_execute): - yield case diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/refactor/extract.py b/vim-plugins/bundle/jedi-vim/jedi/test/refactor/extract.py deleted file mode 100644 index 312aced..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/refactor/extract.py +++ /dev/null @@ -1,47 +0,0 @@ -# --- simple -def test(): - #? 35 a - return test(100, (30 + b, c) + 1) - -# +++ -def test(): - a = (30 + b, c) + 1 - return test(100, a) - - -# --- simple #2 -def test(): - #? 25 a - return test(100, (30 + b, c) + 1) - -# +++ -def test(): - a = 30 + b - return test(100, (a, c) + 1) - - -# --- multiline -def test(): - #? 30 x - return test(1, (30 + b, c) - + 1) -# +++ -def test(): - x = ((30 + b, c) - + 1) - return test(1, x -) - - -# --- multiline #2 -def test(): - #? 25 x - return test(1, (30 + b, c) - + 1) -# +++ -def test(): - x = 30 + b - return test(1, (x, c) - + 1) - - diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/refactor/inline.py b/vim-plugins/bundle/jedi-vim/jedi/test/refactor/inline.py deleted file mode 100644 index c373be2..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/refactor/inline.py +++ /dev/null @@ -1,18 +0,0 @@ -# --- simple -def test(): - #? 4 - a = (30 + b, c) + 1 - return test(100, a) -# +++ -def test(): - return test(100, (30 + b, c) + 1) - - -# --- simple -if 1: - #? 4 - a = 1, 2 - return test(100, a) -# +++ -if 1: - return test(100, (1, 2)) diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/refactor/rename.py b/vim-plugins/bundle/jedi-vim/jedi/test/refactor/rename.py deleted file mode 100644 index e98c589..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/refactor/rename.py +++ /dev/null @@ -1,17 +0,0 @@ -""" -Test coverage for renaming is mostly being done by testing -`Script.usages`. -""" - -# --- simple -def test1(): - #? 7 blabla - test1() - AssertionError - return test1, test1.not_existing -# +++ -def blabla(): - blabla() - AssertionError - return blabla, blabla.not_existing - diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/run.py b/vim-plugins/bundle/jedi-vim/jedi/test/run.py deleted file mode 100755 index 8337f7c..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/run.py +++ /dev/null @@ -1,444 +0,0 @@ -#!/usr/bin/env python -""" -|jedi| is mostly being tested by what I would call "Blackbox Tests". These -tests are just testing the interface and do input/output testing. This makes a -lot of sense for |jedi|. Jedi supports so many different code structures, that -it is just stupid to write 200'000 unittests in the manner of -``regression.py``. Also, it is impossible to do doctests/unittests on most of -the internal data structures. That's why |jedi| uses mostly these kind of -tests. - -There are different kind of tests: - -- completions / goto_definitions ``#?`` -- goto_assignments: ``#!`` -- usages: ``#<`` - -How to run tests? -+++++++++++++++++ - -Jedi uses pytest_ to run unit and integration tests. To run tests, -simply run ``py.test``. You can also use tox_ to run tests for -multiple Python versions. - -.. _pytest: http://pytest.org -.. _tox: http://testrun.org/tox - -Integration test cases are located in ``test/completion`` directory -and each test case is indicated by either the comment ``#?`` (completions / -definitions), ``#!`` (assignments), or ``#<`` (usages). -There is also support for third party libraries. In a normal test run they are -not being executed, you have to provide a ``--thirdparty`` option. - -In addition to standard `-k` and `-m` options in py.test, you can use -`-T` (`--test-files`) option to specify integration test cases to run. -It takes the format of ``FILE_NAME[:LINE[,LINE[,...]]]`` where -``FILE_NAME`` is a file in ``test/completion`` and ``LINE`` is a line -number of the test comment. Here is some recipes: - -Run tests only in ``basic.py`` and ``imports.py``:: - - py.test test/test_integration.py -T basic.py -T imports.py - -Run test at line 4, 6, and 8 in ``basic.py``:: - - py.test test/test_integration.py -T basic.py:4,6,8 - -See ``py.test --help`` for more information. - -If you want to debug a test, just use the ``--pdb`` option. - -Alternate Test Runner -+++++++++++++++++++++ - -If you don't like the output of ``py.test``, there's an alternate test runner -that you can start by running ``./run.py``. The above example could be run by:: - - ./run.py basic 4 6 8 50-80 - -The advantage of this runner is simplicity and more customized error reports. -Using both runners will help you to have a quicker overview of what's -happening. - - -Auto-Completion -+++++++++++++++ - -Uses comments to specify a test in the next line. The comment says which -results are expected. The comment always begins with `#?`. The last row -symbolizes the cursor. - -For example:: - - #? ['real'] - a = 3; a.rea - -Because it follows ``a.rea`` and a is an ``int``, which has a ``real`` -property. - -Goto Definitions -++++++++++++++++ - -Definition tests use the same symbols like completion tests. This is -possible because the completion tests are defined with a list:: - - #? int() - ab = 3; ab - -Goto Assignments -++++++++++++++++ - -Tests look like this:: - - abc = 1 - #! ['abc=1'] - abc - -Additionally it is possible to specify the column by adding a number, which -describes the position of the test (otherwise it's just the end of line):: - - #! 2 ['abc=1'] - abc - -Usages -++++++ - -Tests look like this:: - - abc = 1 - #< abc@1,0 abc@3,0 - abc -""" -import os -import re -import sys -import operator -from ast import literal_eval -from io import StringIO -from functools import reduce - -import jedi -from jedi._compatibility import unicode, is_py3 -from jedi.parser import Parser, load_grammar -from jedi.api.classes import Definition - - -TEST_COMPLETIONS = 0 -TEST_DEFINITIONS = 1 -TEST_ASSIGNMENTS = 2 -TEST_USAGES = 3 - - -class IntegrationTestCase(object): - def __init__(self, test_type, correct, line_nr, column, start, line, - path=None, skip=None): - self.test_type = test_type - self.correct = correct - self.line_nr = line_nr - self.column = column - self.start = start - self.line = line - self.path = path - self.skip = skip - - @property - def module_name(self): - return os.path.splitext(os.path.basename(self.path))[0] - - @property - def line_nr_test(self): - """The test is always defined on the line before.""" - return self.line_nr - 1 - - def __repr__(self): - return '<%s: %s:%s:%s>' % (self.__class__.__name__, self.module_name, - self.line_nr_test, self.line.rstrip()) - - def script(self): - return jedi.Script(self.source, self.line_nr, self.column, self.path) - - def run(self, compare_cb): - testers = { - TEST_COMPLETIONS: self.run_completion, - TEST_DEFINITIONS: self.run_goto_definitions, - TEST_ASSIGNMENTS: self.run_goto_assignments, - TEST_USAGES: self.run_usages, - } - return testers[self.test_type](compare_cb) - - def run_completion(self, compare_cb): - completions = self.script().completions() - #import cProfile; cProfile.run('script.completions()') - - comp_str = set([c.name for c in completions]) - return compare_cb(self, comp_str, set(literal_eval(self.correct))) - - def run_goto_definitions(self, compare_cb): - script = self.script() - evaluator = script._evaluator - - def comparison(definition): - suffix = '()' if definition.type == 'instance' else '' - return definition.desc_with_module + suffix - - def definition(correct, correct_start, path): - should_be = set() - for match in re.finditer('(?:[^ ]+)', correct): - string = match.group(0) - parser = Parser(load_grammar(), string, start_symbol='eval_input') - parser.position_modifier.line = self.line_nr - element = parser.get_parsed_node() - element.parent = jedi.api.completion.get_user_scope( - script._get_module(), - (self.line_nr, self.column) - ) - results = evaluator.eval_element(element) - if not results: - raise Exception('Could not resolve %s on line %s' - % (match.string, self.line_nr - 1)) - - should_be |= set(Definition(evaluator, r) for r in results) - - # Because the objects have different ids, `repr`, then compare. - should = set(comparison(r) for r in should_be) - return should - - should = definition(self.correct, self.start, script.path) - result = script.goto_definitions() - is_str = set(comparison(r) for r in result) - return compare_cb(self, is_str, should) - - def run_goto_assignments(self, compare_cb): - result = self.script().goto_assignments() - comp_str = str(sorted(str(r.description) for r in result)) - return compare_cb(self, comp_str, self.correct) - - def run_usages(self, compare_cb): - result = self.script().usages() - self.correct = self.correct.strip() - compare = sorted((r.module_name, r.line, r.column) for r in result) - wanted = [] - if not self.correct: - positions = [] - else: - positions = literal_eval(self.correct) - for pos_tup in positions: - if type(pos_tup[0]) == str: - # this means that there is a module specified - wanted.append(pos_tup) - else: - line = pos_tup[0] - if pos_tup[0] is not None: - line += self.line_nr - wanted.append((self.module_name, line, pos_tup[1])) - - return compare_cb(self, compare, sorted(wanted)) - - -def skip_python_version(line): - comp_map = { - '==': 'eq', - '<=': 'le', - '>=': 'ge', - '<': 'lt', - '>': 'gt', - } - # check for python minimal version number - match = re.match(r" *# *python *([<>]=?|==) *(\d+(?:\.\d+)?)$", line) - if match: - minimal_python_version = tuple( - map(int, match.group(2).split("."))) - operation = getattr(operator, comp_map[match.group(1)]) - if not operation(sys.version_info, minimal_python_version): - return "Minimal python version %s %s" % (match.group(1), match.group(2)) - - return None - - -def collect_file_tests(path, lines, lines_to_execute): - def makecase(t): - return IntegrationTestCase(t, correct, line_nr, column, - start, line, path=path, skip=skip) - - start = None - correct = None - test_type = None - skip = None - for line_nr, line in enumerate(lines, 1): - if correct is not None: - r = re.match('^(\d+)\s*(.*)$', correct) - if r: - column = int(r.group(1)) - correct = r.group(2) - start += r.regs[2][0] # second group, start index - else: - column = len(line) - 1 # -1 for the \n - if test_type == '!': - yield makecase(TEST_ASSIGNMENTS) - elif test_type == '<': - yield makecase(TEST_USAGES) - elif correct.startswith('['): - yield makecase(TEST_COMPLETIONS) - else: - yield makecase(TEST_DEFINITIONS) - correct = None - else: - skip = skip or skip_python_version(line) - try: - r = re.search(r'(?:^|(?<=\s))#([?!<])\s*([^\n]*)', line) - # test_type is ? for completion and ! for goto_assignments - test_type = r.group(1) - correct = r.group(2) - # Quick hack to make everything work (not quite a bloody unicorn hack though). - if correct == '': - correct = ' ' - start = r.start() - except AttributeError: - correct = None - else: - # Skip the test, if this is not specified test. - for l in lines_to_execute: - if isinstance(l, tuple) and l[0] <= line_nr <= l[1] \ - or line_nr == l: - break - else: - if lines_to_execute: - correct = None - - -def collect_dir_tests(base_dir, test_files, check_thirdparty=False): - for f_name in os.listdir(base_dir): - files_to_execute = [a for a in test_files.items() if f_name.startswith(a[0])] - lines_to_execute = reduce(lambda x, y: x + y[1], files_to_execute, []) - if f_name.endswith(".py") and (not test_files or files_to_execute): - skip = None - if check_thirdparty: - lib = f_name.replace('_.py', '') - try: - # there is always an underline at the end. - # It looks like: completion/thirdparty/pylab_.py - __import__(lib) - except ImportError: - skip = 'Thirdparty-Library %s not found.' % lib - - path = os.path.join(base_dir, f_name) - - if is_py3: - source = open(path, encoding='utf-8').read() - else: - source = unicode(open(path).read(), 'UTF-8') - - for case in collect_file_tests(path, StringIO(source), - lines_to_execute): - case.source = source - if skip: - case.skip = skip - yield case - - -docoptstr = """ -Using run.py to make debugging easier with integration tests. - -An alternative testing format, which is much more hacky, but very nice to -work with. - -Usage: - run.py [--pdb] [--debug] [--thirdparty] [...] - run.py --help - -Options: - -h --help Show this screen. - --pdb Enable pdb debugging on fail. - -d, --debug Enable text output debugging (please install ``colorama``). - --thirdparty Also run thirdparty tests (in ``completion/thirdparty``). -""" -if __name__ == '__main__': - import docopt - arguments = docopt.docopt(docoptstr) - - import time - t_start = time.time() - # Sorry I didn't use argparse here. It's because argparse is not in the - # stdlib in 2.5. - import sys - - if arguments['--debug']: - jedi.set_debug_function() - - # get test list, that should be executed - test_files = {} - last = None - for arg in arguments['']: - match = re.match('(\d+)-(\d+)', arg) - if match: - start, end = match.groups() - test_files[last].append((int(start), int(end))) - elif arg.isdigit(): - if last is None: - continue - test_files[last].append(int(arg)) - else: - test_files[arg] = [] - last = arg - - # completion tests: - dir_ = os.path.dirname(os.path.realpath(__file__)) - completion_test_dir = os.path.join(dir_, '../test/completion') - completion_test_dir = os.path.abspath(completion_test_dir) - summary = [] - tests_fail = 0 - - # execute tests - cases = list(collect_dir_tests(completion_test_dir, test_files)) - if test_files or arguments['--thirdparty']: - completion_test_dir += '/thirdparty' - cases += collect_dir_tests(completion_test_dir, test_files, True) - - def file_change(current, tests, fails): - if current is not None: - current = os.path.basename(current) - print('%s \t\t %s tests and %s fails.' % (current, tests, fails)) - - def report(case, actual, desired): - if actual == desired: - return 0 - else: - print("\ttest fail @%d, actual = %s, desired = %s" - % (case.line_nr - 1, actual, desired)) - return 1 - - import traceback - current = cases[0].path if cases else None - count = fails = 0 - for c in cases: - if c.skip: - continue - if current != c.path: - file_change(current, count, fails) - current = c.path - count = fails = 0 - - try: - if c.run(report): - tests_fail += 1 - fails += 1 - except Exception: - traceback.print_exc() - print("\ttest fail @%d" % (c.line_nr - 1)) - tests_fail += 1 - fails += 1 - if arguments['--pdb']: - import pdb - pdb.post_mortem() - - count += 1 - - file_change(current, count, fails) - - print('\nSummary: (%s fails of %s tests) in %.3fs' - % (tests_fail, len(cases), time.time() - t_start)) - for s in summary: - print(s) - - exit_code = 1 if tests_fail else 0 - sys.exit(exit_code) diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/speed/precedence.py b/vim-plugins/bundle/jedi-vim/jedi/test/speed/precedence.py deleted file mode 100644 index afd8824..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/speed/precedence.py +++ /dev/null @@ -1,37 +0,0 @@ -def marks(code): - if '.' in code: - another(code[:code.index(',') - 1] + '!') - else: - another(code + '.') - - -def another(code2): - call(numbers(code2 + 'haha')) - -marks('start1 ') -marks('start2 ') - - -def alphabet(code4): - if 1: - if 2: - return code4 + 'a' - else: - return code4 + 'b' - else: - if 2: - return code4 + 'c' - else: - return code4 + 'd' - - -def numbers(code5): - if 2: - return alphabet(code5 + '1') - else: - return alphabet(code5 + '2') - - -def call(code3): - code3 = numbers(numbers('end')) + numbers(code3) - code3.partition diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/arguments.py b/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/arguments.py deleted file mode 100644 index 2fc8e81..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/arguments.py +++ /dev/null @@ -1,73 +0,0 @@ -# ----------------- -# normal arguments (no keywords) -# ----------------- - - -def simple(a): - return a - -simple(1) -#! 6 type-error-too-few-arguments -simple() -#! 10 type-error-too-many-arguments -simple(1, 2) - - -#! 10 type-error-too-many-arguments -simple(1, 2, 3) - -# ----------------- -# keyword arguments -# ----------------- - -simple(a=1) -#! 7 type-error-keyword-argument -simple(b=1) -#! 10 type-error-too-many-arguments -simple(1, a=1) - - -def two_params(x, y): - return y - - -two_params(y=2, x=1) -two_params(1, y=2) - -#! 11 type-error-multiple-values -two_params(1, x=2) -#! 17 type-error-too-many-arguments -two_params(1, 2, y=3) - -# ----------------- -# default arguments -# ----------------- - -def default(x, y=1, z=2): - return x - -#! 7 type-error-too-few-arguments -default() -default(1) -default(1, 2) -default(1, 2, 3) -#! 17 type-error-too-many-arguments -default(1, 2, 3, 4) - -default(x=1) - -# ----------------- -# class arguments -# ----------------- - -class Instance(): - def __init__(self, foo): - self.foo = foo - -Instance(1).foo -Instance(foo=1).foo - -#! 12 type-error-too-many-arguments -Instance(1, 2).foo -#! 8 type-error-too-few-arguments -Instance().foo diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/attribute_error.py b/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/attribute_error.py deleted file mode 100644 index 4b084c1..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/attribute_error.py +++ /dev/null @@ -1,119 +0,0 @@ -class Cls(): - class_attr = '' - def __init__(self, input): - self.instance_attr = 3 - self.input = input - - def f(self): - #! 12 attribute-error - return self.not_existing - - def undefined_object(self, obj): - """ - Uses an arbitrary object and performs an operation on it, shouldn't - be a problem. - """ - obj.arbitrary_lookup - - def defined_lookup(self, obj): - """ - `obj` is defined by a call into this function. - """ - obj.upper - #! 4 attribute-error - obj.arbitrary_lookup - - #! 13 name-error - class_attr = a - -Cls(1).defined_lookup('') - -c = Cls(1) -c.class_attr -Cls.class_attr -#! 4 attribute-error -Cls.class_attr_error -c.instance_attr -#! 2 attribute-error -c.instance_attr_error - - -c.something = None - -#! 12 name-error -something = a -something - -# ----------------- -# Unused array variables should still raise attribute errors. -# ----------------- - -# should not raise anything. -for loop_variable in [1, 2]: - #! 4 name-error - x = undefined - loop_variable - -#! 28 name-error -for loop_variable in [1, 2, undefined]: - pass - -#! 7 attribute-error -[1, ''.undefined_attr] - - -def return_one(something): - return 1 - -#! 14 attribute-error -return_one(''.undefined_attribute) - -#! 12 name-error -[r for r in undefined] - -#! 1 name-error -[undefined for r in [1, 2]] - -[r for r in [1, 2]] - -# some random error that showed up -class NotCalled(): - def match_something(self, param): - seems_to_need_an_assignment = param - return [value.match_something() for value in []] - -# ----------------- -# decorators -# ----------------- - -#! 1 name-error -@undefined_decorator -def func(): - return 1 - -# ----------------- -# operators -# ----------------- - -string = '%s %s' % (1, 2) - -# Shouldn't raise an error, because `string` is really just a string, not an -# array or something. -string.upper - -# ----------------- -# imports -# ----------------- - -# Star imports and the like in modules should not cause attribute errors in -# this module. -import import_tree - -import_tree.a -import_tree.b - -# This is something that raised an error, because it was using a complex -# mixture of Jedi fakes and compiled objects. -import _sre -#! 15 attribute-error -_sre.compile().not_existing diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/attribute_warnings.py b/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/attribute_warnings.py deleted file mode 100644 index 0e1e5e9..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/attribute_warnings.py +++ /dev/null @@ -1,46 +0,0 @@ -""" -Jedi issues warnings for possible errors if ``__getattr__``, -``__getattribute__`` or ``setattr`` are used. -""" - -# ----------------- -# __getattr*__ -# ----------------- - - -class Cls(): - def __getattr__(self, name): - return getattr(str, name) - - -Cls().upper - -#! 6 warning attribute-error -Cls().undefined - - -class Inherited(Cls): - pass - -Inherited().upper - -#! 12 warning attribute-error -Inherited().undefined - -# ----------------- -# setattr -# ----------------- - - -class SetattrCls(): - def __init__(self, dct): - # Jedi doesn't even try to understand such code - for k, v in dct.items(): - setattr(self, k, v) - - self.defined = 3 - -c = SetattrCls({'a': 'b'}) -c.defined -#! 2 warning attribute-error -c.undefined diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/branches.py b/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/branches.py deleted file mode 100644 index 6828d33..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/branches.py +++ /dev/null @@ -1,46 +0,0 @@ -# ----------------- -# Simple tests -# ----------------- - -import random - -if random.choice([0, 1]): - x = '' -else: - x = 1 -if random.choice([0, 1]): - y = '' -else: - y = 1 - -# A simple test -if x != 1: - x.upper() -else: - #! 2 attribute-error - x.upper() - pass - -# This operation is wrong, because the types could be different. -#! 6 type-error-operation -z = x + y -# However, here we have correct types. -if x == y: - z = x + y -else: - #! 6 type-error-operation - z = x + y - -# ----------------- -# With a function -# ----------------- - -def addition(a, b): - if type(a) == type(b): - return a + b - else: - #! 9 type-error-operation - return a + b - -addition(1, 1) -addition(1.0, '') diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/builtins.py b/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/builtins.py deleted file mode 100644 index 86caca6..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/builtins.py +++ /dev/null @@ -1,11 +0,0 @@ -# ---------- -# isinstance -# ---------- - -isinstance(1, int) -isinstance(1, (int, str)) - -#! 14 type-error-isinstance -isinstance(1, 1) -#! 14 type-error-isinstance -isinstance(1, [int, str]) diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/class_simple.py b/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/class_simple.py deleted file mode 100644 index 3f84fde..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/class_simple.py +++ /dev/null @@ -1,13 +0,0 @@ -class Base(object): - class Nested(): - def foo(): - pass - - -class X(Base.Nested): - pass - - -X().foo() -#! 4 attribute-error -X().bar() diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/comprehensions.py b/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/comprehensions.py deleted file mode 100644 index 4af799d..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/comprehensions.py +++ /dev/null @@ -1,41 +0,0 @@ -[a + 1 for a in [1, 2]] - -#! 3 type-error-operation -[a + '' for a in [1, 2]] -#! 3 type-error-operation -(a + '' for a in [1, 2]) - -#! 12 type-error-not-iterable -[a for a in 1] - -tuple(str(a) for a in [1]) - -#! 8 type-error-operation -tuple(a + 3 for a in ['']) - -# ---------- -# Some variables within are not defined -# ---------- - -#! 12 name-error -[1 for a in NOT_DEFINFED for b in a if 1] - -#! 25 name-error -[1 for a in [1] for b in NOT_DEFINED if 1] - -#! 12 name-error -[1 for a in NOT_DEFINFED for b in [1] if 1] - -#! 19 name-error -(1 for a in [1] if NOT_DEFINED) - -# ---------- -# unbalanced sides. -# ---------- - -# ok -(1 for a, b in [(1, 2)]) -#! 13 value-error-too-few-values -(1 for a, b, c in [(1, 2)]) -#! 10 value-error-too-many-values -(1 for a, b in [(1, 2, 3)]) diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/descriptors.py b/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/descriptors.py deleted file mode 100644 index 0fc5d15..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/descriptors.py +++ /dev/null @@ -1,13 +0,0 @@ -# classmethod -class TarFile(): - @classmethod - def open(cls, name, **kwargs): - return cls.taropen(name, **kwargs) - - @classmethod - def taropen(cls, name, **kwargs): - return name - - -# should just work -TarFile.open('hallo') diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/generators.py b/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/generators.py deleted file mode 100644 index b941800..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/generators.py +++ /dev/null @@ -1,7 +0,0 @@ -def generator(): - yield 1 - -#! 11 type-error-not-subscriptable -generator()[0] - -list(generator())[0] diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/import_tree/__init__.py b/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/import_tree/__init__.py deleted file mode 100644 index cb485f1..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/import_tree/__init__.py +++ /dev/null @@ -1,5 +0,0 @@ -""" -Another import tree, this time not for completion, but static analysis. -""" - -from .a import * diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/import_tree/a.py b/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/import_tree/a.py deleted file mode 100644 index b02981c..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/import_tree/a.py +++ /dev/null @@ -1 +0,0 @@ -from . import b diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/import_tree/b.py b/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/import_tree/b.py deleted file mode 100644 index e69de29..0000000 diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/imports.py b/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/imports.py deleted file mode 100644 index 0df9bac..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/imports.py +++ /dev/null @@ -1,25 +0,0 @@ - -#! 7 import-error -import not_existing - -import os - -from os.path import abspath -#! 20 import-error -from os.path import not_existing - -from datetime import date -date.today - -#! 5 attribute-error -date.not_existing_attribute - -#! 14 import-error -from datetime.date import today - -#! 16 import-error -import datetime.date -#! 7 import-error -import not_existing_nested.date - -import os.path diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/iterable.py b/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/iterable.py deleted file mode 100644 index 0eae367..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/iterable.py +++ /dev/null @@ -1,21 +0,0 @@ - -a, b = {'asdf': 3, 'b': 'str'} -a - -x = [1] -x[0], b = {'a': 1, 'b': '2'} - -dct = {3: ''} -for x in dct: - pass - -#! 4 type-error-not-iterable -for x, y in dct: - pass - -# Shouldn't cause issues, because if there are no types (or we don't know what -# the types are, we should just ignore it. -#! 0 value-error-too-few-values -a, b = [] -#! 7 name-error -a, b = NOT_DEFINED diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/keywords.py b/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/keywords.py deleted file mode 100644 index e3fcaa4..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/keywords.py +++ /dev/null @@ -1,7 +0,0 @@ -def raises(): - raise KeyError() - - -def wrong_name(): - #! 6 name-error - raise NotExistingException() diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/operations.py b/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/operations.py deleted file mode 100644 index 05e1406..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/operations.py +++ /dev/null @@ -1,16 +0,0 @@ --1 + 1 -1 + 1.0 -#! 2 type-error-operation -1 + '1' -#! 2 type-error-operation -1 - '1' - --1 - - 1 --1 - int() -int() - float() -float() - 3.0 - -a = 3 -b = '' -#! 2 type-error-operation -a + b diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/python2.py b/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/python2.py deleted file mode 100644 index 4d896e3..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/python2.py +++ /dev/null @@ -1,11 +0,0 @@ -""" -Some special cases of Python 2. -""" -# python <= 2.7 - -# print is syntax: -print 1 -print(1) - -#! 6 name-error -print NOT_DEFINED diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/star_arguments.py b/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/star_arguments.py deleted file mode 100644 index 34be43b..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/star_arguments.py +++ /dev/null @@ -1,119 +0,0 @@ -# ----------------- -# *args -# ----------------- - - -def simple(a): - return a - - -def nested(*args): - return simple(*args) - -nested(1) -#! 6 type-error-too-few-arguments -nested() - - -def nested_no_call_to_function(*args): - return simple(1, *args) - - -def simple2(a, b, c): - return b -def nested(*args): - return simple2(1, *args) -def nested_twice(*args1): - return nested(*args1) - -nested_twice(2, 3) -#! 13 type-error-too-few-arguments -nested_twice(2) -#! 19 type-error-too-many-arguments -nested_twice(2, 3, 4) - - -# A named argument can be located before *args. -def star_args_with_named(*args): - return simple2(c='', *args) - -star_args_with_named(1, 2) -# ----------------- -# **kwargs -# ----------------- - - -def kwargs_test(**kwargs): - return simple2(1, **kwargs) - -kwargs_test(c=3, b=2) -#! 12 type-error-too-few-arguments -kwargs_test(c=3) -#! 12 type-error-too-few-arguments -kwargs_test(b=2) -#! 22 type-error-keyword-argument -kwargs_test(b=2, c=3, d=4) -#! 12 type-error-multiple-values -kwargs_test(b=2, c=3, a=4) - - -def kwargs_nested(**kwargs): - return kwargs_test(b=2, **kwargs) - -kwargs_nested(c=3) -#! 13 type-error-too-few-arguments -kwargs_nested() -#! 19 type-error-keyword-argument -kwargs_nested(c=2, d=4) -#! 14 type-error-multiple-values -kwargs_nested(c=2, a=4) -# TODO reenable -##! 14 type-error-multiple-values -#kwargs_nested(b=3, c=2) - -# ----------------- -# mixed *args/**kwargs -# ----------------- - -def simple_mixed(a, b, c): - return b - -def mixed(*args, **kwargs): - return simple_mixed(1, *args, **kwargs) - -mixed(1, 2) -mixed(1, c=2) -mixed(b=2, c=3) -mixed(c=4, b='') - -# need separate functions, otherwise these might swallow the errors -def mixed2(*args, **kwargs): - return simple_mixed(1, *args, **kwargs) - - -#! 7 type-error-too-few-arguments -mixed2(c=2) -#! 7 type-error-too-few-arguments -mixed2(3) -#! 13 type-error-too-many-arguments -mixed2(3, 4, 5) -# TODO reenable -##! 13 type-error-too-many-arguments -#mixed2(3, 4, c=5) -#! 7 type-error-multiple-values -mixed2(3, b=5) - -# ----------------- -# plain wrong arguments -# ----------------- - -#! 12 type-error-star-star -simple(1, **[]) -#! 12 type-error-star-star -simple(1, **1) -class A(): pass -#! 12 type-error-star-star -simple(1, **A()) - -#! 11 type-error-star -simple(1, *1) diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/try_except.py b/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/try_except.py deleted file mode 100644 index e654328..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/static_analysis/try_except.py +++ /dev/null @@ -1,89 +0,0 @@ -try: - #! 4 attribute-error - str.not_existing -except TypeError: - pass - -try: - str.not_existing -except AttributeError: - #! 4 attribute-error - str.not_existing - pass - -try: - import not_existing_import -except ImportError: - pass -try: - #! 7 import-error - import not_existing_import -except AttributeError: - pass - -# ----------------- -# multi except -# ----------------- -try: - str.not_existing -except (TypeError, AttributeError): pass - -try: - str.not_existing -except ImportError: - pass -except (NotImplementedError, AttributeError): pass - -try: - #! 4 attribute-error - str.not_existing -except (TypeError, NotImplementedError): pass - -# ----------------- -# detailed except -# ----------------- -try: - str.not_existing -except ((AttributeError)): pass -try: - #! 4 attribute-error - str.not_existing -except [AttributeError]: pass - -# Should be able to detect errors in except statement as well. -try: - pass -#! 7 name-error -except Undefined: - pass - -# ----------------- -# inheritance -# ----------------- - -try: - undefined -except Exception: - pass - -# should catch everything -try: - undefined -except: - pass - -# ----------------- -# kind of similar: hasattr -# ----------------- - -if hasattr(str, 'undefined'): - str.undefined - str.upper - #! 4 attribute-error - str.undefined2 - #! 4 attribute-error - int.undefined -else: - str.upper - #! 4 attribute-error - str.undefined diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_api/__init__.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_api/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_api/test_api.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_api/test_api.py deleted file mode 100644 index d388c51..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_api/test_api.py +++ /dev/null @@ -1,179 +0,0 @@ -""" -Test all things related to the ``jedi.api`` module. -""" - -from textwrap import dedent - -from jedi import api -from jedi._compatibility import is_py3 -from pytest import raises -from jedi.parser import utils - - -def test_preload_modules(): - def check_loaded(*modules): - # +1 for None module (currently used) - assert len(parser_cache) == len(modules) + 1 - for i in modules: - assert [i in k for k in parser_cache.keys() if k is not None] - - temp_cache, utils.parser_cache = utils.parser_cache, {} - parser_cache = utils.parser_cache - - api.preload_module('sys') - check_loaded() # compiled (c_builtin) modules shouldn't be in the cache. - api.preload_module('json', 'token') - check_loaded('json', 'token') - - utils.parser_cache = temp_cache - - -def test_empty_script(): - assert api.Script('') - - -def test_line_number_errors(): - """ - Script should raise a ValueError if line/column numbers are not in a - valid range. - """ - s = 'hello' - # lines - with raises(ValueError): - api.Script(s, 2, 0) - with raises(ValueError): - api.Script(s, 0, 0) - - # columns - with raises(ValueError): - api.Script(s, 1, len(s) + 1) - with raises(ValueError): - api.Script(s, 1, -1) - - # ok - api.Script(s, 1, 0) - api.Script(s, 1, len(s)) - - -def _check_number(source, result='float'): - completions = api.Script(source).completions() - assert completions[0].parent().name == result - - -def test_completion_on_number_literals(): - # No completions on an int literal (is a float). - assert [c.name for c in api.Script('1.').completions()] \ - == ['and', 'if', 'in', 'is', 'not', 'or'] - - # Multiple points after an int literal basically mean that there's a float - # and a call after that. - _check_number('1..') - _check_number('1.0.') - - # power notation - _check_number('1.e14.') - _check_number('1.e-3.') - _check_number('9e3.') - assert api.Script('1.e3..').completions() == [] - assert api.Script('1.e-13..').completions() == [] - - -def test_completion_on_hex_literals(): - assert api.Script('0x1..').completions() == [] - _check_number('0x1.', 'int') # hexdecimal - # Completing binary literals doesn't work if they are not actually binary - # (invalid statements). - assert api.Script('0b2.b').completions() == [] - _check_number('0b1.', 'int') # binary - - _check_number('0x2e.', 'int') - _check_number('0xE7.', 'int') - _check_number('0xEa.', 'int') - # theoretically, but people can just check for syntax errors: - #assert api.Script('0x.').completions() == [] - - -def test_completion_on_complex_literals(): - assert api.Script('1j..').completions() == [] - _check_number('1j.', 'complex') - _check_number('44.j.', 'complex') - _check_number('4.0j.', 'complex') - # No dot no completion - I thought, but 4j is actually a literall after - # which a keyword like or is allowed. Good times, haha! - assert (set([c.name for c in api.Script('4j').completions()]) == - set(['if', 'and', 'in', 'is', 'not', 'or'])) - - -def test_goto_assignments_on_non_name(): - assert api.Script('for').goto_assignments() == [] - - assert api.Script('assert').goto_assignments() == [] - if is_py3: - assert api.Script('True').goto_assignments() == [] - else: - # In Python 2.7 True is still a name. - assert api.Script('True').goto_assignments()[0].description == 'class bool' - - -def test_goto_definitions_on_non_name(): - assert api.Script('import x', column=0).goto_definitions() == [] - - -def test_goto_definition_not_multiple(): - """ - There should be only one Definition result if it leads back to the same - origin (e.g. instance method) - """ - - s = dedent('''\ - import random - class A(): - def __init__(self, a): - self.a = 3 - - def foo(self): - pass - - if random.randint(0, 1): - a = A(2) - else: - a = A(1) - a''') - assert len(api.Script(s).goto_definitions()) == 1 - - -def test_usage_description(): - descs = [u.description for u in api.Script("foo = ''; foo").usages()] - assert set(descs) == set(["foo = ''", 'foo']) - - -def test_get_line_code(): - def get_line_code(source, line=None, **kwargs): - return api.Script(source, line=line).completions()[0].get_line_code(**kwargs) - - # On builtin - assert get_line_code('') == '' - - # On custom code - line = ' foo' - assert get_line_code('def foo():\n%s' % line) == line - - # With before/after - line = ' foo' - source = 'def foo():\n%s\nother_line' % line - assert get_line_code(source, line=2) == line - assert get_line_code(source, line=2, after=1) == line + '\nother_line' - assert get_line_code(source, line=2, after=1, before=1) == source - - -def test_goto_assignments_follow_imports(): - code = dedent(""" - import inspect - inspect.isfunction""") - definition, = api.Script(code, column=0).goto_assignments(follow_imports=True) - assert 'inspect.py' in definition.module_path - assert definition.start_pos == (1, 0) - - definition, = api.Script(code).goto_assignments(follow_imports=True) - assert 'inspect.py' in definition.module_path - assert definition.start_pos > (1, 0) diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_api/test_api_classes_follow_definition.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_api/test_api_classes_follow_definition.py deleted file mode 100644 index ffc0cb6..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_api/test_api_classes_follow_definition.py +++ /dev/null @@ -1,62 +0,0 @@ -from itertools import chain - -import jedi -from ..helpers import cwd_at - - -def test_import_empty(): - """ github #340, return the full word. """ - completion = jedi.Script("import ").completions()[0] - definition = completion.follow_definition()[0] - assert definition - - -def check_follow_definition_types(source): - # nested import - completions = jedi.Script(source, path='some_path.py').completions() - defs = chain.from_iterable(c.follow_definition() for c in completions) - return [d.type for d in defs] - - -def test_follow_import_incomplete(): - """ - Completion on incomplete imports should always take the full completion - to do any evaluation. - """ - datetime = check_follow_definition_types("import itertool") - assert datetime == ['module'] - - # empty `from * import` parts - itert = jedi.Script("from itertools import ").completions() - definitions = [d for d in itert if d.name == 'chain'] - assert len(definitions) == 1 - assert [d.type for d in definitions[0].follow_definition()] == ['class'] - - # incomplete `from * import` part - datetime = check_follow_definition_types("from datetime import datetim") - assert set(datetime) == set(['class', 'instance']) # py33: builtin and pure py version - - # os.path check - ospath = check_follow_definition_types("from os.path import abspat") - assert ospath == ['function'] - - # alias - alias = check_follow_definition_types("import io as abcd; abcd") - assert alias == ['module'] - - -@cwd_at('test/completion/import_tree') -def test_follow_definition_nested_import(): - types = check_follow_definition_types("import pkg.mod1; pkg") - assert types == ['module'] - - types = check_follow_definition_types("import pkg.mod1; pkg.mod1") - assert types == ['module'] - - types = check_follow_definition_types("import pkg.mod1; pkg.mod1.a") - assert types == ['instance'] - - -def test_follow_definition_land_on_import(): - types = check_follow_definition_types("import datetime; datetim") - assert types == ['module'] diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_api/test_call_signatures.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_api/test_call_signatures.py deleted file mode 100644 index 1add2ab..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_api/test_call_signatures.py +++ /dev/null @@ -1,389 +0,0 @@ -from textwrap import dedent -import inspect - -from ..helpers import TestCase -from jedi import Script -from jedi import cache -from jedi._compatibility import is_py33 - - -def assert_signature(source, expected_name, expected_index=0, line=None, column=None): - signatures = Script(source, line, column).call_signatures() - - assert len(signatures) <= 1 - - if not signatures: - assert expected_name is None, \ - 'There are no signatures, but `%s` expected.' % expected_name - else: - assert signatures[0].name == expected_name - assert signatures[0].index == expected_index - return signatures[0] - - -class TestCallSignatures(TestCase): - def _run_simple(self, source, name, index=0, column=None, line=1): - assert_signature(source, name, index, line, column) - - def test_valid_call(self): - assert_signature('str()', 'str', column=4) - - def test_simple(self): - run = self._run_simple - - # simple - s1 = "sorted(a, str(" - run(s1, 'sorted', 0, 7) - run(s1, 'sorted', 1, 9) - run(s1, 'sorted', 1, 10) - run(s1, 'sorted', 1, 11) - run(s1, 'str', 0, 14) - - s2 = "abs(), " - run(s2, 'abs', 0, 4) - run(s2, None, column=5) - run(s2, None) - - s3 = "abs()." - run(s3, None, column=5) - run(s3, None) - - def test_more_complicated(self): - run = self._run_simple - ''' - s4 = 'abs(zip(), , set,' - run(s4, None, column=3) - run(s4, 'abs', 0, 4) - run(s4, 'zip', 0, 8) - run(s4, 'abs', 0, 9) - #run(s4, 'abs', 1, 10) - ''' - - s5 = "sorted(1,\nif 2:\n def a():" - run(s5, 'sorted', 0, 7) - run(s5, 'sorted', 1, 9) - - s6 = "str().center(" - run(s6, 'center', 0) - run(s6, 'str', 0, 4) - - s7 = "str().upper().center(" - s8 = "str(int[zip(" - run(s7, 'center', 0) - run(s8, 'zip', 0) - run(s8, 'str', 0, 8) - - run("import time; abc = time; abc.sleep(", 'sleep', 0) - - def test_issue_57(self): - # jedi #57 - s = "def func(alpha, beta): pass\n" \ - "func(alpha='101'," - self._run_simple(s, 'func', 0, column=13, line=2) - - def test_flows(self): - # jedi-vim #9 - self._run_simple("with open(", 'open', 0) - - # jedi-vim #11 - self._run_simple("for sorted(", 'sorted', 0) - self._run_simple("for s in sorted(", 'sorted', 0) - - def test_complex(self): - s = """ - def abc(a,b): - pass - - def a(self): - abc( - - if 1: - pass - """ - assert_signature(s, 'abc', 0, line=6, column=24) - s = """ - import re - def huhu(it): - re.compile( - return it * 2 - """ - assert_signature(s, 'compile', 0, line=4, column=31) - - # jedi-vim #70 - s = """def foo(""" - assert Script(s).call_signatures() == [] - - # jedi-vim #116 - s = """import itertools; test = getattr(itertools, 'chain'); test(""" - assert_signature(s, 'chain', 0) - - def test_call_signature_on_module(self): - """github issue #240""" - s = 'import datetime; datetime(' - # just don't throw an exception (if numpy doesn't exist, just ignore it) - assert Script(s).call_signatures() == [] - - def test_call_signatures_empty_parentheses_pre_space(self): - s = dedent("""\ - def f(a, b): - pass - f( )""") - assert_signature(s, 'f', 0, line=3, column=3) - - def test_multiple_signatures(self): - s = dedent("""\ - if x: - def f(a, b): - pass - else: - def f(a, b): - pass - f(""") - assert len(Script(s).call_signatures()) == 2 - - def test_call_signatures_whitespace(self): - s = dedent("""\ - abs( - def x(): - pass - """) - assert_signature(s, 'abs', 0, line=1, column=5) - - def test_decorator_in_class(self): - """ - There's still an implicit param, with a decorator. - Github issue #319. - """ - s = dedent("""\ - def static(func): - def wrapped(obj, *args): - return f(type(obj), *args) - return wrapped - - class C(object): - @static - def test(cls): - return 10 - - C().test(""") - - signatures = Script(s).call_signatures() - assert len(signatures) == 1 - x = [p.description for p in signatures[0].params] - assert x == ['*args'] - - def test_additional_brackets(self): - assert_signature('str((', 'str', 0) - - def test_unterminated_strings(self): - assert_signature('str(";', 'str', 0) - - def test_whitespace_before_bracket(self): - assert_signature('str (', 'str', 0) - assert_signature('str (";', 'str', 0) - assert_signature('str\n(', None) - - def test_brackets_in_string_literals(self): - assert_signature('str (" (', 'str', 0) - assert_signature('str (" )', 'str', 0) - - def test_function_definitions_should_break(self): - """ - Function definitions (and other tokens that cannot exist within call - signatures) should break and not be able to return a call signature. - """ - assert_signature('str(\ndef x', 'str', 0) - assert not Script('str(\ndef x(): pass').call_signatures() - - def test_flow_call(self): - assert not Script('if (1').call_signatures() - - def test_chained_calls(self): - source = dedent(''' - class B(): - def test2(self, arg): - pass - - class A(): - def test1(self): - return B() - - A().test1().test2(''') - - assert_signature(source, 'test2', 0) - - def test_return(self): - source = dedent(''' - def foo(): - return '.'.join()''') - - assert_signature(source, 'join', 0, column=len(" return '.'.join(")) - - -class TestParams(TestCase): - def params(self, source, line=None, column=None): - signatures = Script(source, line, column).call_signatures() - assert len(signatures) == 1 - return signatures[0].params - - def test_param_name(self): - if not is_py33: - p = self.params('''int(''') - # int is defined as: `int(x[, base])` - assert p[0].name == 'x' - # `int` docstring has been redefined: - # http://bugs.python.org/issue14783 - # TODO have multiple call signatures for int (like in the docstr) - #assert p[1].name == 'base' - - p = self.params('''open(something,''') - assert p[0].name in ['file', 'name'] - assert p[1].name == 'mode' - - def test_builtins(self): - """ - The self keyword should be visible even for builtins, if not - instantiated. - """ - p = self.params('str.endswith(') - assert p[0].name == 'self' - assert p[1].name == 'suffix' - p = self.params('str().endswith(') - assert p[0].name == 'suffix' - - -def test_signature_is_definition(): - """ - Through inheritance, a call signature is a sub class of Definition. - Check if the attributes match. - """ - s = """class Spam(): pass\nSpam""" - signature = Script(s + '(').call_signatures()[0] - definition = Script(s + '(', column=0).goto_definitions()[0] - signature.line == 1 - signature.column == 6 - - # Now compare all the attributes that a CallSignature must also have. - for attr_name in dir(definition): - dont_scan = ['defined_names', 'line_nr', 'start_pos', 'documentation', - 'doc', 'parent', 'goto_assignments'] - if attr_name.startswith('_') or attr_name in dont_scan: - continue - attribute = getattr(definition, attr_name) - signature_attribute = getattr(signature, attr_name) - if inspect.ismethod(attribute): - assert attribute() == signature_attribute() - else: - assert attribute == signature_attribute - - -def test_no_signature(): - # str doesn't have a __call__ method - assert Script('str()(').call_signatures() == [] - - s = dedent("""\ - class X(): - pass - X()(""") - assert Script(s).call_signatures() == [] - assert len(Script(s, column=2).call_signatures()) == 1 - - -def test_dict_literal_in_incomplete_call(): - source = """\ - import json - - def foo(): - json.loads( - - json.load.return_value = {'foo': [], - 'bar': True} - - c = Foo() - """ - - script = Script(dedent(source), line=4, column=15) - assert script.call_signatures() - - -def test_completion_interference(): - """Seems to cause problems, see also #396.""" - cache.parser_cache.pop(None, None) - assert Script('open(').call_signatures() - - # complete something usual, before doing the same call_signatures again. - assert Script('from datetime import ').completions() - - assert Script('open(').call_signatures() - - -def test_keyword_argument_index(): - def get(source, column=None): - return Script(source, column=column).call_signatures()[0] - - assert get('sorted([], key=a').index == 2 - assert get('sorted([], key=').index == 2 - assert get('sorted([], no_key=a').index is None - - kw_func = 'def foo(a, b): pass\nfoo(b=3, a=4)' - assert get(kw_func, column=len('foo(b')).index == 0 - assert get(kw_func, column=len('foo(b=')).index == 1 - assert get(kw_func, column=len('foo(b=3, a=')).index == 0 - - kw_func_simple = 'def foo(a, b): pass\nfoo(b=4)' - assert get(kw_func_simple, column=len('foo(b')).index == 0 - assert get(kw_func_simple, column=len('foo(b=')).index == 1 - - args_func = 'def foo(*kwargs): pass\n' - assert get(args_func + 'foo(a').index == 0 - assert get(args_func + 'foo(a, b').index == 0 - - kwargs_func = 'def foo(**kwargs): pass\n' - assert get(kwargs_func + 'foo(a=2').index == 0 - assert get(kwargs_func + 'foo(a=2, b=2').index == 0 - - both = 'def foo(*args, **kwargs): pass\n' - assert get(both + 'foo(a=2').index == 1 - assert get(both + 'foo(a=2, b=2').index == 1 - assert get(both + 'foo(a=2, b=2)', column=len('foo(b=2, a=2')).index == 1 - assert get(both + 'foo(a, b, c').index == 0 - - -def test_bracket_start(): - def bracket_start(src): - signatures = Script(src).call_signatures() - assert len(signatures) == 1 - return signatures[0].bracket_start - - assert bracket_start('str(') == (1, 3) - - -def test_different_caller(): - """ - It's possible to not use names, but another function result or an array - index and then get the call signature of it. - """ - - assert_signature('[str][0](', 'str', 0) - assert_signature('[str][0]()', 'str', 0, column=len('[str][0](')) - - assert_signature('(str)(', 'str', 0) - assert_signature('(str)()', 'str', 0, column=len('(str)(')) - - -def test_in_function(): - code = dedent('''\ - class X(): - @property - def func(''') - assert not Script(code).call_signatures() - - -def test_lambda_params(): - code = dedent('''\ - my_lambda = lambda x: x+1 - my_lambda(1)''') - sig, = Script(code, column=11).call_signatures() - assert sig.index == 0 - assert sig.name == '' - assert [p.name for p in sig.params] == ['x'] diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_api/test_classes.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_api/test_classes.py deleted file mode 100644 index 64d9264..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_api/test_classes.py +++ /dev/null @@ -1,354 +0,0 @@ -""" Test all things related to the ``jedi.api_classes`` module. -""" - -from textwrap import dedent -from inspect import cleandoc - -import pytest - -from jedi import Script, defined_names, __doc__ as jedi_doc, names -from ..helpers import cwd_at -from ..helpers import TestCase - - -def test_is_keyword(): - #results = Script('import ', 1, 1, None).goto_definitions() - #assert len(results) == 1 and results[0].is_keyword is True - results = Script('str', 1, 1, None).goto_definitions() - assert len(results) == 1 and results[0].is_keyword is False - - -def make_definitions(): - """ - Return a list of definitions for parametrized tests. - - :rtype: [jedi.api_classes.BaseDefinition] - """ - source = dedent(""" - import sys - - class C: - pass - - x = C() - - def f(): - pass - - def g(): - yield - - h = lambda: None - """) - - definitions = [] - definitions += defined_names(source) - - source += dedent(""" - variable = sys or C or x or f or g or g() or h""") - lines = source.splitlines() - script = Script(source, len(lines), len('variable'), None) - definitions += script.goto_definitions() - - script2 = Script(source, 4, len('class C'), None) - definitions += script2.usages() - - source_param = "def f(a): return a" - script_param = Script(source_param, 1, len(source_param), None) - definitions += script_param.goto_assignments() - - return definitions - - -@pytest.mark.parametrize('definition', make_definitions()) -def test_basedefinition_type(definition): - assert definition.type in ('module', 'class', 'instance', 'function', - 'generator', 'statement', 'import', 'param') - - -def test_basedefinition_type_import(): - def get_types(source, **kwargs): - return set([t.type for t in Script(source, **kwargs).completions()]) - - # import one level - assert get_types('import t') == set(['module']) - assert get_types('import ') == set(['module']) - assert get_types('import datetime; datetime') == set(['module']) - - # from - assert get_types('from datetime import timedelta') == set(['class']) - assert get_types('from datetime import timedelta; timedelta') == set(['class']) - assert get_types('from json import tool') == set(['module']) - assert get_types('from json import tool; tool') == set(['module']) - - # import two levels - assert get_types('import json.tool; json') == set(['module']) - assert get_types('import json.tool; json.tool') == set(['module']) - assert get_types('import json.tool; json.tool.main') == set(['function']) - assert get_types('import json.tool') == set(['module']) - assert get_types('import json.tool', column=9) == set(['module']) - - -def test_function_call_signature_in_doc(): - defs = Script(""" - def f(x, y=1, z='a'): - pass - f""").goto_definitions() - doc = defs[0].doc - assert "f(x, y=1, z='a')" in str(doc) - - -def test_class_call_signature(): - defs = Script(""" - class Foo: - def __init__(self, x, y=1, z='a'): - pass - Foo""").goto_definitions() - doc = defs[0].doc - assert "Foo(self, x, y=1, z='a')" in str(doc) - - -def test_position_none_if_builtin(): - gotos = Script('import sys; sys.path').goto_assignments() - assert gotos[0].line is None - assert gotos[0].column is None - - -@cwd_at('.') -def test_completion_docstring(): - """ - Jedi should follow imports in certain conditions - """ - def docstr(src, result): - c = Script(src).completions()[0] - assert c.docstring(raw=True, fast=False) == cleandoc(result) - - c = Script('import jedi\njed').completions()[0] - assert c.docstring(fast=False) == cleandoc(jedi_doc) - - docstr('import jedi\njedi.Scr', cleandoc(Script.__doc__)) - - docstr('abcd=3;abcd', '') - docstr('"hello"\nabcd=3\nabcd', 'hello') - # It works with a ; as well. - docstr('"hello"\nabcd=3;abcd', 'hello') - # Shouldn't work with a tuple. - docstr('"hello",0\nabcd=3\nabcd', '') - - -def test_completion_params(): - c = Script('import string; string.capwords').completions()[0] - assert [p.name for p in c.params] == ['s', 'sep'] - - -def test_signature_params(): - def check(defs): - params = defs[0].params - assert len(params) == 1 - assert params[0].name == 'bar' - - s = dedent(''' - def foo(bar): - pass - foo''') - - check(Script(s).goto_definitions()) - - check(Script(s).goto_assignments()) - check(Script(s + '\nbar=foo\nbar').goto_assignments()) - - -def test_param_endings(): - """ - Params should be represented without the comma and whitespace they have - around them. - """ - sig = Script('def x(a, b=5, c=""): pass\n x(').call_signatures()[0] - assert [p.description for p in sig.params] == ['a', 'b=5', 'c=""'] - - -class TestIsDefinition(TestCase): - def _def(self, source, index=-1): - return names(dedent(source), references=True, all_scopes=True)[index] - - def _bool_is_definitions(self, source): - ns = names(dedent(source), references=True, all_scopes=True) - # Assure that names are definitely sorted. - ns = sorted(ns, key=lambda name: (name.line, name.column)) - return [name.is_definition() for name in ns] - - def test_name(self): - d = self._def('name') - assert d.name == 'name' - assert not d.is_definition() - - def test_stmt(self): - src = 'a = f(x)' - d = self._def(src, 0) - assert d.name == 'a' - assert d.is_definition() - d = self._def(src, 1) - assert d.name == 'f' - assert not d.is_definition() - d = self._def(src) - assert d.name == 'x' - assert not d.is_definition() - - def test_import(self): - assert self._bool_is_definitions('import x as a') == [False, True] - assert self._bool_is_definitions('from x import y') == [False, True] - assert self._bool_is_definitions('from x.z import y') == [False, False, True] - - -class TestParent(TestCase): - def _parent(self, source, line=None, column=None): - defs = Script(dedent(source), line, column).goto_assignments() - assert len(defs) == 1 - return defs[0].parent() - - def test_parent(self): - parent = self._parent('foo=1\nfoo') - assert parent.type == 'module' - - parent = self._parent(''' - def spam(): - if 1: - y=1 - y''') - assert parent.name == 'spam' - assert parent.parent().type == 'module' - - def test_on_function(self): - parent = self._parent('''\ - def spam(): - pass''', 1, len('def spam')) - assert parent.name == '' - assert parent.type == 'module' - - def test_parent_on_completion(self): - parent = Script(dedent('''\ - class Foo(): - def bar(): pass - Foo().bar''')).completions()[0].parent() - assert parent.name == 'Foo' - assert parent.type == 'instance' - - parent = Script('str.join').completions()[0].parent() - assert parent.name == 'str' - assert parent.type == 'class' - - -def test_type(): - """ - Github issue #397, type should never raise an error. - """ - for c in Script('import os; os.path.').completions(): - assert c.type - - -class TestGotoAssignments(TestCase): - """ - This tests the BaseDefinition.goto_assignments function, not the jedi - function. They are not really different in functionality, but really - different as an implementation. - """ - def test_repetition(self): - defs = names('a = 1; a', references=True, definitions=False) - # Repeat on the same variable. Shouldn't change once we're on a - # definition. - for _ in range(3): - assert len(defs) == 1 - ass = defs[0].goto_assignments() - assert ass[0].description == 'a = 1' - - def test_named_params(self): - src = """\ - def foo(a=1, bar=2): - pass - foo(bar=1) - """ - bar = names(dedent(src), references=True)[-1] - param = bar.goto_assignments()[0] - assert param.start_pos == (1, 13) - assert param.type == 'param' - - def test_class_call(self): - src = 'from threading import Thread; Thread(group=1)' - n = names(src, references=True)[-1] - assert n.name == 'group' - param_def = n.goto_assignments()[0] - assert param_def.name == 'group' - assert param_def.type == 'param' - - def test_parentheses(self): - n = names('("").upper', references=True)[-1] - assert n.goto_assignments()[0].name == 'upper' - - def test_import(self): - nms = names('from json import load', references=True) - assert nms[0].name == 'json' - assert nms[0].type == 'import' - n = nms[0].goto_assignments()[0] - assert n.name == 'json' - assert n.type == 'module' - - assert nms[1].name == 'load' - assert nms[1].type == 'import' - n = nms[1].goto_assignments()[0] - assert n.name == 'load' - assert n.type == 'function' - - nms = names('import os; os.path', references=True) - assert nms[0].name == 'os' - assert nms[0].type == 'import' - n = nms[0].goto_assignments()[0] - assert n.name == 'os' - assert n.type == 'module' - - n = nms[2].goto_assignments()[0] - assert n.name == 'path' - assert n.type == 'import' - - nms = names('import os.path', references=True) - n = nms[0].goto_assignments()[0] - assert n.name == 'os' - assert n.type == 'module' - n = nms[1].goto_assignments()[0] - # This is very special, normally the name doesn't chance, but since - # os.path is a sys.modules hack, it does. - assert n.name in ('ntpath', 'posixpath', 'os2emxpath') - assert n.type == 'module' - - def test_import_alias(self): - nms = names('import json as foo', references=True) - assert nms[0].name == 'json' - assert nms[0].type == 'import' - n = nms[0].goto_assignments()[0] - assert n.name == 'json' - assert n.type == 'module' - - assert nms[1].name == 'foo' - assert nms[1].type == 'import' - ass = nms[1].goto_assignments() - assert len(ass) == 1 - assert ass[0].name == 'json' - assert ass[0].type == 'module' - - -def test_added_equals_to_params(): - def run(rest_source): - source = dedent(""" - def foo(bar, baz): - pass - """) - results = Script(source + rest_source).completions() - assert len(results) == 1 - return results[0] - - assert run('foo(bar').name_with_symbols == 'bar=' - assert run('foo(bar').complete == '=' - assert run('foo(bar, baz').complete == '=' - assert run(' bar').name_with_symbols == 'bar' - assert run(' bar').complete == '' - x = run('foo(bar=isins').name_with_symbols - assert x == 'isinstance' diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_api/test_completion_context.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_api/test_completion_context.py deleted file mode 100644 index fee4f0e..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_api/test_completion_context.py +++ /dev/null @@ -1,9 +0,0 @@ -from textwrap import dedent -from jedi import Script - - -def test_in_whitespace(): - code = dedent(''' - def x(): - pass''') - assert len(Script(code, column=2).completions()) > 20 diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_api/test_defined_names.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_api/test_defined_names.py deleted file mode 100644 index aae1f6c..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_api/test_defined_names.py +++ /dev/null @@ -1,92 +0,0 @@ -""" -Tests for `api.defined_names`. -""" - -from textwrap import dedent - -from jedi import defined_names, names -from ..helpers import TestCase - - -class TestDefinedNames(TestCase): - def assert_definition_names(self, definitions, names_): - assert [d.name for d in definitions] == names_ - - def check_defined_names(self, source, names_): - definitions = names(dedent(source)) - self.assert_definition_names(definitions, names_) - return definitions - - def test_get_definitions_flat(self): - self.check_defined_names(""" - import module - class Class: - pass - def func(): - pass - data = None - """, ['module', 'Class', 'func', 'data']) - - def test_dotted_assignment(self): - self.check_defined_names(""" - x = Class() - x.y.z = None - """, ['x', 'z']) # TODO is this behavior what we want? - - def test_multiple_assignment(self): - self.check_defined_names(""" - x = y = None - """, ['x', 'y']) - - def test_multiple_imports(self): - self.check_defined_names(""" - from module import a, b - from another_module import * - """, ['a', 'b']) - - def test_nested_definitions(self): - definitions = self.check_defined_names(""" - class Class: - def f(): - pass - def g(): - pass - """, ['Class']) - subdefinitions = definitions[0].defined_names() - self.assert_definition_names(subdefinitions, ['f', 'g']) - self.assertEqual([d.full_name for d in subdefinitions], - ['Class.f', 'Class.g']) - - def test_nested_class(self): - definitions = self.check_defined_names(""" - class L1: - class L2: - class L3: - def f(): pass - def f(): pass - def f(): pass - def f(): pass - """, ['L1', 'f']) - subdefs = definitions[0].defined_names() - subsubdefs = subdefs[0].defined_names() - self.assert_definition_names(subdefs, ['L2', 'f']) - self.assert_definition_names(subsubdefs, ['L3', 'f']) - self.assert_definition_names(subsubdefs[0].defined_names(), ['f']) - - -def test_follow_imports(): - # github issue #344 - imp = defined_names('import datetime')[0] - assert imp.name == 'datetime' - datetime_names = [str(d.name) for d in imp.defined_names()] - assert 'timedelta' in datetime_names - - -def test_names_twice(): - source = dedent(''' - def lol(): - pass - ''') - - defs = names(source=source) - assert defs[0].defined_names() == [] diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_api/test_full_name.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_api/test_full_name.py deleted file mode 100644 index b96c548..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_api/test_full_name.py +++ /dev/null @@ -1,91 +0,0 @@ -""" -Tests for :attr:`.BaseDefinition.full_name`. - -There are three kinds of test: - -#. Test classes derived from :class:`MixinTestFullName`. - Child class defines :attr:`.operation` to alter how - the api definition instance is created. - -#. :class:`TestFullDefinedName` is to test combination of - ``obj.full_name`` and ``jedi.defined_names``. - -#. Misc single-function tests. -""" - -import textwrap - -import pytest - -import jedi -from ..helpers import TestCase - - -class MixinTestFullName(object): - operation = None - - def check(self, source, desired): - script = jedi.Script(textwrap.dedent(source)) - definitions = getattr(script, type(self).operation)() - for d in definitions: - self.assertEqual(d.full_name, desired) - - def test_os_path_join(self): - self.check('import os; os.path.join', 'os.path.join') - - def test_builtin(self): - self.check('TypeError', 'TypeError') - - -class TestFullNameWithGotoDefinitions(MixinTestFullName, TestCase): - operation = 'goto_definitions' - - @pytest.mark.skipif('sys.version_info[0] < 3', reason='Python 2 also yields None.') - def test_tuple_mapping(self): - self.check(""" - import re - any_re = re.compile('.*') - any_re""", '_sre.compile.SRE_Pattern') - - def test_from_import(self): - self.check('from os import path', 'os.path') - - -class TestFullNameWithCompletions(MixinTestFullName, TestCase): - operation = 'completions' - - -class TestFullDefinedName(TestCase): - """ - Test combination of ``obj.full_name`` and ``jedi.defined_names``. - """ - - def check(self, source, desired): - definitions = jedi.defined_names(textwrap.dedent(source)) - full_names = [d.full_name for d in definitions] - self.assertEqual(full_names, desired) - - def test_local_names(self): - self.check(""" - def f(): pass - class C: pass - """, ['f', 'C']) - - def test_imports(self): - self.check(""" - import os - from os import path - from os.path import join - from os import path as opath - """, ['os', 'os.path', 'os.path.join', 'os.path']) - - -def test_sub_module(): - """ - ``full_name needs to check sys.path to actually find it's real path module - path. - """ - defs = jedi.Script('from jedi.api import classes; classes').goto_definitions() - assert [d.full_name for d in defs] == ['jedi.api.classes'] - defs = jedi.Script('import jedi.api; jedi.api').goto_definitions() - assert [d.full_name for d in defs] == ['jedi.api'] diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_api/test_interpreter.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_api/test_interpreter.py deleted file mode 100644 index 0976241..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_api/test_interpreter.py +++ /dev/null @@ -1,160 +0,0 @@ -""" -Tests of ``jedi.api.Interpreter``. -""" - -from ..helpers import TestCase -import jedi -from jedi._compatibility import is_py33 -from jedi.evaluate.compiled import mixed - -class _GlobalNameSpace(): - class SideEffectContainer(): - pass - - -def get_completion(source, namespace): - i = jedi.Interpreter(source, [namespace]) - completions = i.completions() - assert len(completions) == 1 - return completions[0] - - -def test_builtin_details(): - import keyword - - class EmptyClass: - pass - - variable = EmptyClass() - - def func(): - pass - - cls = get_completion('EmptyClass', locals()) - var = get_completion('variable', locals()) - f = get_completion('func', locals()) - m = get_completion('keyword', locals()) - assert cls.type == 'class' - assert var.type == 'instance' - assert f.type == 'function' - assert m.type == 'module' - - -def test_nested_resolve(): - class XX(): - def x(): - pass - - cls = get_completion('XX', locals()) - func = get_completion('XX.x', locals()) - assert func.start_pos == (cls.start_pos[0] + 1, 12) - - -def test_side_effect_completion(): - """ - In the repl it's possible to cause side effects that are not documented in - Python code, however we want references to Python code as well. Therefore - we need some mixed kind of magic for tests. - """ - _GlobalNameSpace.SideEffectContainer.foo = 1 - side_effect = get_completion('SideEffectContainer', _GlobalNameSpace.__dict__) - - # It's a class that contains MixedObject. - assert isinstance(side_effect._definition.base, mixed.MixedObject) - foo = get_completion('SideEffectContainer.foo', _GlobalNameSpace.__dict__) - assert foo.name == 'foo' - - -class TestInterpreterAPI(TestCase): - def check_interpreter_complete(self, source, namespace, completions, - **kwds): - script = jedi.Interpreter(source, [namespace], **kwds) - cs = script.completions() - actual = [c.name for c in cs] - self.assertEqual(sorted(actual), sorted(completions)) - - def test_complete_raw_function(self): - from os.path import join - self.check_interpreter_complete('join("").up', - locals(), - ['upper']) - - def test_complete_raw_function_different_name(self): - from os.path import join as pjoin - self.check_interpreter_complete('pjoin("").up', - locals(), - ['upper']) - - def test_complete_raw_module(self): - import os - self.check_interpreter_complete('os.path.join("a").up', - locals(), - ['upper']) - - def test_complete_raw_instance(self): - import datetime - dt = datetime.datetime(2013, 1, 1) - completions = ['time', 'timetz', 'timetuple'] - if is_py33: - completions += ['timestamp'] - self.check_interpreter_complete('(dt - dt).ti', - locals(), - completions) - - def test_list(self): - array = ['haha', 1] - self.check_interpreter_complete('array[0].uppe', - locals(), - ['upper']) - self.check_interpreter_complete('array[0].real', - locals(), - []) - - # something different, no index given, still just return the right - self.check_interpreter_complete('array[int].real', - locals(), - ['real']) - self.check_interpreter_complete('array[int()].real', - locals(), - ['real']) - # inexistent index - self.check_interpreter_complete('array[2].upper', - locals(), - ['upper']) - - def test_slice(self): - class Foo(): - bar = [] - baz = 'xbarx' - self.check_interpreter_complete('getattr(Foo, baz[1:-1]).append', - locals(), - ['append']) - - def test_getitem_side_effects(self): - class Foo(): - def __getitem__(self, index): - # possible side effects here, should therefore not call this. - return index - - foo = Foo() - self.check_interpreter_complete('foo[0].', locals(), []) - - def test_property_error(self): - class Foo(): - @property - def bar(self): - raise ValueError - - foo = Foo() - self.check_interpreter_complete('foo.bar', locals(), ['bar']) - self.check_interpreter_complete('foo.bar.baz', locals(), []) - - def test_param_completion(self): - def foo(bar): - pass - - lambd = lambda xyz: 3 - - self.check_interpreter_complete('foo(bar', locals(), ['bar']) - # TODO we're not yet using the Python3.5 inspect.signature, yet. - assert not jedi.Interpreter('lambd(xyz', [locals()]).completions() diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_api/test_unicode.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_api/test_unicode.py deleted file mode 100644 index bcd8ad4..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_api/test_unicode.py +++ /dev/null @@ -1,66 +0,0 @@ -# -*- coding: utf-8 -*- -""" -All character set and unicode related tests. -""" -from jedi import Script -from jedi._compatibility import u, unicode - - -def test_unicode_script(): - """ normally no unicode objects are being used. (<=2.7) """ - s = unicode("import datetime; datetime.timedelta") - completions = Script(s).completions() - assert len(completions) - assert type(completions[0].description) is unicode - - s = u("author='öä'; author") - completions = Script(s).completions() - x = completions[0].description - assert type(x) is unicode - - s = u("#-*- coding: iso-8859-1 -*-\nauthor='öä'; author") - s = s.encode('latin-1') - completions = Script(s).completions() - assert type(completions[0].description) is unicode - - -def test_unicode_attribute(): - """ github jedi-vim issue #94 """ - s1 = u('#-*- coding: utf-8 -*-\nclass Person():\n' - ' name = "e"\n\nPerson().name.') - completions1 = Script(s1).completions() - assert 'strip' in [c.name for c in completions1] - s2 = u('#-*- coding: utf-8 -*-\nclass Person():\n' - ' name = "é"\n\nPerson().name.') - completions2 = Script(s2).completions() - assert 'strip' in [c.name for c in completions2] - - -def test_multibyte_script(): - """ `jedi.Script` must accept multi-byte string source. """ - try: - code = u("import datetime; datetime.d") - comment = u("# multi-byte comment あいうえおä") - s = (u('%s\n%s') % (code, comment)).encode('utf-8') - except NameError: - pass # python 3 has no unicode method - else: - assert len(Script(s, 1, len(code)).completions()) - - -def test_goto_definition_at_zero(): - """At zero usually sometimes raises unicode issues.""" - assert Script("a", 1, 1).goto_definitions() == [] - s = Script("str", 1, 1).goto_definitions() - assert len(s) == 1 - assert list(s)[0].description == 'class str' - assert Script("", 1, 0).goto_definitions() == [] - - -def test_complete_at_zero(): - s = Script("str", 1, 3).completions() - assert len(s) == 1 - assert list(s)[0].name == 'str' - - s = Script("", 1, 0).completions() - assert len(s) > 0 diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_api/test_usages.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_api/test_usages.py deleted file mode 100644 index 1325e41..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_api/test_usages.py +++ /dev/null @@ -1,6 +0,0 @@ -import jedi - - -def test_import_usage(): - s = jedi.Script("from .. import foo", line=1, column=18, path="foo.py") - assert [usage.line for usage in s.usages()] == [1] diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_cache.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_cache.py deleted file mode 100644 index 7cff4d4..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_cache.py +++ /dev/null @@ -1,109 +0,0 @@ -""" -Test all things related to the ``jedi.cache`` module. -""" - -import time - -import pytest - -import jedi -from jedi import settings, cache -from jedi.parser.utils import ParserCacheItem, ParserPickling - - -ParserPicklingCls = type(ParserPickling) -ParserPickling = ParserPicklingCls() - - -def test_modulepickling_change_cache_dir(monkeypatch, tmpdir): - """ - ParserPickling should not save old cache when cache_directory is changed. - - See: `#168 `_ - """ - dir_1 = str(tmpdir.mkdir('first')) - dir_2 = str(tmpdir.mkdir('second')) - - item_1 = ParserCacheItem('fake parser 1') - item_2 = ParserCacheItem('fake parser 2') - path_1 = 'fake path 1' - path_2 = 'fake path 2' - - monkeypatch.setattr(settings, 'cache_directory', dir_1) - ParserPickling.save_parser(path_1, item_1) - cached = load_stored_item(ParserPickling, path_1, item_1) - assert cached == item_1.parser - - monkeypatch.setattr(settings, 'cache_directory', dir_2) - ParserPickling.save_parser(path_2, item_2) - cached = load_stored_item(ParserPickling, path_1, item_1) - assert cached is None - - -def load_stored_item(cache, path, item): - """Load `item` stored at `path` in `cache`.""" - return cache.load_parser(path, item.change_time - 1) - - -@pytest.mark.usefixtures("isolated_jedi_cache") -def test_modulepickling_delete_incompatible_cache(): - item = ParserCacheItem('fake parser') - path = 'fake path' - - cache1 = ParserPicklingCls() - cache1.version = 1 - cache1.save_parser(path, item) - cached1 = load_stored_item(cache1, path, item) - assert cached1 == item.parser - - cache2 = ParserPicklingCls() - cache2.version = 2 - cached2 = load_stored_item(cache2, path, item) - assert cached2 is None - - -@pytest.mark.skipif('True', message='Currently the star import cache is not enabled.') -def test_star_import_cache_duration(): - new = 0.01 - old, jedi.settings.star_import_cache_validity = \ - jedi.settings.star_import_cache_validity, new - - dct = cache._time_caches['star_import_cache_validity'] - old_dct = dict(dct) - dct.clear() # first empty... - # path needs to be not-None (otherwise caching effects are not visible) - jedi.Script('', 1, 0, '').completions() - time.sleep(2 * new) - jedi.Script('', 1, 0, '').completions() - - # reset values - jedi.settings.star_import_cache_validity = old - assert len(dct) == 1 - dct = old_dct - cache._star_import_cache = {} - - -def test_cache_call_signatures(): - """ - See github issue #390. - """ - def check(column, call_name, path=None): - assert jedi.Script(s, 1, column, path).call_signatures()[0].name == call_name - - s = 'str(int())' - - for i in range(3): - check(8, 'int') - check(4, 'str') - # Can keep doing these calls and always get the right result. - - # Now lets specify a source_path of boo and alternate these calls, it - # should still work. - for i in range(3): - check(8, 'int', 'boo') - check(4, 'str', 'boo') - - -def test_cache_line_split_issues(): - """Should still work even if there's a newline.""" - assert jedi.Script('int(\n').call_signatures()[0].name == 'int' diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_debug.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_debug.py deleted file mode 100644 index 0033107..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_debug.py +++ /dev/null @@ -1,9 +0,0 @@ -import jedi -from jedi import debug - -def test_simple(): - jedi.set_debug_function() - debug.speed('foo') - debug.dbg('bar') - debug.warning('baz') - jedi.set_debug_function(None, False, False, False) diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/__init__.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/absolute_import/local_module.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/absolute_import/local_module.py deleted file mode 100644 index aa4bf00..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/absolute_import/local_module.py +++ /dev/null @@ -1,14 +0,0 @@ -""" -This is a module that imports the *standard library* unittest, -despite there being a local "unittest" module. It specifies that it -wants the stdlib one with the ``absolute_import`` __future__ import. - -The twisted equivalent of this module is ``twisted.trial._synctest``. -""" -from __future__ import absolute_import - -import unittest - - -class Assertions(unittest.TestCase): - pass diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/absolute_import/unittest.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/absolute_import/unittest.py deleted file mode 100644 index eee1e93..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/absolute_import/unittest.py +++ /dev/null @@ -1,14 +0,0 @@ -""" -This is a module that shadows a builtin (intentionally). - -It imports a local module, which in turn imports stdlib unittest (the -name shadowed by this module). If that is properly resolved, there's -no problem. However, if jedi doesn't understand absolute_imports, it -will get this module again, causing infinite recursion. -""" -from local_module import Assertions - - -class TestCase(Assertions): - def test(self): - self.assertT diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/buildout_project/bin/app b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/buildout_project/bin/app deleted file mode 100644 index 7394d2d..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/buildout_project/bin/app +++ /dev/null @@ -1,12 +0,0 @@ -#!/usr/bin/python - -import sys -sys.path[0:0] = [ - '/usr/lib/python3.4/site-packages', - '/tmp/.buildout/eggs/important_package.egg' -] - -import important_package - -if __name__ == '__main__': - sys.exit(important_package.main()) diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/buildout_project/bin/binary_file b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/buildout_project/bin/binary_file deleted file mode 100644 index f1ad755..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/buildout_project/bin/binary_file +++ /dev/null @@ -1 +0,0 @@ -PNG diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/buildout_project/bin/empty_file b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/buildout_project/bin/empty_file deleted file mode 100644 index e69de29..0000000 diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/buildout_project/buildout.cfg b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/buildout_project/buildout.cfg deleted file mode 100644 index e69de29..0000000 diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/buildout_project/src/proj_name/module_name.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/buildout_project/src/proj_name/module_name.py deleted file mode 100644 index e69de29..0000000 diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/flask-site-packages/flask/__init__.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/flask-site-packages/flask/__init__.py deleted file mode 100644 index e876bc1..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/flask-site-packages/flask/__init__.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/flask-site-packages/flask/ext/__init__.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/flask-site-packages/flask/ext/__init__.py deleted file mode 100644 index 8b13789..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/flask-site-packages/flask/ext/__init__.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/flask-site-packages/flask_baz/__init__.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/flask-site-packages/flask_baz/__init__.py deleted file mode 100644 index e9b3fff..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/flask-site-packages/flask_baz/__init__.py +++ /dev/null @@ -1 +0,0 @@ -Baz = 1 diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/flask-site-packages/flask_foo.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/flask-site-packages/flask_foo.py deleted file mode 100644 index 0b910b8..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/flask-site-packages/flask_foo.py +++ /dev/null @@ -1,2 +0,0 @@ -class Foo(object): - pass diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/flask-site-packages/flaskext/__init__.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/flask-site-packages/flaskext/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/flask-site-packages/flaskext/bar.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/flask-site-packages/flaskext/bar.py deleted file mode 100644 index 6629f9a..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/flask-site-packages/flaskext/bar.py +++ /dev/null @@ -1,2 +0,0 @@ -class Bar(object): - pass diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/flask-site-packages/flaskext/moo/__init__.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/flask-site-packages/flaskext/moo/__init__.py deleted file mode 100644 index 266e809..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/flask-site-packages/flaskext/moo/__init__.py +++ /dev/null @@ -1 +0,0 @@ -Moo = 1 diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/init_extension_module/__init__.cpython-34m.so b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/init_extension_module/__init__.cpython-34m.so deleted file mode 100755 index abfadc3..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/init_extension_module/__init__.cpython-34m.so and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/init_extension_module/module.c b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/init_extension_module/module.c deleted file mode 100644 index bfa06f6..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/init_extension_module/module.c +++ /dev/null @@ -1,15 +0,0 @@ -#include "Python.h" - -static struct PyModuleDef module = { - PyModuleDef_HEAD_INIT, - "init_extension_module", - NULL, - -1, - NULL -}; - -PyMODINIT_FUNC PyInit_init_extension_module(void){ - PyObject *m = PyModule_Create(&module); - PyModule_AddObject(m, "foo", Py_None); - return m; -} diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/init_extension_module/setup.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/init_extension_module/setup.py deleted file mode 100644 index 5ce0517..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/init_extension_module/setup.py +++ /dev/null @@ -1,10 +0,0 @@ -from distutils.core import setup, Extension - -setup(name='init_extension_module', - version='0.0', - description='', - ext_modules=[ - Extension('init_extension_module.__init__', - sources=['module.c']) - ] -) diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/namespace_package/ns1/pkg/__init__.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/namespace_package/ns1/pkg/__init__.py deleted file mode 100644 index bc10ee2..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/namespace_package/ns1/pkg/__init__.py +++ /dev/null @@ -1,9 +0,0 @@ -foo = 'ns1!' - -# this is a namespace package -try: - import pkg_resources - pkg_resources.declare_namespace(__name__) -except ImportError: - import pkgutil - __path__ = pkgutil.extend_path(__path__, __name__) diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/namespace_package/ns1/pkg/ns1_file.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/namespace_package/ns1/pkg/ns1_file.py deleted file mode 100644 index 940279f..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/namespace_package/ns1/pkg/ns1_file.py +++ /dev/null @@ -1 +0,0 @@ -foo = 'ns1_file!' diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/namespace_package/ns1/pkg/ns1_folder/__init__.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/namespace_package/ns1/pkg/ns1_folder/__init__.py deleted file mode 100644 index 9eeeb29..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/namespace_package/ns1/pkg/ns1_folder/__init__.py +++ /dev/null @@ -1 +0,0 @@ -foo = 'ns1_folder!' diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/namespace_package/ns2/pkg/ns2_file.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/namespace_package/ns2/pkg/ns2_file.py deleted file mode 100644 index e87d7d8..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/namespace_package/ns2/pkg/ns2_file.py +++ /dev/null @@ -1 +0,0 @@ -foo = 'ns2_file!' diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/namespace_package/ns2/pkg/ns2_folder/__init__.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/namespace_package/ns2/pkg/ns2_folder/__init__.py deleted file mode 100644 index 70b24ae..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/namespace_package/ns2/pkg/ns2_folder/__init__.py +++ /dev/null @@ -1 +0,0 @@ -foo = 'ns2_folder!' diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/namespace_package/ns2/pkg/ns2_folder/nested/__init__.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/namespace_package/ns2/pkg/ns2_folder/nested/__init__.py deleted file mode 100644 index fbba1db..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/namespace_package/ns2/pkg/ns2_folder/nested/__init__.py +++ /dev/null @@ -1 +0,0 @@ -foo = 'nested!' diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/nested_namespaces/__init__.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/nested_namespaces/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/nested_namespaces/namespace/__init__.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/nested_namespaces/namespace/__init__.py deleted file mode 100644 index 42e33a7..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/nested_namespaces/namespace/__init__.py +++ /dev/null @@ -1,4 +0,0 @@ -try: - __import__('pkg_resources').declare_namespace(__name__) -except ImportError: - pass diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/nested_namespaces/namespace/pkg/__init__.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/nested_namespaces/namespace/pkg/__init__.py deleted file mode 100644 index 3c37820..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/nested_namespaces/namespace/pkg/__init__.py +++ /dev/null @@ -1 +0,0 @@ -CONST = 1 diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/not_in_sys_path/__init__.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/not_in_sys_path/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/not_in_sys_path/not_in_sys_path.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/not_in_sys_path/not_in_sys_path.py deleted file mode 100644 index 8943d8d..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/not_in_sys_path/not_in_sys_path.py +++ /dev/null @@ -1 +0,0 @@ -value = 3 diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/not_in_sys_path/not_in_sys_path_package/__init__.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/not_in_sys_path/not_in_sys_path_package/__init__.py deleted file mode 100644 index 5ef1a74..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/not_in_sys_path/not_in_sys_path_package/__init__.py +++ /dev/null @@ -1 +0,0 @@ -value = 'package' diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/not_in_sys_path/not_in_sys_path_package/module.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/not_in_sys_path/not_in_sys_path_package/module.py deleted file mode 100644 index 364dd03..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/not_in_sys_path/not_in_sys_path_package/module.py +++ /dev/null @@ -1 +0,0 @@ -value = 'package.module' diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/not_in_sys_path/pkg/__init__.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/not_in_sys_path/pkg/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/not_in_sys_path/pkg/module.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/not_in_sys_path/pkg/module.py deleted file mode 100644 index 53c44ca..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/not_in_sys_path/pkg/module.py +++ /dev/null @@ -1,7 +0,0 @@ -from not_in_sys_path import not_in_sys_path -from not_in_sys_path import not_in_sys_path_package -from not_in_sys_path.not_in_sys_path_package import module - -not_in_sys_path.value -not_in_sys_path_package.value -module.value diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/sample_venvs/venv27/lib/python2.7/site-packages/dir-from-foo-pth/__init__.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/sample_venvs/venv27/lib/python2.7/site-packages/dir-from-foo-pth/__init__.py deleted file mode 100644 index 2a1d870..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/sample_venvs/venv27/lib/python2.7/site-packages/dir-from-foo-pth/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -# This file is here to force git to create the directory, as *.pth files only -# add existing directories. diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/sample_venvs/venv27/lib/python2.7/site-packages/egg_link.egg-link b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/sample_venvs/venv27/lib/python2.7/site-packages/egg_link.egg-link deleted file mode 100644 index dde9b7d..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/sample_venvs/venv27/lib/python2.7/site-packages/egg_link.egg-link +++ /dev/null @@ -1 +0,0 @@ -/path/from/egg-link diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/sample_venvs/venv27/lib/python2.7/site-packages/foo.pth b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/sample_venvs/venv27/lib/python2.7/site-packages/foo.pth deleted file mode 100644 index 8850168..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/sample_venvs/venv27/lib/python2.7/site-packages/foo.pth +++ /dev/null @@ -1 +0,0 @@ -./dir-from-foo-pth diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/sample_venvs/venv27/lib/python2.7/site-packages/import_smth.pth b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/sample_venvs/venv27/lib/python2.7/site-packages/import_smth.pth deleted file mode 100644 index 72b006a..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/sample_venvs/venv27/lib/python2.7/site-packages/import_smth.pth +++ /dev/null @@ -1 +0,0 @@ -import smth; smth.extend_path() \ No newline at end of file diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/sample_venvs/venv27/lib/python2.7/site-packages/relative.egg-link b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/sample_venvs/venv27/lib/python2.7/site-packages/relative.egg-link deleted file mode 100644 index 7a9a615..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/sample_venvs/venv27/lib/python2.7/site-packages/relative.egg-link +++ /dev/null @@ -1 +0,0 @@ -./relative/egg-link/path diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/sample_venvs/venv27/lib/python2.7/site-packages/smth.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/sample_venvs/venv27/lib/python2.7/site-packages/smth.py deleted file mode 100644 index 3e3008d..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/sample_venvs/venv27/lib/python2.7/site-packages/smth.py +++ /dev/null @@ -1,6 +0,0 @@ -import sys -sys.path.append('/path/from/smth.py') - - -def extend_path(): - sys.path.append('/path/from/smth.py:extend_path') diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/sample_venvs/venv34/lib/python3.4/site-packages/dir-from-foo-pth/__init__.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/sample_venvs/venv34/lib/python3.4/site-packages/dir-from-foo-pth/__init__.py deleted file mode 100644 index 2a1d870..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/sample_venvs/venv34/lib/python3.4/site-packages/dir-from-foo-pth/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -# This file is here to force git to create the directory, as *.pth files only -# add existing directories. diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/sample_venvs/venv34/lib/python3.4/site-packages/egg_link.egg-link b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/sample_venvs/venv34/lib/python3.4/site-packages/egg_link.egg-link deleted file mode 100644 index dde9b7d..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/sample_venvs/venv34/lib/python3.4/site-packages/egg_link.egg-link +++ /dev/null @@ -1 +0,0 @@ -/path/from/egg-link diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/sample_venvs/venv34/lib/python3.4/site-packages/foo.pth b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/sample_venvs/venv34/lib/python3.4/site-packages/foo.pth deleted file mode 100644 index 8850168..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/sample_venvs/venv34/lib/python3.4/site-packages/foo.pth +++ /dev/null @@ -1 +0,0 @@ -./dir-from-foo-pth diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/sample_venvs/venv34/lib/python3.4/site-packages/import_smth.pth b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/sample_venvs/venv34/lib/python3.4/site-packages/import_smth.pth deleted file mode 100644 index 72b006a..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/sample_venvs/venv34/lib/python3.4/site-packages/import_smth.pth +++ /dev/null @@ -1 +0,0 @@ -import smth; smth.extend_path() \ No newline at end of file diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/sample_venvs/venv34/lib/python3.4/site-packages/relative.egg-link b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/sample_venvs/venv34/lib/python3.4/site-packages/relative.egg-link deleted file mode 100644 index 7a9a615..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/sample_venvs/venv34/lib/python3.4/site-packages/relative.egg-link +++ /dev/null @@ -1 +0,0 @@ -./relative/egg-link/path diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/sample_venvs/venv34/lib/python3.4/site-packages/smth.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/sample_venvs/venv34/lib/python3.4/site-packages/smth.py deleted file mode 100644 index 3e3008d..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/sample_venvs/venv34/lib/python3.4/site-packages/smth.py +++ /dev/null @@ -1,6 +0,0 @@ -import sys -sys.path.append('/path/from/smth.py') - - -def extend_path(): - sys.path.append('/path/from/smth.py:extend_path') diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/test_absolute_import.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/test_absolute_import.py deleted file mode 100644 index a45bffa..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/test_absolute_import.py +++ /dev/null @@ -1,40 +0,0 @@ -""" -Tests ``from __future__ import absolute_import`` (only important for -Python 2.X) -""" -import jedi -from jedi._compatibility import u -from jedi.parser import ParserWithRecovery, load_grammar -from .. import helpers - - -def test_explicit_absolute_imports(): - """ - Detect modules with ``from __future__ import absolute_import``. - """ - parser = ParserWithRecovery(load_grammar(), u("from __future__ import absolute_import"), "test.py") - assert parser.module.has_explicit_absolute_import - - -def test_no_explicit_absolute_imports(): - """ - Detect modules without ``from __future__ import absolute_import``. - """ - parser = ParserWithRecovery(load_grammar(), u("1"), "test.py") - assert not parser.module.has_explicit_absolute_import - - -def test_dont_break_imports_without_namespaces(): - """ - The code checking for ``from __future__ import absolute_import`` shouldn't - assume that all imports have non-``None`` namespaces. - """ - src = u("from __future__ import absolute_import\nimport xyzzy") - parser = ParserWithRecovery(load_grammar(), src, "test.py") - assert parser.module.has_explicit_absolute_import - - -@helpers.cwd_at("test/test_evaluate/absolute_import") -def test_can_complete_when_shadowing(): - script = jedi.Script(path="unittest.py") - assert script.completions() diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/test_annotations.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/test_annotations.py deleted file mode 100644 index 67fe84e..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/test_annotations.py +++ /dev/null @@ -1,60 +0,0 @@ -from textwrap import dedent - -import jedi -import pytest - - -@pytest.mark.skipif('sys.version_info[0] < 3') -def test_simple_annotations(): - """ - Annotations only exist in Python 3. - If annotations adhere to PEP-0484, we use them (they override inference), - else they are parsed but ignored - """ - - source = dedent("""\ - def annot(a:3): - return a - - annot('')""") - - assert [d.name for d in jedi.Script(source, ).goto_definitions()] == ['str'] - - source = dedent("""\ - - def annot_ret(a:3) -> 3: - return a - - annot_ret('')""") - assert [d.name for d in jedi.Script(source, ).goto_definitions()] == ['str'] - - source = dedent("""\ - def annot(a:int): - return a - - annot('')""") - - assert [d.name for d in jedi.Script(source, ).goto_definitions()] == ['int'] - - -@pytest.mark.skipif('sys.version_info[0] < 3') -@pytest.mark.parametrize('reference', [ - 'assert 1', - '1', - 'def x(): pass', - '1, 2', - r'1\n' -]) -def test_illegal_forward_references(reference): - source = 'def foo(bar: "%s"): bar' % reference - - assert not jedi.Script(source).goto_definitions() - - -@pytest.mark.skipif('sys.version_info[0] < 3') -def test_lambda_forward_references(): - source = 'def foo(bar: "lambda: 3"): bar' - - # For now just receiving the 3 is ok. I'm doubting that this is what we - # want. We also execute functions. Should we only execute classes? - assert jedi.Script(source).goto_definitions() diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/test_buildout_detection.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/test_buildout_detection.py deleted file mode 100644 index c5c6556..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/test_buildout_detection.py +++ /dev/null @@ -1,89 +0,0 @@ -import os -from textwrap import dedent - -from jedi._compatibility import u -from jedi.evaluate.sys_path import (_get_parent_dir_with_file, - _get_buildout_scripts, - sys_path_with_modifications, - _check_module) -from jedi.evaluate import Evaluator -from jedi.parser import ParserWithRecovery, load_grammar - -from ..helpers import cwd_at - - -@cwd_at('test/test_evaluate/buildout_project/src/proj_name') -def test_parent_dir_with_file(): - parent = _get_parent_dir_with_file( - os.path.abspath(os.curdir), 'buildout.cfg') - assert parent is not None - assert parent.endswith(os.path.join('test', 'test_evaluate', 'buildout_project')) - - -@cwd_at('test/test_evaluate/buildout_project/src/proj_name') -def test_buildout_detection(): - scripts = _get_buildout_scripts(os.path.abspath('./module_name.py')) - assert len(scripts) == 1 - curdir = os.path.abspath(os.curdir) - appdir_path = os.path.normpath(os.path.join(curdir, '../../bin/app')) - assert scripts[0] == appdir_path - - -def test_append_on_non_sys_path(): - SRC = dedent(u(""" - class Dummy(object): - path = [] - - d = Dummy() - d.path.append('foo')""")) - grammar = load_grammar() - p = ParserWithRecovery(grammar, SRC) - paths = _check_module(Evaluator(grammar), p.module) - assert len(paths) > 0 - assert 'foo' not in paths - - -def test_path_from_invalid_sys_path_assignment(): - SRC = dedent(u(""" - import sys - sys.path = 'invalid'""")) - grammar = load_grammar() - p = ParserWithRecovery(grammar, SRC) - paths = _check_module(Evaluator(grammar), p.module) - assert len(paths) > 0 - assert 'invalid' not in paths - - -@cwd_at('test/test_evaluate/buildout_project/src/proj_name/') -def test_sys_path_with_modifications(): - SRC = dedent(u(""" - import os - """)) - grammar = load_grammar() - p = ParserWithRecovery(grammar, SRC) - p.module.path = os.path.abspath(os.path.join(os.curdir, 'module_name.py')) - paths = sys_path_with_modifications(Evaluator(grammar), p.module) - assert '/tmp/.buildout/eggs/important_package.egg' in paths - - -def test_path_from_sys_path_assignment(): - SRC = dedent(u(""" - #!/usr/bin/python - - import sys - sys.path[0:0] = [ - '/usr/lib/python3.4/site-packages', - '/home/test/.buildout/eggs/important_package.egg' - ] - - path[0:0] = [1] - - import important_package - - if __name__ == '__main__': - sys.exit(important_package.main())""")) - grammar = load_grammar() - p = ParserWithRecovery(grammar, SRC) - paths = _check_module(Evaluator(grammar), p.module) - assert 1 not in paths - assert '/home/test/.buildout/eggs/important_package.egg' in paths diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/test_compiled.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/test_compiled.py deleted file mode 100644 index 762260e..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/test_compiled.py +++ /dev/null @@ -1,86 +0,0 @@ -from textwrap import dedent - -from jedi._compatibility import builtins, is_py3 -from jedi.parser import load_grammar -from jedi.parser.tree import Function -from jedi.evaluate import compiled, representation -from jedi.evaluate import Evaluator -from jedi import Script - - -def _evaluator(): - return Evaluator(load_grammar()) - - -def test_simple(): - e = _evaluator() - bltn = compiled.CompiledObject(e, builtins) - obj = compiled.CompiledObject(e, '_str_', bltn) - upper = e.find_types(obj, 'upper') - assert len(upper) == 1 - objs = list(e.execute(list(upper)[0])) - assert len(objs) == 1 - assert isinstance(objs[0], representation.Instance) - - -def test_fake_loading(): - e = _evaluator() - assert isinstance(compiled.create(e, next), Function) - - builtin = compiled.get_special_object(e, 'BUILTINS') - string = builtin.get_subscope_by_name('str') - from_name = compiled._create_from_name(e, builtin, string, '__init__') - assert isinstance(from_name, Function) - - -def test_fake_docstr(): - assert compiled.create(_evaluator(), next).raw_doc == next.__doc__ - - -def test_parse_function_doc_illegal_docstr(): - docstr = """ - test_func(o - - doesn't have a closing bracket. - """ - assert ('', '') == compiled._parse_function_doc(docstr) - - -def test_doc(): - """ - Even CompiledObject docs always return empty docstrings - not None, that's - just a Jedi API definition. - """ - obj = compiled.CompiledObject(_evaluator(), ''.__getnewargs__) - assert obj.doc == '' - - -def test_string_literals(): - def typ(string): - d = Script("a = %s; a" % string).goto_definitions()[0] - return d.name - - assert typ('""') == 'str' - assert typ('r""') == 'str' - if is_py3: - assert typ('br""') == 'bytes' - assert typ('b""') == 'bytes' - assert typ('u""') == 'str' - else: - assert typ('b""') == 'str' - assert typ('u""') == 'unicode' - - -def test_method_completion(): - code = dedent(''' - class Foo: - def bar(self): - pass - - foo = Foo() - foo.bar.__func__''') - if is_py3: - result = [] - else: - result = ['__func__'] - assert [c.name for c in Script(code).completions()] == result diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/test_docstring.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/test_docstring.py deleted file mode 100644 index 6dbd1ca..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/test_docstring.py +++ /dev/null @@ -1,152 +0,0 @@ -""" -Testing of docstring related issues and especially ``jedi.docstrings``. -""" - -from textwrap import dedent -import jedi -from ..helpers import unittest - -try: - import numpydoc -except ImportError: - numpydoc_unavailable = True -else: - numpydoc_unavailable = False - - -class TestDocstring(unittest.TestCase): - def test_function_doc(self): - defs = jedi.Script(""" - def func(): - '''Docstring of `func`.''' - func""").goto_definitions() - self.assertEqual(defs[0].raw_doc, 'Docstring of `func`.') - - @unittest.skip('need evaluator class for that') - def test_attribute_docstring(self): - defs = jedi.Script(""" - x = None - '''Docstring of `x`.''' - x""").goto_definitions() - self.assertEqual(defs[0].raw_doc, 'Docstring of `x`.') - - @unittest.skip('need evaluator class for that') - def test_multiple_docstrings(self): - defs = jedi.Script(""" - def func(): - '''Original docstring.''' - x = func - '''Docstring of `x`.''' - x""").goto_definitions() - docs = [d.raw_doc for d in defs] - self.assertEqual(docs, ['Original docstring.', 'Docstring of `x`.']) - - def test_completion(self): - assert jedi.Script(''' - class DocstringCompletion(): - #? [] - """ asdfas """''').completions() - - def test_docstrings_type_dotted_import(self): - s = """ - def func(arg): - ''' - :type arg: random.Random - ''' - arg.""" - names = [c.name for c in jedi.Script(s).completions()] - assert 'seed' in names - - def test_docstrings_param_type(self): - s = """ - def func(arg): - ''' - :param str arg: some description - ''' - arg.""" - names = [c.name for c in jedi.Script(s).completions()] - assert 'join' in names - - def test_docstrings_type_str(self): - s = """ - def func(arg): - ''' - :type arg: str - ''' - arg.""" - - names = [c.name for c in jedi.Script(s).completions()] - assert 'join' in names - - def test_docstring_instance(self): - # The types hint that it's a certain kind - s = dedent(""" - class A: - def __init__(self,a): - ''' - :type a: threading.Thread - ''' - - if a is not None: - a.start() - - self.a = a - - - def method_b(c): - ''' - :type c: A - ''' - - c.""") - - names = [c.name for c in jedi.Script(s).completions()] - assert 'a' in names - assert '__init__' in names - assert 'mro' not in names # Exists only for types. - - @unittest.skipIf(numpydoc_unavailable, 'numpydoc module is unavailable') - def test_numpydoc_docstring(self): - s = dedent(''' - def foobar(x, y): - """ - Parameters - ---------- - x : int - y : str - """ - y.''') - names = [c.name for c in jedi.Script(s).completions()] - assert 'isupper' in names - assert 'capitalize' in names - - @unittest.skipIf(numpydoc_unavailable, 'numpydoc module is unavailable') - def test_numpydoc_docstring_set_of_values(self): - s = dedent(''' - def foobar(x, y): - """ - Parameters - ---------- - x : {'foo', 'bar', 100500}, optional - """ - x.''') - names = [c.name for c in jedi.Script(s).completions()] - assert 'isupper' in names - assert 'capitalize' in names - assert 'numerator' in names - - @unittest.skipIf(numpydoc_unavailable, 'numpydoc module is unavailable') - def test_numpydoc_alternative_types(self): - s = dedent(''' - def foobar(x, y): - """ - Parameters - ---------- - x : int or str or list - """ - x.''') - names = [c.name for c in jedi.Script(s).completions()] - assert 'isupper' in names - assert 'capitalize' in names - assert 'numerator' in names - assert 'append' in names diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/test_extension.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/test_extension.py deleted file mode 100644 index 83efc20..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/test_extension.py +++ /dev/null @@ -1,57 +0,0 @@ -""" -Test compiled module -""" -import os - -import jedi -from ..helpers import cwd_at -import pytest - - -def test_completions(): - s = jedi.Script('import _ctypes; _ctypes.') - assert len(s.completions()) >= 15 - - -def test_call_signatures_extension(): - if os.name == 'nt': - func = 'LoadLibrary' - params = 1 - else: - func = 'dlopen' - params = 2 - s = jedi.Script('import _ctypes; _ctypes.%s(' % (func,)) - sigs = s.call_signatures() - assert len(sigs) == 1 - assert len(sigs[0].params) == params - - -def test_call_signatures_stdlib(): - s = jedi.Script('import math; math.cos(') - sigs = s.call_signatures() - assert len(sigs) == 1 - assert len(sigs[0].params) == 1 - - -# Check only on linux 64 bit platform and Python3.4. -@pytest.mark.skipif('sys.platform != "linux" or sys.maxsize <= 2**32 or sys.version_info[:2] != (3, 4)') -@cwd_at('test/test_evaluate') -def test_init_extension_module(): - """ - ``__init__`` extension modules are also packages and Jedi should understand - that. - - Originally coming from #472. - - This test was built by the module.c and setup.py combination you can find - in the init_extension_module folder. You can easily build the - `__init__.cpython-34m.so` by compiling it (create a virtualenv and run - `setup.py install`. - - This is also why this test only runs on certain systems (and Python 3.4). - """ - s = jedi.Script('import init_extension_module as i\ni.', path='not_existing.py') - assert 'foo' in [c.name for c in s.completions()] - - s = jedi.Script('from init_extension_module import foo\nfoo', path='not_existing.py') - assert ['foo'] == [c.name for c in s.completions()] diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/test_helpers.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/test_helpers.py deleted file mode 100644 index 02e6d36..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/test_helpers.py +++ /dev/null @@ -1,16 +0,0 @@ -from textwrap import dedent - -from jedi import names -from jedi.evaluate import helpers - - -def test_call_of_leaf_in_brackets(): - s = dedent(""" - x = 1 - type(x) - """) - last_x = names(s, references=True, definitions=False)[-1] - name = last_x._name - - call = helpers.call_of_leaf(name) - assert call == name diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/test_imports.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/test_imports.py deleted file mode 100644 index 8eb2387..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/test_imports.py +++ /dev/null @@ -1,129 +0,0 @@ -import os -import sys - -import pytest - -import jedi -from jedi._compatibility import find_module_py33, find_module -from ..helpers import cwd_at - - -@pytest.mark.skipif('sys.version_info < (3,3)') -def test_find_module_py33(): - """Needs to work like the old find_module.""" - assert find_module_py33('_io') == (None, '_io', False) - - -def test_find_module_package(): - file, path, is_package = find_module('json') - assert file is None - assert path.endswith('json') - assert is_package is True - - -def test_find_module_not_package(): - file, path, is_package = find_module('io') - assert file is not None - assert path.endswith('io.py') - assert is_package is False - - -def test_find_module_package_zipped(): - if 'zipped_imports/pkg.zip' not in sys.path: - sys.path.append(os.path.join(os.path.dirname(__file__), - 'zipped_imports/pkg.zip')) - file, path, is_package = find_module('pkg') - assert file is not None - assert path.endswith('pkg.zip') - assert is_package is True - assert len(jedi.Script('import pkg; pkg.mod', 1, 19).completions()) == 1 - - -@pytest.mark.skipif('sys.version_info < (2,7)') -def test_find_module_not_package_zipped(): - if 'zipped_imports/not_pkg.zip' not in sys.path: - sys.path.append(os.path.join(os.path.dirname(__file__), - 'zipped_imports/not_pkg.zip')) - file, path, is_package = find_module('not_pkg') - assert file is not None - assert path.endswith('not_pkg.zip') - assert is_package is False - assert len( - jedi.Script('import not_pkg; not_pkg.val', 1, 27).completions()) == 1 - - -@cwd_at('test/test_evaluate/not_in_sys_path/pkg') -def test_import_not_in_sys_path(): - """ - non-direct imports (not in sys.path) - """ - a = jedi.Script(path='module.py', line=5).goto_definitions() - assert a[0].name == 'int' - - a = jedi.Script(path='module.py', line=6).goto_definitions() - assert a[0].name == 'str' - a = jedi.Script(path='module.py', line=7).goto_definitions() - assert a[0].name == 'str' - - -@pytest.mark.parametrize("script,name", [ - ("from flask.ext import foo; foo.", "Foo"), # flask_foo.py - ("from flask.ext import bar; bar.", "Bar"), # flaskext/bar.py - ("from flask.ext import baz; baz.", "Baz"), # flask_baz/__init__.py - ("from flask.ext import moo; moo.", "Moo"), # flaskext/moo/__init__.py - ("from flask.ext.", "foo"), - ("from flask.ext.", "bar"), - ("from flask.ext.", "baz"), - ("from flask.ext.", "moo"), - pytest.mark.xfail(("import flask.ext.foo; flask.ext.foo.", "Foo")), - pytest.mark.xfail(("import flask.ext.bar; flask.ext.bar.", "Foo")), - pytest.mark.xfail(("import flask.ext.baz; flask.ext.baz.", "Foo")), - pytest.mark.xfail(("import flask.ext.moo; flask.ext.moo.", "Foo")), -]) -def test_flask_ext(script, name): - """flask.ext.foo is really imported from flaskext.foo or flask_foo. - """ - path = os.path.join(os.path.dirname(__file__), 'flask-site-packages') - completions = jedi.Script(script, sys_path=[path]).completions() - assert name in [c.name for c in completions] - - -@cwd_at('test/test_evaluate/') -def test_not_importable_file(): - src = 'import not_importable_file as x; x.' - assert not jedi.Script(src, path='example.py').completions() - - -def test_import_unique(): - src = "import os; os.path" - defs = jedi.Script(src, path='example.py').goto_definitions() - defs = [d._definition for d in defs] - assert len(defs) == len(set(defs)) - - -def test_cache_works_with_sys_path_param(tmpdir): - foo_path = tmpdir.join('foo') - bar_path = tmpdir.join('bar') - foo_path.join('module.py').write('foo = 123', ensure=True) - bar_path.join('module.py').write('bar = 123', ensure=True) - foo_completions = jedi.Script('import module; module.', - sys_path=[foo_path.strpath]).completions() - bar_completions = jedi.Script('import module; module.', - sys_path=[bar_path.strpath]).completions() - assert 'foo' in [c.name for c in foo_completions] - assert 'bar' not in [c.name for c in foo_completions] - - assert 'bar' in [c.name for c in bar_completions] - assert 'foo' not in [c.name for c in bar_completions] - - -def test_import_completion_docstring(): - import abc - s = jedi.Script('"""test"""\nimport ab') - completions = s.completions() - assert len(completions) == 1 - assert completions[0].docstring(fast=False) == abc.__doc__ - - # However for performance reasons not all modules are loaded and the - # docstring is empty in this case. - assert completions[0].docstring() == '' diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/test_namespace_package.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/test_namespace_package.py deleted file mode 100644 index 3beed65..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/test_namespace_package.py +++ /dev/null @@ -1,65 +0,0 @@ -import jedi -from os.path import dirname, join - - -def test_namespace_package(): - sys_path = [join(dirname(__file__), d) - for d in ['namespace_package/ns1', 'namespace_package/ns2']] - - def script_with_path(*args, **kwargs): - return jedi.Script(sys_path=sys_path, *args, **kwargs) - - # goto definition - assert script_with_path('from pkg import ns1_file').goto_definitions() - assert script_with_path('from pkg import ns2_file').goto_definitions() - assert not script_with_path('from pkg import ns3_file').goto_definitions() - - # goto assignment - tests = { - 'from pkg.ns2_folder.nested import foo': 'nested!', - 'from pkg.ns2_folder import foo': 'ns2_folder!', - 'from pkg.ns2_file import foo': 'ns2_file!', - 'from pkg.ns1_folder import foo': 'ns1_folder!', - 'from pkg.ns1_file import foo': 'ns1_file!', - 'from pkg import foo': 'ns1!', - } - for source, solution in tests.items(): - ass = script_with_path(source).goto_assignments() - assert len(ass) == 1 - assert ass[0].description == "foo = '%s'" % solution - - # completion - completions = script_with_path('from pkg import ').completions() - names = [str(c.name) for c in completions] # str because of unicode - compare = ['foo', 'ns1_file', 'ns1_folder', 'ns2_folder', 'ns2_file', - 'pkg_resources', 'pkgutil', '__name__', '__path__', - '__package__', '__file__', '__doc__'] - # must at least contain these items, other items are not important - assert set(compare) == set(names) - - tests = { - 'from pkg import ns2_folder as x': 'ns2_folder!', - 'from pkg import ns2_file as x': 'ns2_file!', - 'from pkg.ns2_folder import nested as x': 'nested!', - 'from pkg import ns1_folder as x': 'ns1_folder!', - 'from pkg import ns1_file as x': 'ns1_file!', - 'import pkg as x': 'ns1!', - } - for source, solution in tests.items(): - for c in script_with_path(source + '; x.').completions(): - if c.name == 'foo': - completion = c - solution = "statement: foo = '%s'" % solution - assert completion.description == solution - - -def test_nested_namespace_package(): - CODE = 'from nested_namespaces.namespace.pkg import CONST' - - sys_path = [dirname(__file__)] - - script = jedi.Script(sys_path=sys_path, source=CODE, line=1, column=45) - - result = script.goto_definitions() - - assert len(result) == 1 diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/test_precedence.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/test_precedence.py deleted file mode 100644 index 462b7d4..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/test_precedence.py +++ /dev/null @@ -1,20 +0,0 @@ -from jedi.parser import load_grammar, Parser -from jedi.evaluate import Evaluator -from jedi.evaluate.compiled import CompiledObject - -import pytest - - -@pytest.mark.skipif('sys.version_info[0] < 3') # Ellipsis does not exists in 2 -@pytest.mark.parametrize('source', [ - '1 == 1', - '1.0 == 1', - '... == ...' -]) -def test_equals(source): - evaluator = Evaluator(load_grammar()) - node = Parser(load_grammar(), source, 'eval_input').get_parsed_node() - results = evaluator.eval_element(node) - assert len(results) == 1 - first = results.pop() - assert isinstance(first, CompiledObject) and first.obj is True diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/test_pyc.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/test_pyc.py deleted file mode 100644 index c101da1..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/test_pyc.py +++ /dev/null @@ -1,64 +0,0 @@ -""" -Test completions from *.pyc files: - - - generate a dummy python module - - compile the dummy module to generate a *.pyc - - delete the pure python dummy module - - try jedi on the generated *.pyc -""" -import os -import shutil -import sys - -import pytest - -import jedi -from ..helpers import cwd_at - - -SRC = """class Foo: - pass - -class Bar: - pass -""" - - -def generate_pyc(): - os.mkdir("dummy_package") - with open("dummy_package/__init__.py", 'w'): - pass - with open("dummy_package/dummy.py", 'w') as f: - f.write(SRC) - import compileall - compileall.compile_file("dummy_package/dummy.py") - os.remove("dummy_package/dummy.py") - - if sys.version_info[0] == 3: - # Python3 specific: - # To import pyc modules, we must move them out of the __pycache__ - # directory and rename them to remove ".cpython-%s%d" - # see: http://stackoverflow.com/questions/11648440/python-does-not-detect-pyc-files - for f in os.listdir("dummy_package/__pycache__"): - dst = f.replace('.cpython-%s%s' % sys.version_info[:2], "") - dst = os.path.join("dummy_package", dst) - shutil.copy(os.path.join("dummy_package/__pycache__", f), dst) - - -# Python 2.6 does not necessarily come with `compileall.compile_file`. -@pytest.mark.skipif("sys.version_info > (2,6)") -@cwd_at('test/test_evaluate') -def test_pyc(): - """ - The list of completion must be greater than 2. - """ - try: - generate_pyc() - s = jedi.Script("from dummy_package import dummy; dummy.", path='blub.py') - assert len(s.completions()) >= 2 - finally: - shutil.rmtree("dummy_package") - - -if __name__ == "__main__": - test_pyc() diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/test_representation.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/test_representation.py deleted file mode 100644 index 1d3d562..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/test_representation.py +++ /dev/null @@ -1,36 +0,0 @@ -from textwrap import dedent - -from jedi import Script - - -def get_definition_and_evaluator(source): - d = Script(dedent(source)).goto_definitions()[0] - return d._name.parent, d._evaluator - - -def test_function_execution(): - """ - We've been having an issue of a mutable list that was changed inside the - function execution. Test if an execution always returns the same result. - """ - - s = """ - def x(): - return str() - x""" - func, evaluator = get_definition_and_evaluator(s) - # Now just use the internals of the result (easiest way to get a fully - # usable function). - # Should return the same result both times. - assert len(evaluator.execute(func)) == 1 - assert len(evaluator.execute(func)) == 1 - - -def test_class_mro(): - s = """ - class X(object): - pass - X""" - cls, evaluator = get_definition_and_evaluator(s) - mro = cls.py__mro__() - assert [str(c.name) for c in mro] == ['X', 'object'] diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/test_sys_path.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/test_sys_path.py deleted file mode 100644 index 9635eec..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/test_sys_path.py +++ /dev/null @@ -1,59 +0,0 @@ -import os -from glob import glob -import sys - -import pytest - -from jedi._compatibility import unicode -from jedi.parser import ParserWithRecovery, load_grammar -from jedi.evaluate import sys_path, Evaluator - - -def test_paths_from_assignment(): - def paths(src): - grammar = load_grammar() - stmt = ParserWithRecovery(grammar, unicode(src)).module.statements[0] - return set(sys_path._paths_from_assignment(Evaluator(grammar), stmt)) - - assert paths('sys.path[0:0] = ["a"]') == set(['a']) - assert paths('sys.path = ["b", 1, x + 3, y, "c"]') == set(['b', 'c']) - assert paths('sys.path = a = ["a"]') == set(['a']) - - # Fail for complicated examples. - assert paths('sys.path, other = ["a"], 2') == set() - - -# Currently venv site-packages resolution only seeks pythonX.Y/site-packages -# that belong to the same version as the interpreter to avoid issues with -# cross-version imports. "venvs/" dir contains "venv27" and "venv34" that -# mimic venvs created for py2.7 and py3.4 respectively. If test runner is -# invoked with one of those versions, the test below will be run for the -# matching directory. -CUR_DIR = os.path.dirname(__file__) -VENVS = list(glob( - os.path.join(CUR_DIR, 'sample_venvs/venv%d%d' % sys.version_info[:2]))) - - -@pytest.mark.parametrize('venv', VENVS) -def test_get_venv_path(venv): - pjoin = os.path.join - venv_path = sys_path.get_venv_path(venv) - - site_pkgs = (glob(pjoin(venv, 'lib', 'python*', 'site-packages')) + - glob(pjoin(venv, 'lib', 'site-packages')))[0] - ETALON = [ - pjoin('/path', 'from', 'egg-link'), - pjoin(site_pkgs, '.', 'relative', 'egg-link', 'path'), - site_pkgs, - pjoin(site_pkgs, 'dir-from-foo-pth'), - ] - - # Ensure that pth and egg-link paths were added. - assert venv_path[:len(ETALON)] == ETALON - - # Ensure that none of venv dirs leaked to the interpreter. - assert not set(sys.path).intersection(ETALON) - - # Ensure that "import ..." lines were ignored. - assert pjoin('/path', 'from', 'smth.py') not in venv_path - assert pjoin('/path', 'from', 'smth.py:extend_path') not in venv_path diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/zipped_imports/not_pkg.zip b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/zipped_imports/not_pkg.zip deleted file mode 100644 index f1516a6..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/zipped_imports/not_pkg.zip and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/zipped_imports/pkg.zip b/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/zipped_imports/pkg.zip deleted file mode 100644 index ec8eac4..0000000 Binary files a/vim-plugins/bundle/jedi-vim/jedi/test/test_evaluate/zipped_imports/pkg.zip and /dev/null differ diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_integration.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_integration.py deleted file mode 100644 index edca711..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_integration.py +++ /dev/null @@ -1,60 +0,0 @@ -import os - -import pytest - -from . import helpers - - -def assert_case_equal(case, actual, desired): - """ - Assert ``actual == desired`` with formatted message. - - This is not needed for typical py.test use case, but as we need - ``--assert=plain`` (see ../pytest.ini) to workaround some issue - due to py.test magic, let's format the message by hand. - """ - assert actual == desired, """ -Test %r failed. -actual = %s -desired = %s -""" % (case, actual, desired) - - -def assert_static_analysis(case, actual, desired): - """A nicer formatting for static analysis tests.""" - a = set(actual) - d = set(desired) - assert actual == desired, """ -Test %r failed. -not raised = %s -unspecified = %s -""" % (case, sorted(d - a), sorted(a - d)) - - -def test_completion(case, monkeypatch): - if case.skip is not None: - pytest.skip(case.skip) - repo_root = helpers.root_dir - monkeypatch.chdir(os.path.join(repo_root, 'jedi')) - case.run(assert_case_equal) - - -def test_static_analysis(static_analysis_case): - if static_analysis_case.skip is not None: - pytest.skip(static_analysis_case.skip) - else: - static_analysis_case.run(assert_static_analysis) - - -def test_refactor(refactor_case): - """ - Run refactoring test case. - - :type refactor_case: :class:`.refactor.RefactoringCase` - """ - if 0: - # TODO Refactoring is not relevant at the moment, it will be changed - # significantly in the future, but maybe we can use these tests: - refactor_case.run() - assert_case_equal(refactor_case, - refactor_case.result, refactor_case.desired) diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_integration_analysis.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_integration_analysis.py deleted file mode 100644 index cfcd405..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_integration_analysis.py +++ /dev/null @@ -1,12 +0,0 @@ -""" -Test of keywords and ``jedi.keywords`` -""" -from jedi import Script - - -def test_issue436(): - code = "bar = 0\nbar += 'foo' + 4" - errors = set(repr(e) for e in Script(code)._analysis()) - assert len(errors) == 2 - assert '' in errors - assert '' in errors diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_integration_import.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_integration_import.py deleted file mode 100644 index d961666..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_integration_import.py +++ /dev/null @@ -1,83 +0,0 @@ -""" -Tests of various import related things that could not be tested with "Black Box -Tests". -""" -from jedi import Script -from .helpers import cwd_at -from jedi._compatibility import is_py26 - -import pytest - - -def test_goto_definition_on_import(): - assert Script("import sys_blabla", 1, 8).goto_definitions() == [] - assert len(Script("import sys", 1, 8).goto_definitions()) == 1 - - -@cwd_at('jedi') -def test_complete_on_empty_import(): - assert Script("from datetime import").completions()[0].name == 'import' - # should just list the files in the directory - assert 10 < len(Script("from .", path='whatever.py').completions()) < 30 - - # Global import - assert len(Script("from . import", 1, 5, 'whatever.py').completions()) > 30 - # relative import - assert 10 < len(Script("from . import", 1, 6, 'whatever.py').completions()) < 30 - - # Global import - assert len(Script("from . import classes", 1, 5, 'whatever.py').completions()) > 30 - # relative import - assert 10 < len(Script("from . import classes", 1, 6, 'whatever.py').completions()) < 30 - - wanted = set(['ImportError', 'import', 'ImportWarning']) - assert set([c.name for c in Script("import").completions()]) == wanted - if not is_py26: # python 2.6 doesn't always come with a library `import*`. - assert len(Script("import import", path='').completions()) > 0 - - # 111 - assert Script("from datetime import").completions()[0].name == 'import' - assert Script("from datetime import ").completions() - - -def test_imports_on_global_namespace_without_path(): - """If the path is None, there shouldn't be any import problem""" - completions = Script("import operator").completions() - assert [c.name for c in completions] == ['operator'] - completions = Script("import operator", path='example.py').completions() - assert [c.name for c in completions] == ['operator'] - - # the first one has a path the second doesn't - completions = Script("import keyword", path='example.py').completions() - assert [c.name for c in completions] == ['keyword'] - completions = Script("import keyword").completions() - assert [c.name for c in completions] == ['keyword'] - - -def test_named_import(): - """named import - jedi-vim issue #8""" - s = "import time as dt" - assert len(Script(s, 1, 15, '/').goto_definitions()) == 1 - assert len(Script(s, 1, 10, '/').goto_definitions()) == 1 - - -@pytest.mark.skipif('True', reason='The nested import stuff is still very messy.') -def test_goto_following_on_imports(): - s = "import multiprocessing.dummy; multiprocessing.dummy" - g = Script(s).goto_assignments() - assert len(g) == 1 - assert (g[0].line, g[0].column) != (0, 0) - - -def test_after_from(): - def check(source, result, column=None): - completions = Script(source, column=column).completions() - assert [c.name for c in completions] == result - - check('\nfrom os. ', ['path']) - check('\nfrom os ', ['import']) - check('from os ', ['import']) - check('\nfrom os import whatever', ['import'], len('from os im')) - - check('from os\\\n', ['import']) - check('from os \\\n', ['import']) diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_integration_keyword.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_integration_keyword.py deleted file mode 100644 index ad4a2ae..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_integration_keyword.py +++ /dev/null @@ -1,29 +0,0 @@ -""" -Test of keywords and ``jedi.keywords`` -""" -from jedi._compatibility import is_py3 -from jedi import Script - - -def test_goto_assignments_keyword(): - """ - Bug: goto assignments on ``in`` used to raise AttributeError:: - - 'unicode' object has no attribute 'generate_call_path' - """ - Script('in').goto_assignments() - - -def test_keyword(): - """ github jedi-vim issue #44 """ - defs = Script("print").goto_definitions() - if is_py3: - assert [d.doc for d in defs] - else: - assert defs == [] - - assert Script("import").goto_assignments() == [] - - completions = Script("import", 1, 1).completions() - assert len(completions) > 10 and 'if' in [c.name for c in completions] - assert Script("assert").goto_definitions() == [] diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_integration_stdlib.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_integration_stdlib.py deleted file mode 100644 index 3cbe658..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_integration_stdlib.py +++ /dev/null @@ -1,45 +0,0 @@ -""" -Tests of various stdlib related things that could not be tested -with "Black Box Tests". -""" -from textwrap import dedent - -import pytest -from jedi import Script -from jedi._compatibility import is_py26 - -# The namedtuple is different for different Python2.7 versions. Some versions -# are missing the attribute `_class_template`. -pytestmark = pytest.mark.skipif('sys.version_info[0] < 3') - - -@pytest.mark.parametrize(['letter', 'expected'], [ - ('n', ['name']), - ('s', ['smart']), -]) -def test_namedtuple_str(letter, expected): - source = dedent("""\ - import collections - Person = collections.namedtuple('Person', 'name smart') - dave = Person('Dave', False) - dave.%s""") % letter - result = Script(source).completions() - completions = set(r.name for r in result) - if is_py26: - assert completions == set() - else: - assert completions == set(expected) - - -def test_namedtuple_list(): - source = dedent("""\ - import collections - Cat = collections.namedtuple('Person', ['legs', u'length', 'large']) - garfield = Cat(4, '85cm', True) - garfield.l""") - result = Script(source).completions() - completions = set(r.name for r in result) - if is_py26: - assert completions == set() - else: - assert completions == set(['legs', 'length', 'large']) diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_jedi_system.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_jedi_system.py deleted file mode 100644 index ea0d1e9..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_jedi_system.py +++ /dev/null @@ -1,61 +0,0 @@ -""" -Test the Jedi "System" which means for example to test if imports are -correctly used. -""" - -import os -import inspect - -import jedi - - -def test_settings_module(): - """ - jedi.settings and jedi.cache.settings must be the same module. - """ - from jedi import cache - from jedi import settings - assert cache.settings is settings - - -def test_no_duplicate_modules(): - """ - Make sure that import hack works as expected. - - Jedi does an import hack (see: jedi/__init__.py) to have submodules - with circular dependencies. The modules in this circular dependency - "loop" must be imported by ``import `` rather than normal - ``from jedi import `` (or ``from . jedi ...``). This test - make sure that this is satisfied. - - See also: - - - `#160 `_ - - `#161 `_ - """ - import sys - jedipath = os.path.dirname(os.path.abspath(jedi.__file__)) - - def is_submodule(m): - try: - filepath = m.__file__ - except AttributeError: - return False - return os.path.abspath(filepath).startswith(jedipath) - - modules = list(filter(is_submodule, sys.modules.values())) - top_modules = [m for m in modules if not m.__name__.startswith('jedi.')] - for m in modules: - if m is jedi: - # py.test automatically improts `jedi.*` when --doctest-modules - # is given. So this test cannot succeeds. - continue - for tm in top_modules: - try: - imported = getattr(m, tm.__name__) - except AttributeError: - continue - if inspect.ismodule(imported): - # module could have a function with the same name, e.g. - # `keywords.keywords`. - assert imported is tm diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_new_parser.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_new_parser.py deleted file mode 100644 index e66591d..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_new_parser.py +++ /dev/null @@ -1,13 +0,0 @@ -from jedi._compatibility import u -from jedi.parser import ParserWithRecovery, load_grammar - - -def test_basic_parsing(): - def compare(string): - """Generates the AST object and then regenerates the code.""" - assert ParserWithRecovery(load_grammar(), string).module.get_code() == string - - compare(u('\na #pass\n')) - compare(u('wblabla* 1\t\n')) - compare(u('def x(a, b:3): pass\n')) - compare(u('assert foo\n')) diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_parser/__init__.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_parser/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_parser/test_fast_parser.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_parser/test_fast_parser.py deleted file mode 100644 index 46cdf5c..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_parser/test_fast_parser.py +++ /dev/null @@ -1,496 +0,0 @@ -from textwrap import dedent - -import pytest - -import jedi -from jedi._compatibility import u -from jedi import cache -from jedi.parser import load_grammar -from jedi.parser.fast import FastParser -from jedi.parser.utils import save_parser - - -def test_add_to_end(): - """ - fast_parser doesn't parse everything again. It just updates with the - help of caches, this is an example that didn't work. - """ - - a = dedent(""" - class Abc(): - def abc(self): - self.x = 3 - - class Two(Abc): - def h(self): - self - """) # ^ here is the first completion - - b = " def g(self):\n" \ - " self." - assert jedi.Script(a, 8, 12, 'example.py').completions() - assert jedi.Script(a + b, path='example.py').completions() - - a = a[:-1] + '.\n' - assert jedi.Script(a, 8, 13, 'example.py').completions() - assert jedi.Script(a + b, path='example.py').completions() - - -def test_class_in_docstr(): - """ - Regression test for a problem with classes in docstrings. - """ - a = '"\nclasses\n"' - jedi.Script(a, 1, 0)._get_module() - - b = a + '\nimport os' - assert jedi.Script(b, 4, 8).goto_assignments() - - -def test_carriage_return_splitting(): - source = u(dedent(''' - - - - "string" - - class Foo(): - pass - ''')) - source = source.replace('\n', '\r\n') - p = FastParser(load_grammar(), source) - assert [n.value for lst in p.module.names_dict.values() for n in lst] == ['Foo'] - - -def test_split_parts(): - cache.parser_cache.pop(None, None) - - def splits(source): - class Mock(FastParser): - def __init__(self, *args): - self.number_of_splits = 0 - - return tuple(FastParser._split_parts(Mock(None, None), source)) - - def test(*parts): - assert splits(''.join(parts)) == parts - - test('a\n\n', 'def b(): pass\n', 'c\n') - test('a\n', 'def b():\n pass\n', 'c\n') - - test('from x\\\n') - test('a\n\\\n') - - -def check_fp(src, number_parsers_used, number_of_splits=None, number_of_misses=0): - if number_of_splits is None: - number_of_splits = number_parsers_used - - p = FastParser(load_grammar(), u(src)) - save_parser(None, p, pickling=False) - - assert src == p.module.get_code() - assert p.number_of_splits == number_of_splits - assert p.number_parsers_used == number_parsers_used - assert p.number_of_misses == number_of_misses - return p.module - - -def test_change_and_undo(): - # Empty the parser cache for the path None. - cache.parser_cache.pop(None, None) - func_before = 'def func():\n pass\n' - # Parse the function and a. - check_fp(func_before + 'a', 2) - # Parse just b. - check_fp(func_before + 'b', 1, 2) - # b has changed to a again, so parse that. - check_fp(func_before + 'a', 1, 2) - # Same as before no parsers should be used. - check_fp(func_before + 'a', 0, 2) - - # Getting rid of an old parser: Still no parsers used. - check_fp('a', 0, 1) - # Now the file has completely change and we need to parse. - check_fp('b', 1, 1) - # And again. - check_fp('a', 1, 1) - - -def test_positions(): - # Empty the parser cache for the path None. - cache.parser_cache.pop(None, None) - - func_before = 'class A:\n pass\n' - m = check_fp(func_before + 'a', 2) - assert m.start_pos == (1, 0) - assert m.end_pos == (3, 1) - - m = check_fp('a', 0, 1) - assert m.start_pos == (1, 0) - assert m.end_pos == (1, 1) - - -def test_if(): - src = dedent('''\ - def func(): - x = 3 - if x: - def y(): - return x - return y() - - func() - ''') - - # Two parsers needed, one for pass and one for the function. - check_fp(src, 2) - assert [d.name for d in jedi.Script(src, 8, 6).goto_definitions()] == ['int'] - - -def test_if_simple(): - src = dedent('''\ - if 1: - a = 3 - ''') - check_fp(src + 'a', 1) - check_fp(src + "else:\n a = ''\na", 1) - - -def test_for(): - src = dedent("""\ - for a in [1,2]: - a - - for a1 in 1,"": - a1 - """) - check_fp(src, 1) - - -def test_class_with_class_var(): - src = dedent("""\ - class SuperClass: - class_super = 3 - def __init__(self): - self.foo = 4 - pass - """) - check_fp(src, 3) - - -def test_func_with_if(): - src = dedent("""\ - def recursion(a): - if foo: - return recursion(a) - else: - if bar: - return inexistent - else: - return a - """) - check_fp(src, 1) - - -def test_decorator(): - src = dedent("""\ - class Decorator(): - @memoize - def dec(self, a): - return a - """) - check_fp(src, 2) - - -def test_nested_funcs(): - src = dedent("""\ - def memoize(func): - def wrapper(*args, **kwargs): - return func(*args, **kwargs) - return wrapper - """) - check_fp(src, 3) - - -def test_class_and_if(): - src = dedent("""\ - class V: - def __init__(self): - pass - - if 1: - c = 3 - - def a_func(): - return 1 - - # COMMENT - a_func()""") - check_fp(src, 5, 5) - assert [d.name for d in jedi.Script(src).goto_definitions()] == ['int'] - - -def test_func_with_for_and_comment(): - # The first newline is important, leave it. It should not trigger another - # parser split. - src = dedent("""\ - - def func(): - pass - - - for a in [1]: - # COMMENT - a""") - check_fp(src, 2) - # We don't need to parse the for loop, but we need to parse the other two, - # because the split is in a different place. - check_fp('a\n' + src, 2, 3) - - -def test_multi_line_params(): - src = dedent("""\ - def x(a, - b): - pass - - foo = 1 - """) - check_fp(src, 2) - - -def test_one_statement_func(): - src = dedent("""\ - first - def func(): a - """) - check_fp(src + 'second', 3) - # Empty the parser cache, because we're not interested in modifications - # here. - cache.parser_cache.pop(None, None) - check_fp(src + 'def second():\n a', 3) - - -def test_class_func_if(): - src = dedent("""\ - class Class: - def func(self): - if 1: - a - else: - b - - pass - """) - check_fp(src, 3) - - -def test_for_on_one_line(): - src = dedent("""\ - foo = 1 - for x in foo: pass - - def hi(): - pass - """) - check_fp(src, 2) - - src = dedent("""\ - def hi(): - for x in foo: pass - pass - - pass - """) - check_fp(src, 2) - - src = dedent("""\ - def hi(): - for x in foo: pass - - def nested(): - pass - """) - check_fp(src, 2) - - -def test_multi_line_for(): - src = dedent("""\ - for x in [1, - 2]: - pass - - pass - """) - check_fp(src, 1) - - -def test_wrong_indentation(): - src = dedent("""\ - def func(): - a - b - a - """) - #check_fp(src, 1) - - src = dedent("""\ - def complex(): - def nested(): - a - b - a - - def other(): - pass - """) - check_fp(src, 3) - - -def test_open_parentheses(): - func = 'def func():\n a' - code = u('isinstance(\n\n' + func) - p = FastParser(load_grammar(), code) - # As you can see, the part that was failing is still there in the get_code - # call. It is not relevant for evaluation, but still available as an - # ErrorNode. - assert p.module.get_code() == code - assert p.number_of_splits == 2 - assert p.number_parsers_used == 2 - save_parser(None, p, pickling=False) - - # Now with a correct parser it should work perfectly well. - check_fp('isinstance()\n' + func, 1, 2) - - -def test_strange_parentheses(): - src = dedent(""" - class X(): - a = (1 - if 1 else 2) - def x(): - pass - """) - check_fp(src, 2) - - -def test_backslash(): - src = dedent(r""" - a = 1\ - if 1 else 2 - def x(): - pass - """) - check_fp(src, 2) - - src = dedent(r""" - def x(): - a = 1\ - if 1 else 2 - def y(): - pass - """) - # The dangling if leads to not splitting where we theoretically could - # split. - check_fp(src, 2) - - src = dedent(r""" - def first(): - if foo \ - and bar \ - or baz: - pass - def second(): - pass - """) - check_fp(src, 2) - - - -def test_fake_parentheses(): - """ - The fast parser splitting counts parentheses, but not as correct tokens. - Therefore parentheses in string tokens are included as well. This needs to - be accounted for. - """ - src = dedent(r""" - def x(): - a = (')' - if 1 else 2) - def y(): - pass - def z(): - pass - """) - check_fp(src, 3, 2, 1) - - -def test_additional_indent(): - source = dedent('''\ - int( - def x(): - pass - ''') - - check_fp(source, 2) - - -def test_incomplete_function(): - source = '''return ImportErr''' - - script = jedi.Script(dedent(source), 1, 3) - assert script.completions() - - -def test_string_literals(): - """Simplified case of jedi-vim#377.""" - source = dedent(""" - x = ur''' - - def foo(): - pass - """) - - script = jedi.Script(dedent(source)) - script._get_module().end_pos == (6, 0) - assert script.completions() - - -def test_decorator_string_issue(): - """ - Test case from #589 - """ - source = dedent('''\ - """ - @""" - def bla(): - pass - - bla.''') - - s = jedi.Script(source) - assert s.completions() - assert s._get_module().get_code() == source - - -def test_round_trip(): - source = dedent(''' - def x(): - """hahaha""" - func''') - - f = FastParser(load_grammar(), u(source)) - assert f.get_parsed_node().get_code() == source - - -@pytest.mark.xfail() -def test_parentheses_in_string(): - code = dedent(''' - def x(): - '(' - - import abc - - abc.''') - check_fp(code, 2, 1, 1) diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_parser/test_get_code.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_parser/test_get_code.py deleted file mode 100644 index 43202fb..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_parser/test_get_code.py +++ /dev/null @@ -1,107 +0,0 @@ -import difflib - -import pytest - -from jedi._compatibility import u -from jedi.parser import ParserWithRecovery, load_grammar - -code_basic_features = u(''' -"""A mod docstring""" - -def a_function(a_argument, a_default = "default"): - """A func docstring""" - - a_result = 3 * a_argument - print(a_result) # a comment - b = """ -from -to""" + "huhu" - - - if a_default == "default": - return str(a_result) - else - return None -''') - - -def diff_code_assert(a, b, n=4): - if a != b: - diff = "\n".join(difflib.unified_diff( - a.splitlines(), - b.splitlines(), - n=n, - lineterm="" - )) - assert False, "Code does not match:\n%s\n\ncreated code:\n%s" % ( - diff, - b - ) - pass - - -@pytest.mark.skipif('True', reason='Refactor a few parser things first.') -def test_basic_parsing(): - """Validate the parsing features""" - - prs = ParserWithRecovery(load_grammar(), code_basic_features) - diff_code_assert( - code_basic_features, - prs.module.get_code() - ) - - -def test_operators(): - src = u('5 * 3') - prs = ParserWithRecovery(load_grammar(), src) - diff_code_assert(src, prs.module.get_code()) - - -def test_get_code(): - """Use the same code that the parser also generates, to compare""" - s = u('''"""a docstring""" -class SomeClass(object, mixin): - def __init__(self): - self.xy = 3.0 - """statement docstr""" - def some_method(self): - return 1 - def yield_method(self): - while hasattr(self, 'xy'): - yield True - for x in [1, 2]: - yield x - def empty(self): - pass -class Empty: - pass -class WithDocstring: - """class docstr""" - pass -def method_with_docstring(): - """class docstr""" - pass -''') - assert ParserWithRecovery(load_grammar(), s).module.get_code() == s - - -def test_end_newlines(): - """ - The Python grammar explicitly needs a newline at the end. Jedi though still - wants to be able, to return the exact same code without the additional new - line the parser needs. - """ - def test(source, end_pos): - module = ParserWithRecovery(load_grammar(), u(source)).module - assert module.get_code() == source - assert module.end_pos == end_pos - - test('a', (1, 1)) - test('a\n', (2, 0)) - test('a\nb', (2, 1)) - test('a\n#comment\n', (3, 0)) - test('a\n#comment', (2, 8)) - test('a#comment', (1, 9)) - test('def a():\n pass', (2, 5)) - - test('def a(', (1, 6)) diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_parser/test_param_splitting.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_parser/test_param_splitting.py deleted file mode 100644 index f97c3dc..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_parser/test_param_splitting.py +++ /dev/null @@ -1,34 +0,0 @@ -''' -To make the life of any analysis easier, we are generating Param objects -instead of simple parser objects. -''' - -from textwrap import dedent - -from jedi.parser import Parser, load_grammar - - -def assert_params(param_string, **wanted_dct): - source = dedent(''' - def x(%s): - pass - ''') % param_string - - parser = Parser(load_grammar(), dedent(source)) - funcdef = parser.get_parsed_node().subscopes[0] - dct = dict((p.name.value, p.default and p.default.get_code()) - for p in funcdef.params) - assert dct == wanted_dct - assert parser.get_parsed_node().get_code() == source - - -def test_split_params_with_separation_star(): - assert_params(u'x, y=1, *, z=3', x=None, y='1', z='3') - assert_params(u'*, x', x=None) - assert_params(u'*') - - -def test_split_params_with_stars(): - assert_params(u'x, *args', x=None, args=None) - assert_params(u'**kwargs', kwargs=None) - assert_params(u'*args, **kwargs', args=None, kwargs=None) diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_parser/test_parser.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_parser/test_parser.py deleted file mode 100644 index 0ec75d0..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_parser/test_parser.py +++ /dev/null @@ -1,238 +0,0 @@ -# -*- coding: utf-8 -*- -import sys -from textwrap import dedent - -import jedi -from jedi._compatibility import u, is_py3 -from jedi.parser import ParserWithRecovery, load_grammar -from jedi.parser import tree as pt - - -def test_user_statement_on_import(): - """github #285""" - s = u("from datetime import (\n" - " time)") - - for pos in [(2, 1), (2, 4)]: - p = ParserWithRecovery(load_grammar(), s) - stmt = p.module.get_statement_for_position(pos) - assert isinstance(stmt, pt.Import) - assert [str(n) for n in stmt.get_defined_names()] == ['time'] - - -class TestCallAndName(): - def get_call(self, source): - # Get the simple_stmt and then the first one. - simple_stmt = ParserWithRecovery(load_grammar(), u(source)).module.children[0] - return simple_stmt.children[0] - - def test_name_and_call_positions(self): - name = self.get_call('name\nsomething_else') - assert str(name) == 'name' - assert name.start_pos == (1, 0) - assert name.end_pos == (1, 4) - - leaf = self.get_call('1.0\n') - assert leaf.value == '1.0' - assert leaf.eval() == 1.0 - assert leaf.start_pos == (1, 0) - assert leaf.end_pos == (1, 3) - - def test_call_type(self): - call = self.get_call('hello') - assert isinstance(call, pt.Name) - - def test_literal_type(self): - literal = self.get_call('1.0') - assert isinstance(literal, pt.Literal) - assert type(literal.eval()) == float - - literal = self.get_call('1') - assert isinstance(literal, pt.Literal) - assert type(literal.eval()) == int - - literal = self.get_call('"hello"') - assert isinstance(literal, pt.Literal) - assert literal.eval() == 'hello' - - -class TestSubscopes(): - def get_sub(self, source): - return ParserWithRecovery(load_grammar(), u(source)).module.subscopes[0] - - def test_subscope_names(self): - name = self.get_sub('class Foo: pass').name - assert name.start_pos == (1, len('class ')) - assert name.end_pos == (1, len('class Foo')) - assert str(name) == 'Foo' - - name = self.get_sub('def foo(): pass').name - assert name.start_pos == (1, len('def ')) - assert name.end_pos == (1, len('def foo')) - assert str(name) == 'foo' - - -class TestImports(): - def get_import(self, source): - return ParserWithRecovery(load_grammar(), source).module.imports[0] - - def test_import_names(self): - imp = self.get_import(u('import math\n')) - names = imp.get_defined_names() - assert len(names) == 1 - assert str(names[0]) == 'math' - assert names[0].start_pos == (1, len('import ')) - assert names[0].end_pos == (1, len('import math')) - - assert imp.start_pos == (1, 0) - assert imp.end_pos == (1, len('import math')) - - -def test_module(): - module = ParserWithRecovery(load_grammar(), u('asdf'), 'example.py').module - name = module.name - assert str(name) == 'example' - assert name.start_pos == (1, 0) - assert name.end_pos == (1, 7) - - module = ParserWithRecovery(load_grammar(), u('asdf')).module - name = module.name - assert str(name) == '' - assert name.start_pos == (1, 0) - assert name.end_pos == (1, 0) - - -def test_end_pos(): - s = u(dedent(''' - x = ['a', 'b', 'c'] - def func(): - y = None - ''')) - parser = ParserWithRecovery(load_grammar(), s) - scope = parser.module.subscopes[0] - assert scope.start_pos == (3, 0) - assert scope.end_pos == (5, 0) - - -def test_carriage_return_statements(): - source = u(dedent(''' - foo = 'ns1!' - - # this is a namespace package - ''')) - source = source.replace('\n', '\r\n') - stmt = ParserWithRecovery(load_grammar(), source).module.statements[0] - assert '#' not in stmt.get_code() - - -def test_incomplete_list_comprehension(): - """ Shouldn't raise an error, same bug as #418. """ - # With the old parser this actually returned a statement. With the new - # parser only valid statements generate one. - assert ParserWithRecovery(load_grammar(), u('(1 for def')).module.statements == [] - - -def test_hex_values_in_docstring(): - source = r''' - def foo(object): - """ - \xff - """ - return 1 - ''' - - doc = ParserWithRecovery(load_grammar(), dedent(u(source))).module.subscopes[0].raw_doc - if is_py3: - assert doc == '\xff' - else: - assert doc == u('�') - - -def test_error_correction_with(): - source = """ - with open() as f: - try: - f.""" - comps = jedi.Script(source).completions() - assert len(comps) > 30 - # `open` completions have a closed attribute. - assert [1 for c in comps if c.name == 'closed'] - - -def test_newline_positions(): - endmarker = ParserWithRecovery(load_grammar(), u('a\n')).module.children[-1] - assert endmarker.end_pos == (2, 0) - new_line = endmarker.get_previous_leaf() - assert new_line.start_pos == (1, 1) - assert new_line.end_pos == (2, 0) - - -def test_end_pos_error_correction(): - """ - Source code without ending newline are given one, because the Python - grammar needs it. However, they are removed again. We still want the right - end_pos, even if something breaks in the parser (error correction). - """ - s = u('def x():\n .') - m = ParserWithRecovery(load_grammar(), s).module - func = m.children[0] - assert func.type == 'funcdef' - # This is not exactly correct, but ok, because it doesn't make a difference - # at all. We just want to make sure that the module end_pos is correct! - assert func.end_pos == (3, 0) - assert m.end_pos == (2, 2) - - -def test_param_splitting(): - """ - Jedi splits parameters into params, this is not what the grammar does, - but Jedi does this to simplify argument parsing. - """ - def check(src, result): - # Python 2 tuple params should be ignored for now. - grammar = load_grammar('%s.%s' % sys.version_info[:2]) - m = ParserWithRecovery(grammar, u(src)).module - if is_py3: - assert not m.subscopes - else: - # We don't want b and c to be a part of the param enumeration. Just - # ignore them, because it's not what we want to support in the - # future. - assert [str(param.name) for param in m.subscopes[0].params] == result - - check('def x(a, (b, c)):\n pass', ['a']) - check('def x((b, c)):\n pass', []) - - -def test_unicode_string(): - s = pt.String(None, u('bö'), (0, 0)) - assert repr(s) # Should not raise an Error! - - -def test_backslash_dos_style(): - grammar = load_grammar() - m = ParserWithRecovery(grammar, u('\\\r\n')).module - assert m - - -def test_started_lambda_stmt(): - p = ParserWithRecovery(load_grammar(), u'lambda a, b: a i') - assert p.get_parsed_node().children[0].type == 'error_node' - - -def test_python2_octal(): - parser = ParserWithRecovery(load_grammar(), u'0660') - first = parser.get_parsed_node().children[0] - if is_py3: - assert first.type == 'error_node' - else: - assert first.children[0].type == 'number' - - -def test_python3_octal(): - parser = ParserWithRecovery(load_grammar(), u'0o660') - module = parser.get_parsed_node() - if is_py3: - assert module.children[0].children[0].type == 'number' - else: - assert module.children[0].type == 'error_node' diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_parser/test_parser_tree.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_parser/test_parser_tree.py deleted file mode 100644 index 57ea825..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_parser/test_parser_tree.py +++ /dev/null @@ -1,69 +0,0 @@ -# -*- coding: utf-8 # This file contains Unicode characters. - -from textwrap import dedent - -import pytest - -from jedi._compatibility import u, unicode -from jedi.parser import ParserWithRecovery, load_grammar -from jedi.parser import tree as pt - - -class TestsFunctionAndLambdaParsing(object): - - FIXTURES = [ - ('def my_function(x, y, z) -> str:\n return x + y * z\n', { - 'name': 'my_function', - 'call_sig': 'my_function(x, y, z)', - 'params': ['x', 'y', 'z'], - 'annotation': "str", - }), - ('lambda x, y, z: x + y * z\n', { - 'name': '', - 'call_sig': '(x, y, z)', - 'params': ['x', 'y', 'z'], - }), - ] - - @pytest.fixture(params=FIXTURES) - def node(self, request): - parsed = ParserWithRecovery(load_grammar(), dedent(u(request.param[0]))) - request.keywords['expected'] = request.param[1] - return parsed.module.subscopes[0] - - @pytest.fixture() - def expected(self, request, node): - return request.keywords['expected'] - - def test_name(self, node, expected): - assert isinstance(node.name, pt.Name) - assert unicode(node.name) == u(expected['name']) - - def test_params(self, node, expected): - assert isinstance(node.params, list) - assert all(isinstance(x, pt.Param) for x in node.params) - assert [unicode(x.name) for x in node.params] == [u(x) for x in expected['params']] - - def test_is_generator(self, node, expected): - assert node.is_generator() is expected.get('is_generator', False) - - def test_yields(self, node, expected): - # TODO: There's a comment in the code noting that the current implementation is incorrect. This returns an - # empty list at the moment (not e.g. False). - if expected.get('yields', False): - assert node.yields - else: - assert not node.yields - - def test_annotation(self, node, expected): - expected_annotation = expected.get('annotation', None) - if expected_annotation is None: - assert node.annotation() is None - else: - assert node.annotation().value == expected_annotation - - def test_get_call_signature(self, node, expected): - assert node.get_call_signature() == expected['call_sig'] - - def test_doc(self, node, expected): - assert node.doc == expected.get('doc') or (expected['call_sig'] + '\n\n') diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_parser/test_pgen2.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_parser/test_pgen2.py deleted file mode 100644 index 46f4938..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_parser/test_pgen2.py +++ /dev/null @@ -1,279 +0,0 @@ -"""Test suite for 2to3's parser and grammar files. - -This is the place to add tests for changes to 2to3's grammar, such as those -merging the grammars for Python 2 and 3. In addition to specific tests for -parts of the grammar we've changed, we also make sure we can parse the -test_grammar.py files from both Python 2 and Python 3. -""" - -from textwrap import dedent - - -from jedi._compatibility import unicode, is_py3 -from jedi.parser import Parser, load_grammar, ParseError -import pytest - -from test.helpers import TestCase - - -def parse(code, version='3.4'): - code = dedent(code) + "\n\n" - grammar = load_grammar(version=version) - return Parser(grammar, unicode(code), 'file_input').get_parsed_node() - - -class TestDriver(TestCase): - - def test_formfeed(self): - s = """print 1\n\x0Cprint 2\n""" - t = parse(s, '2.7') - self.assertEqual(t.children[0].children[0].type, 'print_stmt') - self.assertEqual(t.children[1].children[0].type, 'print_stmt') - s = """1\n\x0C\x0C2\n""" - t = parse(s, '2.7') - - -class GrammarTest(TestCase): - def invalid_syntax(self, code, **kwargs): - try: - parse(code, **kwargs) - except ParseError: - pass - else: - raise AssertionError("Syntax shouldn't have been valid") - - -class TestMatrixMultiplication(GrammarTest): - @pytest.mark.skipif('sys.version_info[:2] < (3, 5)') - def test_matrix_multiplication_operator(self): - parse("a @ b", "3.5") - parse("a @= b", "3.5") - - -class TestYieldFrom(GrammarTest): - def test_yield_from(self): - parse("yield from x") - parse("(yield from x) + y") - self.invalid_syntax("yield from") - - -class TestAsyncAwait(GrammarTest): - @pytest.mark.skipif('sys.version_info[:2] < (3, 5)') - def test_await_expr(self): - parse("""async def foo(): - await x - """, "3.5") - - parse("""async def foo(): - - def foo(): pass - - def foo(): pass - - await x - """, "3.5") - - parse("""async def foo(): return await a""", "3.5") - - parse("""def foo(): - def foo(): pass - async def foo(): await x - """, "3.5") - - @pytest.mark.skipif('sys.version_info[:2] < (3, 5)') - @pytest.mark.xfail(reason="acting like python 3.7") - def test_await_expr_invalid(self): - self.invalid_syntax("await x", version="3.5") - self.invalid_syntax("""def foo(): - await x""", version="3.5") - - self.invalid_syntax("""def foo(): - def foo(): pass - async def foo(): pass - await x - """, version="3.5") - - @pytest.mark.skipif('sys.version_info[:2] < (3, 5)') - @pytest.mark.xfail(reason="acting like python 3.7") - def test_async_var(self): - parse("""async = 1""", "3.5") - parse("""await = 1""", "3.5") - parse("""def async(): pass""", "3.5") - - @pytest.mark.skipif('sys.version_info[:2] < (3, 5)') - def test_async_for(self): - parse("""async def foo(): - async for a in b: pass""", "3.5") - - @pytest.mark.skipif('sys.version_info[:2] < (3, 5)') - @pytest.mark.xfail(reason="acting like python 3.7") - def test_async_for_invalid(self): - self.invalid_syntax("""def foo(): - async for a in b: pass""", version="3.5") - - @pytest.mark.skipif('sys.version_info[:2] < (3, 5)') - def test_async_with(self): - parse("""async def foo(): - async with a: pass""", "3.5") - - @pytest.mark.skipif('sys.version_info[:2] < (3, 5)') - @pytest.mark.xfail(reason="acting like python 3.7") - def test_async_with_invalid(self): - self.invalid_syntax("""def foo(): - async with a: pass""", version="3.5") - - -class TestRaiseChanges(GrammarTest): - def test_2x_style_1(self): - parse("raise") - - def test_2x_style_2(self): - parse("raise E, V", version='2.7') - - def test_2x_style_3(self): - parse("raise E, V, T", version='2.7') - - def test_2x_style_invalid_1(self): - self.invalid_syntax("raise E, V, T, Z", version='2.7') - - def test_3x_style(self): - parse("raise E1 from E2") - - def test_3x_style_invalid_1(self): - self.invalid_syntax("raise E, V from E1") - - def test_3x_style_invalid_2(self): - self.invalid_syntax("raise E from E1, E2") - - def test_3x_style_invalid_3(self): - self.invalid_syntax("raise from E1, E2") - - def test_3x_style_invalid_4(self): - self.invalid_syntax("raise E from") - - -# Adapted from Python 3's Lib/test/test_grammar.py:GrammarTests.testFuncdef -class TestFunctionAnnotations(GrammarTest): - def test_1(self): - parse("""def f(x) -> list: pass""") - - def test_2(self): - parse("""def f(x:int): pass""") - - def test_3(self): - parse("""def f(*x:str): pass""") - - def test_4(self): - parse("""def f(**x:float): pass""") - - def test_5(self): - parse("""def f(x, y:1+2): pass""") - - def test_6(self): - self.invalid_syntax("""def f(a, (b:1, c:2, d)): pass""") - - def test_7(self): - self.invalid_syntax("""def f(a, (b:1, c:2, d), e:3=4, f=5, *g:6): pass""") - - def test_8(self): - s = """def f(a, (b:1, c:2, d), e:3=4, f=5, - *g:6, h:7, i=8, j:9=10, **k:11) -> 12: pass""" - self.invalid_syntax(s) - - -class TestExcept(GrammarTest): - def test_new(self): - s = """ - try: - x - except E as N: - y""" - parse(s) - - def test_old(self): - s = """ - try: - x - except E, N: - y""" - parse(s, version='2.7') - - -# Adapted from Python 3's Lib/test/test_grammar.py:GrammarTests.testAtoms -class TestSetLiteral(GrammarTest): - def test_1(self): - parse("""x = {'one'}""") - - def test_2(self): - parse("""x = {'one', 1,}""") - - def test_3(self): - parse("""x = {'one', 'two', 'three'}""") - - def test_4(self): - parse("""x = {2, 3, 4,}""") - - -class TestNumericLiterals(GrammarTest): - def test_new_octal_notation(self): - code = """0o7777777777777""" - if is_py3: - parse(code) - else: - self.invalid_syntax(code) - self.invalid_syntax("""0o7324528887""") - - def test_new_binary_notation(self): - parse("""0b101010""") - self.invalid_syntax("""0b0101021""") - - -class TestClassDef(GrammarTest): - def test_new_syntax(self): - parse("class B(t=7): pass") - parse("class B(t, *args): pass") - parse("class B(t, **kwargs): pass") - parse("class B(t, *args, **kwargs): pass") - parse("class B(t, y=9, *args, **kwargs): pass") - - -class TestParserIdempotency(TestCase): - """A cut-down version of pytree_idempotency.py.""" - def test_extended_unpacking(self): - parse("a, *b, c = x\n") - parse("[*a, b] = x\n") - parse("(z, *y, w) = m\n") - parse("for *z, m in d: pass\n") - - -class TestLiterals(GrammarTest): - # It's not possible to get the same result when using \xaa in Python 2/3, - # because it's treated differently. - @pytest.mark.skipif('sys.version_info[0] < 3') - def test_multiline_bytes_literals(self): - s = """ - md5test(b"\xaa" * 80, - (b"Test Using Larger Than Block-Size Key " - b"and Larger Than One Block-Size Data"), - "6f630fad67cda0ee1fb1f562db3aa53e") - """ - parse(s) - - def test_multiline_bytes_tripquote_literals(self): - s = ''' - b""" - - - """ - ''' - parse(s) - - @pytest.mark.skipif('sys.version_info[0] < 3') - def test_multiline_str_literals(self): - s = """ - md5test("\xaa" * 80, - ("Test Using Larger Than Block-Size Key " - "and Larger Than One Block-Size Data"), - "6f630fad67cda0ee1fb1f562db3aa53e") - """ - parse(s) diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_parser/test_tokenize.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_parser/test_tokenize.py deleted file mode 100644 index e53f85a..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_parser/test_tokenize.py +++ /dev/null @@ -1,152 +0,0 @@ -# -*- coding: utf-8 # This file contains Unicode characters. - -from io import StringIO -from textwrap import dedent - -import pytest - -from jedi._compatibility import u, is_py3 -from jedi.parser.token import NAME, OP, NEWLINE, STRING, INDENT -from jedi.parser import ParserWithRecovery, load_grammar, tokenize - - -from ..helpers import unittest - - -class TokenTest(unittest.TestCase): - def test_end_pos_one_line(self): - parsed = ParserWithRecovery(load_grammar(), dedent(u(''' - def testit(): - a = "huhu" - '''))) - tok = parsed.module.subscopes[0].statements[0].children[2] - assert tok.end_pos == (3, 14) - - def test_end_pos_multi_line(self): - parsed = ParserWithRecovery(load_grammar(), dedent(u(''' - def testit(): - a = """huhu - asdfasdf""" + "h" - '''))) - tok = parsed.module.subscopes[0].statements[0].children[2].children[0] - assert tok.end_pos == (4, 11) - - def test_simple_no_whitespace(self): - # Test a simple one line string, no preceding whitespace - simple_docstring = u('"""simple one line docstring"""') - simple_docstring_io = StringIO(simple_docstring) - tokens = tokenize.generate_tokens(simple_docstring_io.readline) - token_list = list(tokens) - _, value, _, prefix = token_list[0] - assert prefix == '' - assert value == '"""simple one line docstring"""' - - def test_simple_with_whitespace(self): - # Test a simple one line string with preceding whitespace and newline - simple_docstring = u(' """simple one line docstring""" \r\n') - simple_docstring_io = StringIO(simple_docstring) - tokens = tokenize.generate_tokens(simple_docstring_io.readline) - token_list = list(tokens) - assert token_list[0][0] == INDENT - typ, value, start_pos, prefix = token_list[1] - assert prefix == ' ' - assert value == '"""simple one line docstring"""' - assert typ == STRING - typ, value, start_pos, prefix = token_list[2] - assert prefix == ' ' - assert typ == NEWLINE - - def test_function_whitespace(self): - # Test function definition whitespace identification - fundef = dedent(u(''' - def test_whitespace(*args, **kwargs): - x = 1 - if x > 0: - print(True) - ''')) - fundef_io = StringIO(fundef) - tokens = tokenize.generate_tokens(fundef_io.readline) - token_list = list(tokens) - for _, value, _, prefix in token_list: - if value == 'test_whitespace': - assert prefix == ' ' - if value == '(': - assert prefix == '' - if value == '*': - assert prefix == '' - if value == '**': - assert prefix == ' ' - if value == 'print': - assert prefix == ' ' - if value == 'if': - assert prefix == ' ' - - def test_identifier_contains_unicode(self): - fundef = dedent(u(''' - def 我あφ(): - pass - ''')) - fundef_io = StringIO(fundef) - tokens = tokenize.generate_tokens(fundef_io.readline) - token_list = list(tokens) - unicode_token = token_list[1] - if is_py3: - assert unicode_token[0] == NAME - else: - # Unicode tokens in Python 2 seem to be identified as operators. - # They will be ignored in the parser, that's ok. - assert unicode_token[0] == OP - - def test_quoted_strings(self): - - string_tokens = [ - 'u"test"', - 'u"""test"""', - 'U"""test"""', - "u'''test'''", - "U'''test'''", - ] - - for s in string_tokens: - parsed = ParserWithRecovery(load_grammar(), u('''a = %s\n''' % s)) - simple_stmt = parsed.module.children[0] - expr_stmt = simple_stmt.children[0] - assert len(expr_stmt.children) == 3 - string_tok = expr_stmt.children[2] - assert string_tok.type == 'string' - assert string_tok.value == s - assert string_tok.eval() == 'test' - - -def test_tokenizer_with_string_literal_backslash(): - import jedi - c = jedi.Script("statement = u'foo\\\n'; statement").goto_definitions() - assert c[0]._name.parent.obj == 'foo' - - -def test_ur_literals(): - """ - Decided to parse `u''` literals regardless of Python version. This makes - probably sense: - - - Python 3.2 doesn't support it and is still supported by Jedi, but might - not be. While this is incorrect, it's just incorrect for one "old" and in - the future not very important version. - - All the other Python versions work very well with it. - """ - def check(literal): - io = StringIO(u(literal)) - tokens = tokenize.generate_tokens(io.readline) - token_list = list(tokens) - typ, result_literal, _, _ = token_list[0] - assert typ == STRING - assert result_literal == literal - - check('u""') - check('ur""') - check('Ur""') - check('UR""') - check('bR""') - # Must be in the right order. - with pytest.raises(AssertionError): - check('Rb""') diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_parser/test_user_context.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_parser/test_user_context.py deleted file mode 100644 index 01aff79..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_parser/test_user_context.py +++ /dev/null @@ -1,6 +0,0 @@ -import jedi - - -def test_form_feed_characters(): - s = "\f\nclass Test(object):\n pass" - jedi.Script(s, line=2, column=18).call_signatures() diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_regression.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_regression.py deleted file mode 100644 index abb1072..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_regression.py +++ /dev/null @@ -1,206 +0,0 @@ -""" -Unit tests to avoid errors of the past. These are also all tests that didn't -found a good place in any other testing module. -""" - -import os -import sys -import textwrap - -from .helpers import TestCase, cwd_at - -import pytest -import jedi -from jedi._compatibility import u -from jedi import Script -from jedi import api -from jedi import common -from jedi.evaluate import imports -from jedi.parser import ParserWithRecovery, load_grammar - -#jedi.set_debug_function() - - -class TestRegression(TestCase): - def test_goto_definition_cursor(self): - - s = ("class A():\n" - " def _something(self):\n" - " return\n" - " def different_line(self,\n" - " b):\n" - " return\n" - "A._something\n" - "A.different_line" - ) - - in_name = 2, 9 - under_score = 2, 8 - cls = 2, 7 - should1 = 7, 10 - diff_line = 4, 10 - should2 = 8, 10 - - def get_def(pos): - return [d.description for d in Script(s, *pos).goto_definitions()] - - in_name = get_def(in_name) - under_score = get_def(under_score) - should1 = get_def(should1) - should2 = get_def(should2) - - diff_line = get_def(diff_line) - - assert should1 == in_name - assert should1 == under_score - - assert should2 == diff_line - - assert get_def(cls) == [] - - @pytest.mark.skipif('True', reason='Skip for now, test case is not really supported.') - @cwd_at('jedi') - def test_add_dynamic_mods(self): - fname = '__main__.py' - api.settings.additional_dynamic_modules = [fname] - # Fictional module that defines a function. - src1 = "def r(a): return a" - # Other fictional modules in another place in the fs. - src2 = 'from .. import setup; setup.r(1)' - script = Script(src1, path='../setup.py') - imports.load_module(script._evaluator, os.path.abspath(fname), src2) - result = script.goto_definitions() - assert len(result) == 1 - assert result[0].description == 'class int' - - def test_os_nowait(self): - """ github issue #45 """ - s = Script("import os; os.P_").completions() - assert 'P_NOWAIT' in [i.name for i in s] - - def test_points_in_completion(self): - """At some point, points were inserted into the completions, this - caused problems, sometimes. - """ - c = Script("if IndentationErr").completions() - assert c[0].name == 'IndentationError' - self.assertEqual(c[0].complete, 'or') - - def test_no_statement_parent(self): - source = textwrap.dedent(""" - def f(): - pass - - class C: - pass - - variable = f if random.choice([0, 1]) else C""") - defs = Script(source, column=3).goto_definitions() - defs = sorted(defs, key=lambda d: d.line) - self.assertEqual([d.description for d in defs], - ['def f', 'class C']) - - def test_end_pos_line(self): - # jedi issue #150 - s = u("x()\nx( )\nx( )\nx ( )") - parser = ParserWithRecovery(load_grammar(), s) - for i, s in enumerate(parser.module.statements): - assert s.end_pos == (i + 1, i + 3) - - def check_definition_by_marker(self, source, after_cursor, names): - r""" - Find definitions specified by `after_cursor` and check what found - - For example, for the following configuration, you can pass - ``after_cursor = 'y)'``.:: - - function( - x, y) - \ - `- You want cursor to be here - """ - source = textwrap.dedent(source) - for (i, line) in enumerate(source.splitlines()): - if after_cursor in line: - break - column = len(line) - len(after_cursor) - defs = Script(source, i + 1, column).goto_definitions() - print(defs) - assert [d.name for d in defs] == names - - def test_backslash_continuation(self): - """ - Test that ModuleWithCursor.get_path_until_cursor handles continuation - """ - self.check_definition_by_marker(r""" - x = 0 - a = \ - [1, 2, 3, 4, 5, 6, 7, 8, 9, x] # <-- here - """, '] # <-- here', ['int']) - - # completion in whitespace - s = 'asdfxyxxxxxxxx sds\\\n hello' - assert Script(s, 2, 4).goto_assignments() == [] - - def test_backslash_continuation_and_bracket(self): - self.check_definition_by_marker(r""" - x = 0 - a = \ - [1, 2, 3, 4, 5, 6, 7, 8, 9, (x)] # <-- here - """, '(x)] # <-- here', ['int']) - - def test_generator(self): - # Did have some problems with the usage of generator completions this - # way. - s = "def abc():\n" \ - " yield 1\n" \ - "abc()." - assert Script(s).completions() - - def test_fake_subnodes(self): - """ - Test the number of subnodes of a fake object. - - There was a bug where the number of child nodes would grow on every - call to :func:``jedi.evaluate.compiled.fake.get_faked``. - - See Github PR#649 and isseu #591. - """ - def get_str_completion(values): - for c in values: - if c.name == 'str': - return c - limit = None - for i in range(2): - completions = Script('').completions() - c = get_str_completion(completions) - n = len(c._definition.subscopes[0].children[-1].children) - if i == 0: - limit = n - else: - assert n == limit - - def test_source_to_unicode_unicode_text(self): - source = ( - b"# vim: fileencoding=utf-8\n" - b"# \xe3\x81\x82\xe3\x81\x84\xe3\x81\x86\xe3\x81\x88\xe3\x81\x8a\n" - ) - actual = common.source_to_unicode(source) - expected = source.decode('utf-8') - assert actual == expected - - -def test_loading_unicode_files_with_bad_global_charset(monkeypatch, tmpdir): - dirname = str(tmpdir.mkdir('jedi-test')) - filename1 = os.path.join(dirname, 'test1.py') - filename2 = os.path.join(dirname, 'test2.py') - if sys.version_info < (3, 0): - data = "# coding: latin-1\nfoo = 'm\xf6p'\n" - else: - data = "# coding: latin-1\nfoo = 'm\xf6p'\n".encode("latin-1") - - with open(filename1, "wb") as f: - f.write(data) - s = Script("from test1 import foo\nfoo.", - line=2, column=4, path=filename2) - s.completions() diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_speed.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_speed.py deleted file mode 100644 index 4ea1656..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_speed.py +++ /dev/null @@ -1,53 +0,0 @@ -""" -Speed tests of Jedi. To prove that certain things don't take longer than they -should. -""" - -import time -import functools - -from .helpers import TestCase, cwd_at -import jedi - -class TestSpeed(TestCase): - def _check_speed(time_per_run, number=4, run_warm=True): - """ Speed checks should typically be very tolerant. Some machines are - faster than others, but the tests should still pass. These tests are - here to assure that certain effects that kill jedi performance are not - reintroduced to Jedi.""" - def decorated(func): - @functools.wraps(func) - def wrapper(self): - if run_warm: - func(self) - first = time.time() - for i in range(number): - func(self) - single_time = (time.time() - first) / number - print('\nspeed', func, single_time) - assert single_time < time_per_run - return wrapper - return decorated - - @_check_speed(0.2) - def test_os_path_join(self): - s = "from posixpath import join; join('', '')." - assert len(jedi.Script(s).completions()) > 10 # is a str completion - - @_check_speed(0.15) - def test_scipy_speed(self): - s = 'import scipy.weave; scipy.weave.inline(' - script = jedi.Script(s, 1, len(s), '') - script.call_signatures() - #print(jedi.imports.imports_processed) - - @_check_speed(0.8) - @cwd_at('test') - def test_precedence_slowdown(self): - """ - Precedence calculation can slow down things significantly in edge - cases. Having strange recursion structures increases the problem. - """ - with open('speed/precedence.py') as f: - line = len(f.read().splitlines()) - assert jedi.Script(line=line, path='speed/precedence.py').goto_definitions() diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_utils.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_utils.py deleted file mode 100644 index 2eb6e8c..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_utils.py +++ /dev/null @@ -1,111 +0,0 @@ -try: - import readline -except ImportError: - readline = False - -from jedi import utils - -from .helpers import unittest, cwd_at - - -@unittest.skipIf(not readline, "readline not found") -class TestSetupReadline(unittest.TestCase): - class NameSpace(object): - pass - - def __init__(self, *args, **kwargs): - super(type(self), self).__init__(*args, **kwargs) - - self.namespace = self.NameSpace() - utils.setup_readline(self.namespace) - - def completions(self, text): - completer = readline.get_completer() - i = 0 - completions = [] - while True: - completion = completer(text, i) - if completion is None: - break - completions.append(completion) - i += 1 - return completions - - def test_simple(self): - assert self.completions('list') == ['list'] - assert self.completions('importerror') == ['ImportError'] - s = "print(BaseE" - assert self.completions(s) == [s + 'xception'] - - def test_nested(self): - assert self.completions('list.Insert') == ['list.insert'] - assert self.completions('list().Insert') == ['list().insert'] - - def test_magic_methods(self): - assert self.completions('list.__getitem__') == ['list.__getitem__'] - assert self.completions('list().__getitem__') == ['list().__getitem__'] - - def test_modules(self): - import sys - import os - self.namespace.sys = sys - self.namespace.os = os - - try: - assert self.completions('os.path.join') == ['os.path.join'] - string = 'os.path.join("a").upper' - assert self.completions(string) == [string] - - c = set(['os.' + d for d in dir(os) if d.startswith('ch')]) - assert set(self.completions('os.ch')) == set(c) - finally: - del self.namespace.sys - del self.namespace.os - - def test_calls(self): - s = 'str(bytes' - assert self.completions(s) == [s, 'str(BytesWarning'] - - def test_import(self): - s = 'from os.path import a' - assert set(self.completions(s)) == set([s + 'ltsep', s + 'bspath']) - assert self.completions('import keyword') == ['import keyword'] - - import os - s = 'from os import ' - goal = set([s + el for el in dir(os)]) - # There are minor differences, e.g. the dir doesn't include deleted - # items as well as items that are not only available on linux. - assert len(set(self.completions(s)).symmetric_difference(goal)) < 20 - - @cwd_at('test') - def test_local_import(self): - s = 'import test_utils' - assert self.completions(s) == [s] - - def test_preexisting_values(self): - self.namespace.a = range(10) - assert set(self.completions('a.')) == set(['a.' + n for n in dir(range(1))]) - del self.namespace.a - - def test_colorama(self): - """ - Only test it if colorama library is available. - - This module is being tested because it uses ``setattr`` at some point, - which Jedi doesn't understand, but it should still work in the REPL. - """ - try: - # if colorama is installed - import colorama - except ImportError: - pass - else: - self.namespace.colorama = colorama - assert self.completions('colorama') - assert self.completions('colorama.Fore.BLACK') == ['colorama.Fore.BLACK'] - del self.namespace.colorama - - -def test_version_info(): - assert utils.version_info()[:2] > (0, 7) diff --git a/vim-plugins/bundle/jedi-vim/jedi/test/test_windows.py b/vim-plugins/bundle/jedi-vim/jedi/test/test_windows.py deleted file mode 100644 index e5d8cd0..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/test/test_windows.py +++ /dev/null @@ -1,8 +0,0 @@ -import jedi - -def test_path_issues(): - """ - See pull request #684 for details. - """ - source = '''from datetime import ''' - assert jedi.Script(source).completions() diff --git a/vim-plugins/bundle/jedi-vim/jedi/tox.ini b/vim-plugins/bundle/jedi-vim/jedi/tox.ini deleted file mode 100644 index 97b77a1..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi/tox.ini +++ /dev/null @@ -1,47 +0,0 @@ -[tox] -envlist = py26, py27, py33, py34, py35 -[testenv] -deps = - pytest>=2.3.5 - pytest-cache -# docopt for sith doctests - docopt -# coloroma for colored debug output - colorama -setenv = -# https://github.com/tomchristie/django-rest-framework/issues/1957 -# tox corrupts __pycache__, solution from here: - PYTHONDONTWRITEBYTECODE=1 -commands = - py.test {posargs:jedi test} -[testenv:py26] -deps = - unittest2 - {[testenv]deps} -[testenv:py27] -deps = -# for testing the typing module - typing - {[testenv]deps} -[testenv:py33] -deps = - typing - {[testenv]deps} -[testenv:py34] -deps = - typing - {[testenv]deps} -[testenv:py35] -deps = - {[testenv]deps} -[testenv:cov] -deps = - coverage - {[testenv]deps} -commands = - coverage run --source jedi -m py.test - coverage report -[testenv:sith] -commands = - {envpython} -c "import os; a='{envtmpdir}'; os.path.exists(a) or os.makedirs(a)" - {envpython} sith.py --record {envtmpdir}/record.json random {posargs:jedi} diff --git a/vim-plugins/bundle/jedi-vim/jedi_vim.py b/vim-plugins/bundle/jedi-vim/jedi_vim.py deleted file mode 100644 index 5ddd80a..0000000 --- a/vim-plugins/bundle/jedi-vim/jedi_vim.py +++ /dev/null @@ -1,723 +0,0 @@ -# -*- coding: utf-8 -*- -""" -The Python parts of the Jedi library for VIM. It is mostly about communicating -with VIM. -""" - -import traceback # for exception output -import re -import os -import sys -from shlex import split as shsplit -from contextlib import contextmanager -try: - from itertools import zip_longest -except ImportError: - from itertools import izip_longest as zip_longest # Python 2 - -import vim - -is_py3 = sys.version_info[0] >= 3 -if is_py3: - ELLIPSIS = "…" - unicode = str -else: - ELLIPSIS = u"…" - - -class PythonToVimStr(unicode): - """ Vim has a different string implementation of single quotes """ - __slots__ = [] - - def __new__(cls, obj, encoding='UTF-8'): - if not (is_py3 or isinstance(obj, unicode)): - obj = unicode.__new__(cls, obj, encoding) - - # Vim cannot deal with zero bytes: - obj = obj.replace('\0', '\\0') - return unicode.__new__(cls, obj) - - def __repr__(self): - # this is totally stupid and makes no sense but vim/python unicode - # support is pretty bad. don't ask how I came up with this... It just - # works... - # It seems to be related to that bug: http://bugs.python.org/issue5876 - if unicode is str: - s = self - else: - s = self.encode('UTF-8') - return '"%s"' % s.replace('\\', '\\\\').replace('"', r'\"') - - -class VimError(Exception): - def __init__(self, message, throwpoint, executing): - super(type(self), self).__init__(message) - self.message = message - self.throwpoint = throwpoint - self.executing = executing - - def __str__(self): - return self.message + '; created by: ' + repr(self.executing) - - -def _catch_exception(string, is_eval): - """ - Interface between vim and python calls back to it. - Necessary, because the exact error message is not given by `vim.error`. - """ - result = vim.eval('jedi#_vim_exceptions({0}, {1})'.format( - repr(PythonToVimStr(string, 'UTF-8')), int(is_eval))) - if 'exception' in result: - raise VimError(result['exception'], result['throwpoint'], string) - return result['result'] - - -def vim_command(string): - _catch_exception(string, False) - - -def vim_eval(string): - return _catch_exception(string, True) - - -def no_jedi_warning(error=None): - vim.command('echohl WarningMsg') - vim.command('echom "Please install Jedi if you want to use jedi-vim."') - if error: - vim.command('echom "The error was: {0}"'.format(error)) - vim.command('echohl None') - - -def echo_highlight(msg): - vim_command('echohl WarningMsg | echom "jedi-vim: {0}" | echohl None'.format( - str(msg).replace('"', '\\"'))) - - -try: - import jedi -except ImportError as e: - no_jedi_warning(str(e)) - jedi = None - jedi_import_error = str(e) -else: - try: - version = jedi.__version__ - except Exception as e: # e.g. AttributeError - echo_highlight( - "Error when loading the jedi python module ({0}). " - "Please ensure that Jedi is installed correctly (see Installation " - "in the README.".format(e)) - jedi = None - else: - if isinstance(version, str): - # the normal use case, now. - from jedi import utils - version = utils.version_info() - if version < (0, 7): - echo_highlight('Please update your Jedi version, it is too old.') - - -def catch_and_print_exceptions(func): - def wrapper(*args, **kwargs): - try: - return func(*args, **kwargs) - except (Exception, vim.error): - print(traceback.format_exc()) - return None - return wrapper - - -def _check_jedi_availability(show_error=False): - def func_receiver(func): - def wrapper(*args, **kwargs): - if jedi is None: - if show_error: - no_jedi_warning() - return - else: - return func(*args, **kwargs) - return wrapper - return func_receiver - - -@catch_and_print_exceptions -def get_script(source=None, column=None): - jedi.settings.additional_dynamic_modules = \ - [b.name for b in vim.buffers if b.name is not None and b.name.endswith('.py')] - if source is None: - source = '\n'.join(vim.current.buffer) - row = vim.current.window.cursor[0] - if column is None: - column = vim.current.window.cursor[1] - buf_path = vim.current.buffer.name - encoding = vim_eval('&encoding') or 'latin1' - return jedi.Script(source, row, column, buf_path, encoding) - - -@_check_jedi_availability(show_error=False) -@catch_and_print_exceptions -def completions(): - row, column = vim.current.window.cursor - # Clear call signatures in the buffer so they aren't seen by the completer. - # Call signatures in the command line can stay. - if int(vim_eval("g:jedi#show_call_signatures")) == 1: - clear_call_signatures() - if vim.eval('a:findstart') == '1': - count = 0 - for char in reversed(vim.current.line[:column]): - if not re.match('[\w\d]', char): - break - count += 1 - vim.command('return %i' % (column - count)) - else: - base = vim.eval('a:base') - source = '' - for i, line in enumerate(vim.current.buffer): - # enter this path again, otherwise source would be incomplete - if i == row - 1: - source += line[:column] + base + line[column:] - else: - source += line - source += '\n' - # here again hacks, because jedi has a different interface than vim - column += len(base) - try: - script = get_script(source=source, column=column) - completions = script.completions() - signatures = script.call_signatures() - - out = [] - for c in completions: - d = dict(word=PythonToVimStr(c.name[:len(base)] + c.complete), - abbr=PythonToVimStr(c.name_with_symbols), - # stuff directly behind the completion - menu=PythonToVimStr(c.description), - info=PythonToVimStr(c.docstring()), # docstr - icase=1, # case insensitive - dup=1 # allow duplicates (maybe later remove this) - ) - out.append(d) - - strout = str(out) - except Exception: - # print to stdout, will be in :messages - print(traceback.format_exc()) - strout = '' - completions = [] - signatures = [] - - show_call_signatures(signatures) - vim.command('return ' + strout) - - -@contextmanager -def tempfile(content): - # Using this instead of the tempfile module because Windows won't read - # from a file not yet written to disk - with open(vim_eval('tempname()'), 'w') as f: - f.write(content) - try: - yield f - finally: - os.unlink(f.name) - -@_check_jedi_availability(show_error=True) -@catch_and_print_exceptions -def goto(mode="goto", no_output=False): - """ - :param str mode: "related_name", "definition", "assignment", "auto" - :return: list of definitions/assignments - :rtype: list - """ - script = get_script() - try: - if mode == "goto": - definitions = [x for x in script.goto_definitions() - if not x.in_builtin_module()] - if not definitions: - definitions = script.goto_assignments() - elif mode == "related_name": - definitions = script.usages() - elif mode == "definition": - definitions = script.goto_definitions() - elif mode == "assignment": - definitions = script.goto_assignments() - except jedi.NotFoundError: - echo_highlight("Cannot follow nothing. Put your cursor on a valid name.") - definitions = [] - else: - if no_output: - return definitions - if not definitions: - echo_highlight("Couldn't find any definitions for this.") - elif len(definitions) == 1 and mode != "related_name": - d = list(definitions)[0] - if d.in_builtin_module(): - if d.is_keyword: - echo_highlight("Cannot get the definition of Python keywords.") - else: - echo_highlight("Builtin modules cannot be displayed (%s)." - % d.desc_with_module) - else: - using_tagstack = int(vim_eval('g:jedi#use_tag_stack')) == 1 - if d.module_path != vim.current.buffer.name: - result = new_buffer(d.module_path, - using_tagstack=using_tagstack) - if not result: - return [] - if d.module_path and using_tagstack: - tagname = d.name - with tempfile('{0}\t{1}\t{2}'.format(tagname, d.module_path, - 'call cursor({0}, {1})'.format(d.line, d.column + 1))) as f: - old_tags = vim.eval('&tags') - old_wildignore = vim.eval('&wildignore') - try: - # Clear wildignore to ensure tag file isn't ignored - vim.command('set wildignore=') - vim.command('let &tags = %s' % - repr(PythonToVimStr(f.name))) - vim.command('tjump %s' % tagname) - finally: - vim.command('let &tags = %s' % - repr(PythonToVimStr(old_tags))) - vim.command('let &wildignore = %s' % - repr(PythonToVimStr(old_wildignore))) - vim.current.window.cursor = d.line, d.column - else: - # multiple solutions - lst = [] - for d in definitions: - if d.in_builtin_module(): - lst.append(dict(text=PythonToVimStr('Builtin ' + d.description))) - else: - lst.append(dict(filename=PythonToVimStr(d.module_path), - lnum=d.line, col=d.column + 1, - text=PythonToVimStr(d.description))) - vim_eval('setqflist(%s)' % repr(lst)) - vim_eval('jedi#add_goto_window(' + str(len(lst)) + ')') - return definitions - - -@_check_jedi_availability(show_error=True) -@catch_and_print_exceptions -def show_documentation(): - script = get_script() - try: - definitions = script.goto_definitions() - except jedi.NotFoundError: - definitions = [] - except Exception: - # print to stdout, will be in :messages - definitions = [] - print("Exception, this shouldn't happen.") - print(traceback.format_exc()) - - if not definitions: - echo_highlight('No documentation found for that.') - vim.command('return') - else: - docs = ['Docstring for %s\n%s\n%s' % (d.desc_with_module, '=' * 40, d.docstring()) - if d.docstring() else '|No Docstring for %s|' % d for d in definitions] - text = ('\n' + '-' * 79 + '\n').join(docs) - vim.command('let l:doc = %s' % repr(PythonToVimStr(text))) - vim.command('let l:doc_lines = %s' % len(text.split('\n'))) - return True - - -@catch_and_print_exceptions -def clear_call_signatures(): - # Check if using command line call signatures - if int(vim_eval("g:jedi#show_call_signatures")) == 2: - vim_command('echo ""') - return - cursor = vim.current.window.cursor - e = vim_eval('g:jedi#call_signature_escape') - # We need two turns here to search and replace certain lines: - # 1. Search for a line with a call signature and save the appended - # characters - # 2. Actually replace the line and redo the status quo. - py_regex = r'%sjedi=([0-9]+), (.*?)%s.*?%sjedi%s'.replace( - '%s', re.escape(e)) - for i, line in enumerate(vim.current.buffer): - match = re.search(py_regex, line) - if match is not None: - # Some signs were added to minimize syntax changes due to call - # signatures. We have to remove them again. The number of them is - # specified in `match.group(1)`. - after = line[match.end() + int(match.group(1)):] - line = line[:match.start()] + match.group(2) + after - vim.current.buffer[i] = line - vim.current.window.cursor = cursor - - -@_check_jedi_availability(show_error=False) -@catch_and_print_exceptions -def show_call_signatures(signatures=()): - if int(vim_eval("has('conceal') && g:jedi#show_call_signatures")) == 0: - return - - if signatures == (): - signatures = get_script().call_signatures() - clear_call_signatures() - - if not signatures: - return - - if int(vim_eval("g:jedi#show_call_signatures")) == 2: - return cmdline_call_signatures(signatures) - - for i, signature in enumerate(signatures): - line, column = signature.bracket_start - # signatures are listed above each other - line_to_replace = line - i - 1 - # because there's a space before the bracket - insert_column = column - 1 - if insert_column < 0 or line_to_replace <= 0: - # Edge cases, when the call signature has no space on the screen. - break - - # TODO check if completion menu is above or below - line = vim_eval("getline(%s)" % line_to_replace) - - params = [p.description.replace('\n', '') for p in signature.params] - try: - # *_*PLACEHOLDER*_* makes something fat. See after/syntax file. - params[signature.index] = '*_*%s*_*' % params[signature.index] - except (IndexError, TypeError): - pass - - # This stuff is reaaaaally a hack! I cannot stress enough, that - # this is a stupid solution. But there is really no other yet. - # There is no possibility in VIM to draw on the screen, but there - # will be one (see :help todo Patch to access screen under Python. - # (Marko Mahni, 2010 Jul 18)) - text = " (%s) " % ', '.join(params) - text = ' ' * (insert_column - len(line)) + text - end_column = insert_column + len(text) - 2 # -2 due to bold symbols - - # Need to decode it with utf8, because vim returns always a python 2 - # string even if it is unicode. - e = vim_eval('g:jedi#call_signature_escape') - if hasattr(e, 'decode'): - e = e.decode('UTF-8') - # replace line before with cursor - regex = "xjedi=%sx%sxjedix".replace('x', e) - - prefix, replace = line[:insert_column], line[insert_column:end_column] - - # Check the replace stuff for strings, to append them - # (don't want to break the syntax) - regex_quotes = r'''\\*["']+''' - # `add` are all the quotation marks. - # join them with a space to avoid producing ''' - add = ' '.join(re.findall(regex_quotes, replace)) - # search backwards - if add and replace[0] in ['"', "'"]: - a = re.search(regex_quotes + '$', prefix) - add = ('' if a is None else a.group(0)) + add - - tup = '%s, %s' % (len(add), replace) - repl = prefix + (regex % (tup, text)) + add + line[end_column:] - - vim_eval('setline(%s, %s)' % (line_to_replace, repr(PythonToVimStr(repl)))) - - -@catch_and_print_exceptions -def cmdline_call_signatures(signatures): - def get_params(s): - return [p.description.replace('\n', '') for p in s.params] - - def escape(string): - return string.replace('"', '\\"').replace(r'\n', r'\\n') - - def join(): - return ', '.join(filter(None, (left, center, right))) - - def too_long(): - return len(join()) > max_msg_len - - if len(signatures) > 1: - params = zip_longest(*map(get_params, signatures), fillvalue='_') - params = ['(' + ', '.join(p) + ')' for p in params] - else: - params = get_params(signatures[0]) - - index = next(iter(s.index for s in signatures if s.index is not None), None) - - # Allow 12 characters for showcmd plus 18 for ruler - setting - # noruler/noshowcmd here causes incorrect undo history - max_msg_len = int(vim_eval('&columns')) - 12 - if int(vim_eval('&ruler')): - max_msg_len -= 18 - max_msg_len -= len(signatures[0].call_name) + 2 # call name + parentheses - - if max_msg_len < (1 if params else 0): - return - elif index is None: - text = escape(', '.join(params)) - if params and len(text) > max_msg_len: - text = ELLIPSIS - elif max_msg_len < len(ELLIPSIS): - return - else: - left = escape(', '.join(params[:index])) - center = escape(params[index]) - right = escape(', '.join(params[index + 1:])) - while too_long(): - if left and left != ELLIPSIS: - left = ELLIPSIS - continue - if right and right != ELLIPSIS: - right = ELLIPSIS - continue - if (left or right) and center != ELLIPSIS: - left = right = None - center = ELLIPSIS - continue - if too_long(): - # Should never reach here - return - - max_num_spaces = max_msg_len - if index is not None: - max_num_spaces -= len(join()) - _, column = signatures[0].bracket_start - spaces = min(int(vim_eval('g:jedi#first_col +' - 'wincol() - col(".")')) + - column - len(signatures[0].call_name), - max_num_spaces) * ' ' - - if index is not None: - vim_command(' echon "%s" | ' - 'echohl Function | echon "%s" | ' - 'echohl None | echon "(" | ' - 'echohl jediFunction | echon "%s" | ' - 'echohl jediFat | echon "%s" | ' - 'echohl jediFunction | echon "%s" | ' - 'echohl None | echon ")"' - % (spaces, signatures[0].call_name, - left + ', ' if left else '', - center, ', ' + right if right else '')) - else: - vim_command(' echon "%s" | ' - 'echohl Function | echon "%s" | ' - 'echohl None | echon "(%s)"' - % (spaces, signatures[0].call_name, text)) - - -@_check_jedi_availability(show_error=True) -@catch_and_print_exceptions -def rename(): - if not int(vim.eval('a:0')): - # Need to save the cursor position before insert mode - cursor = vim.current.window.cursor - changenr = vim.eval('changenr()') # track undo tree - vim_command('augroup jedi_rename') - vim_command('autocmd InsertLeave call jedi#rename' - '({}, {}, {})'.format(cursor[0], cursor[1], changenr)) - vim_command('augroup END') - - vim_command("let s:jedi_replace_orig = expand('')") - vim_command('normal! diw') - vim_command('startinsert') - - else: - # Remove autocommand. - vim_command('autocmd! jedi_rename InsertLeave') - - args = vim.eval('a:000') - cursor = tuple(int(x) for x in args[:2]) - changenr = args[2] - - # Get replacement, if there is something on the cursor. - # This won't be the case when the user ends insert mode right away, - # and `` would pick up the nearest word instead. - if vim_eval('getline(".")[getpos(".")[2]-1]') != ' ': - replace = vim_eval("expand('')") - else: - replace = None - - vim_command('undo {}'.format(changenr)) - - vim.current.window.cursor = cursor - - if replace: - return do_rename(replace) - - -def rename_visual(): - replace = vim.eval('input("Rename to: ")') - orig = vim.eval('getline(".")[(getpos("\'<")[2]-1):getpos("\'>")[2]]') - do_rename(replace, orig) - - -def do_rename(replace, orig=None): - if not len(replace): - echo_highlight('No rename possible without name.') - return - - if orig is None: - orig = vim_eval('s:jedi_replace_orig') - - # Save original window / tab. - saved_tab = int(vim_eval('tabpagenr()')) - saved_win = int(vim_eval('winnr()')) - - temp_rename = goto(mode="related_name", no_output=True) - # Sort the whole thing reverse (positions at the end of the line - # must be first, because they move the stuff before the position). - temp_rename = sorted(temp_rename, reverse=True, - key=lambda x: (x.module_path, x.line, x.column)) - buffers = set() - for r in temp_rename: - if r.in_builtin_module(): - continue - - if os.path.abspath(vim.current.buffer.name) != r.module_path: - result = new_buffer(r.module_path) - if not result: - echo_highlight("Jedi-vim: failed to create buffer window for {0}!".format(r.module_path)) - continue - - buffers.add(vim.current.buffer.name) - - # Save view. - saved_view = vim_eval('string(winsaveview())') - - # Replace original word. - vim.current.window.cursor = (r.line, r.column) - vim_command('normal! c{0:d}l{1}'.format(len(orig), replace)) - - # Restore view. - vim_command('call winrestview(%s)' % saved_view) - - # Restore previous tab and window. - vim_command('tabnext {0:d}'.format(saved_tab)) - vim_command('{0:d}wincmd w'.format(saved_win)) - - if len(buffers) > 1: - echo_highlight('Jedi did {0:d} renames in {1:d} buffers!'.format( - len(temp_rename), len(buffers))) - else: - echo_highlight('Jedi did {0:d} renames!'.format(len(temp_rename))) - - -@_check_jedi_availability(show_error=True) -@catch_and_print_exceptions -def py_import(): - # args are the same as for the :edit command - args = shsplit(vim.eval('a:args')) - import_path = args.pop() - text = 'import %s' % import_path - scr = jedi.Script(text, 1, len(text), '') - try: - completion = scr.goto_assignments()[0] - except IndexError: - echo_highlight('Cannot find %s in sys.path!' % import_path) - else: - if completion.in_builtin_module(): - echo_highlight('%s is a builtin module.' % import_path) - else: - cmd_args = ' '.join([a.replace(' ', '\\ ') for a in args]) - new_buffer(completion.module_path, cmd_args) - - -@catch_and_print_exceptions -def py_import_completions(): - argl = vim.eval('a:argl') - try: - import jedi - except ImportError: - print('Pyimport completion requires jedi module: https://github.com/davidhalter/jedi') - comps = [] - else: - text = 'import %s' % argl - script = jedi.Script(text, 1, len(text), '') - comps = ['%s%s' % (argl, c.complete) for c in script.completions()] - vim.command("return '%s'" % '\n'.join(comps)) - - -@catch_and_print_exceptions -def new_buffer(path, options='', using_tagstack=False): - # options are what you can to edit the edit options - if int(vim_eval('g:jedi#use_tabs_not_buffers')) == 1: - _tabnew(path, options) - elif not vim_eval('g:jedi#use_splits_not_buffers') in [1, '1']: - user_split_option = vim_eval('g:jedi#use_splits_not_buffers') - split_options = { - 'top': 'topleft split', - 'left': 'topleft vsplit', - 'right': 'botright vsplit', - 'bottom': 'botright split', - 'winwidth': 'vs' - } - if (user_split_option == 'winwidth' and - vim.current.window.width <= 2 * int(vim_eval( - "&textwidth ? &textwidth : 80"))): - split_options['winwidth'] = 'sp' - if user_split_option not in split_options: - print('Unsupported value for g:jedi#use_splits_not_buffers: {0}. ' - 'Valid options are: {1}.'.format( - user_split_option, ', '.join(split_options.keys()))) - else: - vim_command(split_options[user_split_option] + " %s" % escape_file_path(path)) - else: - if int(vim_eval("!&hidden && &modified")) == 1: - if vim_eval("bufname('%')") is None: - echo_highlight('Cannot open a new buffer, use `:set hidden` or save your buffer') - return False - else: - vim_command('w') - if using_tagstack: - return True - vim_command('edit %s %s' % (options, escape_file_path(path))) - # sometimes syntax is being disabled and the filetype not set. - if int(vim_eval('!exists("g:syntax_on")')) == 1: - vim_command('syntax enable') - if int(vim_eval("&filetype != 'python'")) == 1: - vim_command('set filetype=python') - return True - - -@catch_and_print_exceptions -def _tabnew(path, options=''): - """ - Open a file in a new tab or switch to an existing one. - - :param options: `:tabnew` options, read vim help. - """ - path = os.path.abspath(path) - if int(vim_eval('has("gui")')) == 1: - vim_command('tab drop %s %s' % (options, escape_file_path(path))) - return - - for tab_nr in range(int(vim_eval("tabpagenr('$')"))): - for buf_nr in vim_eval("tabpagebuflist(%i + 1)" % tab_nr): - buf_nr = int(buf_nr) - 1 - try: - buf_path = vim.buffers[buf_nr].name - except (LookupError, ValueError): - # Just do good old asking for forgiveness. - # don't know why this happens :-) - pass - else: - if buf_path == path: - # tab exists, just switch to that tab - vim_command('tabfirst | tabnext %i' % (tab_nr + 1)) - # Goto the buffer's window. - vim_command('exec bufwinnr(%i) . " wincmd w"' % (buf_nr + 1)) - break - else: - continue - break - else: - # tab doesn't exist, add a new one. - vim_command('tabnew %s' % escape_file_path(path)) - - -def escape_file_path(path): - return path.replace(' ', r'\ ') - - -def print_to_stdout(level, str_out): - print(str_out) diff --git a/vim-plugins/bundle/jedi-vim/plugin/jedi.vim b/vim-plugins/bundle/jedi-vim/plugin/jedi.vim deleted file mode 100644 index e224014..0000000 --- a/vim-plugins/bundle/jedi-vim/plugin/jedi.vim +++ /dev/null @@ -1,38 +0,0 @@ -"jedi-vim - Omni Completion for python in vim -" Maintainer: David Halter -" -" This part of the software is just the vim interface. The really big deal is -" the Jedi Python library. - -if get(g:, 'jedi#auto_vim_configuration', 1) - " jedi-vim doesn't work in compatible mode (vim script syntax problems) - if &compatible - " vint: -ProhibitSetNoCompatible - set nocompatible - " vint: +ProhibitSetNoCompatible - endif - - " jedi-vim really needs, otherwise jedi-vim cannot start. - filetype plugin on - - " Change completeopt, but only if it has Vim's default value. - let s:save_completeopt=&completeopt - set completeopt& - let s:default_completeopt=&completeopt - let &completeopt=s:save_completeopt - if s:default_completeopt == &completeopt - set completeopt=menuone,longest,preview - endif - - if len(mapcheck('', 'i')) == 0 - inoremap - endif -endif - -" Pyimport command -command! -nargs=1 -complete=custom,jedi#py_import_completions Pyimport :call jedi#py_import() - -command! -nargs=0 -bar JediDebugInfo call jedi#debug_info() -command! -nargs=0 -bang JediClearCache call jedi#clear_cache(0) - -" vim: set et ts=4: diff --git a/vim-plugins/bundle/jedi-vim/pytest.ini b/vim-plugins/bundle/jedi-vim/pytest.ini deleted file mode 100644 index 16700c3..0000000 --- a/vim-plugins/bundle/jedi-vim/pytest.ini +++ /dev/null @@ -1,3 +0,0 @@ -[pytest] -# Ignore all files -norecursedirs = * diff --git a/vim-plugins/bundle/jedi-vim/test/completions.vim b/vim-plugins/bundle/jedi-vim/test/completions.vim deleted file mode 100644 index 60cafbe..0000000 --- a/vim-plugins/bundle/jedi-vim/test/completions.vim +++ /dev/null @@ -1,63 +0,0 @@ -let g:jedi#completions_command = 'X' -source plugin/jedi.vim - -describe 'completions' - before - new - set filetype=python - end - - after - bd! - end - - it 'smart import' - exec "normal ifrom os " - Expect getline('.') == 'from os import ' - end - - it 'no smart import after space' - exec "normal! ifrom os " - exec "normal a " - Expect getline('.') == 'from os ' - end - - it 'import' - " X is the completion command - normal oimporX - Expect getline('.') == 'import' - normal a subproX - Expect getline('.') == 'import subprocess' - end - - it 'exception' - normal oIndentationErrX - Expect getline('.') == 'IndentationError' - normal a().filenaX - Expect getline('.') == 'IndentationError().filename' - end - - it 'dot_open' - normal oraisX ImpXErrX() - Expect getline('.') == 'raise ImportError()' - end - - it 'cycling through entries' - " testing select_first doesn't seem to work in ex mode - execute "normal oraise impX\\\" - Expect getline('.') == 'raise ImportWarning' - let g:jedi#popup_select_first = 0 - execute "normal oraise impX\\\" - Expect getline('.') == 'raise ImportWarning' - let g:jedi#popup_select_first = 1 - - " -longest completes the first one - set completeopt -=longest - execute "normal oraise baseX" - Expect getline('.') == 'raise BaseException' - set completeopt +=longest - - end -end - -" vim: et:ts=4:sw=4 diff --git a/vim-plugins/bundle/jedi-vim/test/completions_disabled.vim b/vim-plugins/bundle/jedi-vim/test/completions_disabled.vim deleted file mode 100644 index 37b7346..0000000 --- a/vim-plugins/bundle/jedi-vim/test/completions_disabled.vim +++ /dev/null @@ -1,21 +0,0 @@ -let g:jedi#completions_command = 'X' -let g:jedi#completions_enabled = 0 -source plugin/jedi.vim - -describe 'completions_disabled' - before - new - set filetype=python - end - - after - bd! - end - - it 'typing' - normal oraise ImportErrX - Expect getline('.') == 'raise ImportErrX' - end -end - -" vim: et:ts=4:sw=4 diff --git a/vim-plugins/bundle/jedi-vim/test/documentation.vim b/vim-plugins/bundle/jedi-vim/test/documentation.vim deleted file mode 100644 index 119e360..0000000 --- a/vim-plugins/bundle/jedi-vim/test/documentation.vim +++ /dev/null @@ -1,31 +0,0 @@ -source plugin/jedi.vim - -describe 'documentation docstrings' - before - set filetype=python - end - - after - bd! - bd! - end - - it 'simple' - put = 'ImportError' - normal GK - Expect bufname('%') == "'__doc__'" - Expect &filetype == 'rst' - let content = join(getline(1,'$'), "\n") - Expect stridx(content, "Import can't find module") > 0 - normal K - Expect bufname('%') == '' - end - - it 'no documentation' - put = 'x = 2' - normal oGK - Expect bufname('%') == '' - end -end - -" vim: et:ts=4:sw=4 diff --git a/vim-plugins/bundle/jedi-vim/test/goto.vim b/vim-plugins/bundle/jedi-vim/test/goto.vim deleted file mode 100644 index b65a1c7..0000000 --- a/vim-plugins/bundle/jedi-vim/test/goto.vim +++ /dev/null @@ -1,217 +0,0 @@ -let mapleader = '\' -source plugin/jedi.vim -source test/utils.vim - -describe 'goto_simple' - before - new " open a new split - set filetype=python - put =[ - \ 'def a(): pass', - \ 'b = a', - \ 'c = b', - \ ] - normal! ggdd - normal! G$ - Expect line('.') == 3 - end - - after - bd! - end - - it 'goto_definitions' - silent normal \d - Expect line('.') == 1 - "Expect col('.') == 5 " not working yet. - end - - it 'goto_assignments' - silent normal \g - Expect line('.') == 2 - Expect col('.') == 1 - - " cursor before `=` means that it stays there. - silent normal \g - Expect line('.') == 2 - Expect col('.') == 1 - - " going to the last line changes it. - normal! $ - silent normal \g - Expect line('.') == 1 - Expect col('.') == 5 - end -end - - -describe 'goto_with_tabs' - before - set filetype=python - let g:jedi#use_tabs_not_buffers = 1 - end - - after - bd! - bd! - end - - it 'follow_import' - put = ['import subprocess', 'subprocess'] - silent normal G\g - Expect getline('.') == 'import subprocess' - Expect line('.') == 2 - Expect col('.') == 8 - - silent normal G\d - Expect CurrentBufferIsModule('subprocess') == 1 - Expect line('.') == 1 - Expect col('.') == 1 - Expect tabpagenr('$') == 2 - Expect winnr('$') == 1 - tabprevious - Expect bufname('%') == '' - end - - it 'multi_definitions' - " This used to behave differently. Now we don't have any real multi - " definitions. - - " put = ['import tokenize'] - " silent normal G$\d - " Expect CurrentBufferIsModule('tokenize') == 1 - " Expect CurrentBufferIsModule('token') == 0 - " execute "normal \" - " Expect tabpagenr('$') == 2 - " Expect winnr('$') == 1 - " Expect CurrentBufferIsModule('token') == 1 - - " bd - " silent normal G$\d - " execute "normal j\" - " Expect tabpagenr('$') == 2 - " Expect winnr('$') == 1 - " Expect CurrentBufferIsModule('tokenize') == 1 - end -end - - -describe 'goto_with_buffers' - before - set filetype=python - let g:jedi#use_tabs_not_buffers = 0 - end - - after - bd! - bd! - set nohidden - end - - it 'no_new_tabs' - put = ['import os'] - normal G$ - call jedi#goto_assignments() - python jedi_vim.goto() - Expect CurrentBufferIsModule('os') == 0 - " Without hidden, it's not possible to open a new buffer, when the old - " one is not saved. - set hidden - call jedi#goto_assignments() - Expect CurrentBufferIsModule('os') == 1 - Expect winnr('$') == 1 - Expect tabpagenr('$') == 1 - Expect line('.') == 1 - Expect col('.') == 1 - end - - it 'multi_definitions' - " set hidden - " put = ['import tokenize'] - " silent normal G$\d - " Expect CurrentBufferIsModule('tokenize') == 0 - " Expect CurrentBufferIsModule('token') == 0 - " execute "normal \" - " Expect tabpagenr('$') == 1 - " Expect winnr('$') == 1 - " Expect CurrentBufferIsModule('token') == 1 - - " bd - " silent normal G$\d - " execute "normal j\" - " Expect tabpagenr('$') == 1 - " Expect winnr('$') == 1 - " Expect CurrentBufferIsModule('tokenize') == 1 - end -end - - - -describe 'goto_with_splits' - before - set filetype=python - let g:jedi#use_splits_not_buffers = 'left' - end - - after - bd! - bd! - end - - it 'follow_import' - put = ['import subprocess', 'subprocess'] - silent normal G\g - Expect getline('.') == 'import subprocess' - Expect line('.') == 2 - Expect col('.') == 8 - - silent normal G\d - Expect CurrentBufferIsModule('subprocess') == 1 - Expect line('.') == 1 - Expect col('.') == 1 - Expect winnr('$') == 2 - wincmd l - Expect bufname('%') == '' - end - -end - - -describe 'goto_wildignore' - before - set filetype=python - set wildignore=*,with\ spaces,*.pyc - set hidden - let g:jedi#use_tag_stack = 1 - let g:jedi#use_tabs_not_buffers = 0 - " Need to use splits for code coverage in new_buffer() - let g:jedi#use_splits_not_buffers = 1 - - put = ['from subprocess import Popen', 'Popen'] - Expect CurrentBufferIsModule('subprocess') == 0 - silent normal G - end - - after - bd! - bd! - set wildignore&vim - end - - it 'restores_wildignore' - let before = &wildignore - call jedi#goto() - Expect getline('.') =~ 'Popen' - Expect &wildignore == before - end - - it 'not_using_tagstack' - let g:jedi#use_tag_stack = 0 - call jedi#goto() - Expect CurrentBufferIsModule('subprocess') == 1 - Expect getline('.') =~ 'Popen' - end -end - - -" vim: et:ts=4:sw=4 diff --git a/vim-plugins/bundle/jedi-vim/test/pyimport.vim b/vim-plugins/bundle/jedi-vim/test/pyimport.vim deleted file mode 100644 index 098113c..0000000 --- a/vim-plugins/bundle/jedi-vim/test/pyimport.vim +++ /dev/null @@ -1,32 +0,0 @@ -source plugin/jedi.vim -source test/utils.vim - -describe 'pyimport' - before - let g:jedi#use_tabs_not_buffers = 1 - end - - after - bd! - bd! - end - - it 'open_tab' - Pyimport os - Expect CurrentBufferIsModule('os') == 1 - Pyimport subprocess - Expect CurrentBufferIsModule('subprocess') == 1 - " the empty tab is sometimes also a tab - Expect tabpagenr('$') >= 2 - end - - it 'completion' - " don't know how to test this directly - "execute "Pyimport subproc\" - "Expect CurrentBufferIsModule('subprocess') == 1 - - Expect jedi#py_import_completions('subproc', 0, 0) == 'subprocess' - Expect jedi#py_import_completions('subprocess', 0, 0) == 'subprocess' - Expect jedi#py_import_completions('zip', 0, 0) == "zipfile\nzipimport" - end -end diff --git a/vim-plugins/bundle/jedi-vim/test/signatures.vim b/vim-plugins/bundle/jedi-vim/test/signatures.vim deleted file mode 100644 index c1525f6..0000000 --- a/vim-plugins/bundle/jedi-vim/test/signatures.vim +++ /dev/null @@ -1,130 +0,0 @@ -source plugin/jedi.vim - -describe 'signatures' - before - set filetype=python - end - - after - bd! - bd! - end - - it 'simple' - normal oabs( - " equals doautocmd CursorMovedI - Python jedi_vim.show_call_signatures() - - Expect getline(1) == '=`=jedi=0, =`= (*_*number*_*) =`=jedi=`=' - - doautocmd InsertLeave - Expect getline(1) == '' - end - - it 'multiple buffers' - set hidden - new - setfiletype python - redir => autocmds - autocmd jedi_call_signatures * - redir END - Expect autocmds =~# 'jedi_call_signatures' - buffer # - redir => autocmds - autocmd jedi_call_signatures * - redir END - Expect autocmds =~# 'jedi_call_signatures' - bd! - end - - it 'simple after CursorHoldI with only parenthesis' - noautocmd normal o - doautocmd CursorHoldI - noautocmd normal iabs( - doautocmd CursorHoldI - Expect getline(1) == '=`=jedi=0, =`= (*_*number*_*) =`=jedi=`=' - end - - it 'no signature' - normal ostr - Python jedi_vim.show_call_signatures() - Expect getline(1, '$') == ['', 'str '] - end - - it 'signatures disabled' - let g:jedi#show_call_signatures = 0 - - normal ostr( - Python jedi_vim.show_call_signatures() - Expect getline(1, '$') == ['', 'str( '] - - let g:jedi#show_call_signatures = 1 - end - - it 'command line simple' - let g:jedi#show_call_signatures = 2 - call jedi#configure_call_signatures() - - normal oabs( - redir => msg - Python jedi_vim.show_call_signatures() - redir END - Expect msg == "\nabs(number)" - - redir => msg - doautocmd InsertLeave - redir END - Expect msg == "\n" - - normal Sdef foo(a, b): pass - normal ofoo(a, b, c, - redir => msg - Python jedi_vim.show_call_signatures() - redir END - Expect msg == "\nfoo(a, b)" - end - - it 'command line truncation' - let g:jedi#show_call_signatures = 2 - call jedi#configure_call_signatures() - - function! Signature() - redir => msg - Python jedi_vim.show_call_signatures() - redir END - return msg - endfunction - - let funcname = repeat('a', &columns - 30) - put = 'def '.funcname.'(arg1, arg2, arg3, a, b, c):' - put = ' pass' - execute "normal o".funcname."( " - Expect Signature() == "\n".funcname."(arg1, …)" - - normal sarg1, - Expect Signature() == "\n".funcname."(…, arg2, …)" - - normal sarg2, arg3, - Expect Signature() == "\n".funcname."(…, a, b, c)" - - normal sa, b, - Expect Signature() == "\n".funcname."(…, c)" - - g/^/d - put = 'def '.funcname.'('.repeat('b', 20).', arg2):' - put = ' pass' - execute "normal o".funcname."( " - Expect Signature() == "\n".funcname."(…)" - end - - it 'command line no signature' - let g:jedi#show_call_signatures = 2 - call jedi#configure_call_signatures() - - normal ostr - redir => msg - Python jedi_vim.show_call_signatures() - redir END - Expect msg == "\n" - end -end diff --git a/vim-plugins/bundle/jedi-vim/test/utils.vim b/vim-plugins/bundle/jedi-vim/test/utils.vim deleted file mode 100644 index 5ad2a1d..0000000 --- a/vim-plugins/bundle/jedi-vim/test/utils.vim +++ /dev/null @@ -1,11 +0,0 @@ -function! CurrentBufferIsModule(module_name) - return EndsWith(bufname('%'), a:module_name.'.py') -endfunction - - -function EndsWith(string, end) - let l:should = len(a:string) - strlen(a:end) - return l:should == stridx(a:string, a:end, should) -endfunction - -" vim: et:ts=4:sw=4 diff --git a/vim-plugins/bundle/jedi-vim/test_integration.py b/vim-plugins/bundle/jedi-vim/test_integration.py deleted file mode 100644 index d47e06b..0000000 --- a/vim-plugins/bundle/jedi-vim/test_integration.py +++ /dev/null @@ -1,2 +0,0 @@ -def test_integration(case, monkeypatch, pytestconfig): - case.run() diff --git a/vim-plugins/bundle/python-mode/pymode/__pycache__/rope.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/__pycache__/rope.cpython-36.pyc new file mode 100644 index 0000000..cb4994b Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/__pycache__/rope.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/__pycache__/__init__.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/__pycache__/__init__.cpython-36.pyc new file mode 100644 index 0000000..8cef527 Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/__pycache__/__init__.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/__init__.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/__init__.cpython-36.pyc new file mode 100644 index 0000000..d7d82b1 Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/__init__.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/arguments.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/arguments.cpython-36.pyc new file mode 100644 index 0000000..c5ac833 Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/arguments.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/ast.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/ast.cpython-36.pyc new file mode 100644 index 0000000..1f341c7 Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/ast.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/astutils.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/astutils.cpython-36.pyc new file mode 100644 index 0000000..07ddb89 Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/astutils.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/builtins.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/builtins.cpython-36.pyc new file mode 100644 index 0000000..bec071b Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/builtins.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/change.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/change.cpython-36.pyc new file mode 100644 index 0000000..3d6a604 Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/change.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/codeanalyze.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/codeanalyze.cpython-36.pyc new file mode 100644 index 0000000..7988210 Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/codeanalyze.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/default_config.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/default_config.cpython-36.pyc new file mode 100644 index 0000000..5e307b9 Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/default_config.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/evaluate.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/evaluate.cpython-36.pyc new file mode 100644 index 0000000..c915d1a Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/evaluate.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/exceptions.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/exceptions.cpython-36.pyc new file mode 100644 index 0000000..dd853a2 Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/exceptions.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/fscommands.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/fscommands.cpython-36.pyc new file mode 100644 index 0000000..cd8e1a7 Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/fscommands.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/history.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/history.cpython-36.pyc new file mode 100644 index 0000000..c442edf Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/history.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/libutils.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/libutils.cpython-36.pyc new file mode 100644 index 0000000..6e44c8b Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/libutils.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/prefs.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/prefs.cpython-36.pyc new file mode 100644 index 0000000..1a8ca72 Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/prefs.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/project.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/project.cpython-36.pyc new file mode 100644 index 0000000..1c8c8e5 Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/project.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/pycore.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/pycore.cpython-36.pyc new file mode 100644 index 0000000..2ab89b7 Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/pycore.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/pynames.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/pynames.cpython-36.pyc new file mode 100644 index 0000000..776e419 Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/pynames.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/pynamesdef.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/pynamesdef.cpython-36.pyc new file mode 100644 index 0000000..b1f4170 Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/pynamesdef.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/pyobjects.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/pyobjects.cpython-36.pyc new file mode 100644 index 0000000..b7cc522 Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/pyobjects.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/pyobjectsdef.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/pyobjectsdef.cpython-36.pyc new file mode 100644 index 0000000..b0aac48 Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/pyobjectsdef.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/pyscopes.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/pyscopes.cpython-36.pyc new file mode 100644 index 0000000..4730489 Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/pyscopes.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/resourceobserver.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/resourceobserver.cpython-36.pyc new file mode 100644 index 0000000..89aad9f Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/resourceobserver.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/resources.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/resources.cpython-36.pyc new file mode 100644 index 0000000..e28dd7f Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/resources.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/simplify.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/simplify.cpython-36.pyc new file mode 100644 index 0000000..e4ef96c Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/simplify.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/stdmods.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/stdmods.cpython-36.pyc new file mode 100644 index 0000000..2fee189 Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/stdmods.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/taskhandle.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/taskhandle.cpython-36.pyc new file mode 100644 index 0000000..88c7598 Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/taskhandle.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/worder.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/worder.cpython-36.pyc new file mode 100644 index 0000000..4fdc9c6 Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/__pycache__/worder.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/base/oi/__pycache__/__init__.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/oi/__pycache__/__init__.cpython-36.pyc new file mode 100644 index 0000000..30b29ac Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/oi/__pycache__/__init__.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/base/oi/__pycache__/doa.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/oi/__pycache__/doa.cpython-36.pyc new file mode 100644 index 0000000..bde7bcc Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/oi/__pycache__/doa.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/base/oi/__pycache__/docstrings.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/oi/__pycache__/docstrings.cpython-36.pyc new file mode 100644 index 0000000..fc6abff Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/oi/__pycache__/docstrings.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/base/oi/__pycache__/memorydb.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/oi/__pycache__/memorydb.cpython-36.pyc new file mode 100644 index 0000000..9c45d9e Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/oi/__pycache__/memorydb.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/base/oi/__pycache__/objectdb.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/oi/__pycache__/objectdb.cpython-36.pyc new file mode 100644 index 0000000..cfaaaf2 Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/oi/__pycache__/objectdb.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/base/oi/__pycache__/objectinfo.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/oi/__pycache__/objectinfo.cpython-36.pyc new file mode 100644 index 0000000..931a4b0 Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/oi/__pycache__/objectinfo.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/base/oi/__pycache__/soa.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/oi/__pycache__/soa.cpython-36.pyc new file mode 100644 index 0000000..8ceba88 Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/oi/__pycache__/soa.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/base/oi/__pycache__/soi.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/oi/__pycache__/soi.cpython-36.pyc new file mode 100644 index 0000000..8b3bf66 Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/oi/__pycache__/soi.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/base/oi/__pycache__/transform.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/oi/__pycache__/transform.cpython-36.pyc new file mode 100644 index 0000000..01fdc61 Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/oi/__pycache__/transform.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/base/utils/__pycache__/__init__.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/utils/__pycache__/__init__.cpython-36.pyc new file mode 100644 index 0000000..260fd56 Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/utils/__pycache__/__init__.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/base/utils/__pycache__/datastructures.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/utils/__pycache__/datastructures.cpython-36.pyc new file mode 100644 index 0000000..fa73301 Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/utils/__pycache__/datastructures.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/base/utils/__pycache__/pycompat.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/utils/__pycache__/pycompat.cpython-36.pyc new file mode 100644 index 0000000..4446a85 Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/base/utils/__pycache__/pycompat.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/contrib/__pycache__/__init__.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/contrib/__pycache__/__init__.cpython-36.pyc new file mode 100644 index 0000000..063b247 Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/contrib/__pycache__/__init__.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/contrib/__pycache__/autoimport.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/contrib/__pycache__/autoimport.cpython-36.pyc new file mode 100644 index 0000000..736337a Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/contrib/__pycache__/autoimport.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/contrib/__pycache__/codeassist.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/contrib/__pycache__/codeassist.cpython-36.pyc new file mode 100644 index 0000000..522f34d Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/contrib/__pycache__/codeassist.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/contrib/__pycache__/findit.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/contrib/__pycache__/findit.cpython-36.pyc new file mode 100644 index 0000000..b1d50cb Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/contrib/__pycache__/findit.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/contrib/__pycache__/fixsyntax.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/contrib/__pycache__/fixsyntax.cpython-36.pyc new file mode 100644 index 0000000..ad78813 Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/contrib/__pycache__/fixsyntax.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/contrib/__pycache__/generate.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/contrib/__pycache__/generate.cpython-36.pyc new file mode 100644 index 0000000..9564e2e Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/contrib/__pycache__/generate.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/__pycache__/__init__.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/__pycache__/__init__.cpython-36.pyc new file mode 100644 index 0000000..a86ca5a Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/__pycache__/__init__.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/__pycache__/change_signature.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/__pycache__/change_signature.cpython-36.pyc new file mode 100644 index 0000000..d27c8e7 Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/__pycache__/change_signature.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/__pycache__/extract.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/__pycache__/extract.cpython-36.pyc new file mode 100644 index 0000000..23807f0 Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/__pycache__/extract.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/__pycache__/functionutils.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/__pycache__/functionutils.cpython-36.pyc new file mode 100644 index 0000000..3c75a18 Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/__pycache__/functionutils.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/__pycache__/inline.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/__pycache__/inline.cpython-36.pyc new file mode 100644 index 0000000..eed2ae6 Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/__pycache__/inline.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/__pycache__/move.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/__pycache__/move.cpython-36.pyc new file mode 100644 index 0000000..337e5c0 Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/__pycache__/move.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/__pycache__/occurrences.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/__pycache__/occurrences.cpython-36.pyc new file mode 100644 index 0000000..4a85729 Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/__pycache__/occurrences.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/__pycache__/patchedast.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/__pycache__/patchedast.cpython-36.pyc new file mode 100644 index 0000000..a0f376d Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/__pycache__/patchedast.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/__pycache__/rename.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/__pycache__/rename.cpython-36.pyc new file mode 100644 index 0000000..3fd5033 Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/__pycache__/rename.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/__pycache__/restructure.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/__pycache__/restructure.cpython-36.pyc new file mode 100644 index 0000000..7bbae9f Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/__pycache__/restructure.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/__pycache__/similarfinder.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/__pycache__/similarfinder.cpython-36.pyc new file mode 100644 index 0000000..c4b21de Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/__pycache__/similarfinder.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/__pycache__/sourceutils.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/__pycache__/sourceutils.cpython-36.pyc new file mode 100644 index 0000000..b65b0de Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/__pycache__/sourceutils.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/__pycache__/suites.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/__pycache__/suites.cpython-36.pyc new file mode 100644 index 0000000..827efdd Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/__pycache__/suites.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/__pycache__/topackage.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/__pycache__/topackage.cpython-36.pyc new file mode 100644 index 0000000..c9d8bea Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/__pycache__/topackage.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/__pycache__/usefunction.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/__pycache__/usefunction.cpython-36.pyc new file mode 100644 index 0000000..598618e Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/__pycache__/usefunction.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/__pycache__/wildcards.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/__pycache__/wildcards.cpython-36.pyc new file mode 100644 index 0000000..4c36625 Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/__pycache__/wildcards.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/importutils/__pycache__/__init__.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/importutils/__pycache__/__init__.cpython-36.pyc new file mode 100644 index 0000000..553e2a0 Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/importutils/__pycache__/__init__.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/importutils/__pycache__/actions.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/importutils/__pycache__/actions.cpython-36.pyc new file mode 100644 index 0000000..b1aa9d3 Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/importutils/__pycache__/actions.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/importutils/__pycache__/importinfo.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/importutils/__pycache__/importinfo.cpython-36.pyc new file mode 100644 index 0000000..9226474 Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/importutils/__pycache__/importinfo.cpython-36.pyc differ diff --git a/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/importutils/__pycache__/module_imports.cpython-36.pyc b/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/importutils/__pycache__/module_imports.cpython-36.pyc new file mode 100644 index 0000000..d351621 Binary files /dev/null and b/vim-plugins/bundle/python-mode/pymode/libs/rope/refactor/importutils/__pycache__/module_imports.cpython-36.pyc differ diff --git a/vim-plugins/bundle/vim-lion/README.md b/vim-plugins/temp-unloaded-plugins/vim-lion/README.md similarity index 100% rename from vim-plugins/bundle/vim-lion/README.md rename to vim-plugins/temp-unloaded-plugins/vim-lion/README.md diff --git a/vim-plugins/bundle/vim-lion/doc/lion.txt b/vim-plugins/temp-unloaded-plugins/vim-lion/doc/lion.txt similarity index 100% rename from vim-plugins/bundle/vim-lion/doc/lion.txt rename to vim-plugins/temp-unloaded-plugins/vim-lion/doc/lion.txt diff --git a/vim-plugins/bundle/vim-lion/doc/tags b/vim-plugins/temp-unloaded-plugins/vim-lion/doc/tags similarity index 100% rename from vim-plugins/bundle/vim-lion/doc/tags rename to vim-plugins/temp-unloaded-plugins/vim-lion/doc/tags diff --git a/vim-plugins/bundle/vim-lion/plugin/lion.vim b/vim-plugins/temp-unloaded-plugins/vim-lion/plugin/lion.vim similarity index 100% rename from vim-plugins/bundle/vim-lion/plugin/lion.vim rename to vim-plugins/temp-unloaded-plugins/vim-lion/plugin/lion.vim