├── .gitignore ├── .gitmodules ├── .travis.yml ├── AUTHORS.txt ├── CHANGELOG.md ├── LICENSE.txt ├── README.md ├── _version.py ├── appveyor.yml ├── data └── test │ └── pkg │ ├── __init__.py │ └── mod.py ├── dependencies └── pyinstaller │ └── 3.4 │ └── bootloader │ └── Windows-32bit │ ├── run.exe │ ├── run_d.exe │ ├── runw.exe │ └── runw_d.exe ├── freezing.spec ├── images └── readme │ ├── class_members.png │ ├── field_references.png │ ├── fill_custom_sourcegroup.png │ ├── function_calls.png │ ├── local_symbols.png │ └── pick_custom_sourcegroup.png ├── indexer.py ├── requirements.txt ├── run.py ├── shallow_indexer.py ├── test.py └── test_shallow.py /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__ 2 | .vscode 3 | build 4 | dist 5 | 6 | /_sourcetraildb.pyd 7 | /sourcetraildb.py -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "SourcetrailDB"] 2 | path = SourcetrailDB 3 | url = https://github.com/CoatiSoftware/SourcetrailDB.git 4 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: cpp 2 | 3 | 4 | matrix: 5 | include: 6 | - os: linux 7 | sudo: required 8 | compiler: gcc 9 | dist: bionic 10 | addons: 11 | apt: 12 | sources: 13 | - ubuntu-toolchain-r-test 14 | packages: 15 | - g++-5 16 | env: 17 | - CC_COMPILER=gcc-5 CXX_COMPILER=g++-5 PYTHON=3.6 18 | 19 | - os: osx 20 | compiler: clang 21 | env: 22 | - PYTHON=3.6 23 | 24 | 25 | before_install: 26 | - | 27 | if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then 28 | HOMEBREW_NO_AUTO_UPDATE=1 brew install swig 29 | brew link --force swig 30 | elif [[ "$TRAVIS_OS_NAME" == "linux" ]]; then 31 | pyenv shell 3.6 32 | sudo apt-get update 33 | sudo apt-get install -qq swig 34 | fi 35 | 36 | 37 | install: 38 | - if [[ "${CXX_COMPILER}" != "" ]]; then export CXX=${CXX_COMPILER}; export CXX_FOR_BUILD=${CXX_COMPILER}; fi 39 | - if [[ "${CC_COMPILER}" != "" ]]; then export CC=${CC_COMPILER}; export CC_FOR_BUILD=${CC_COMPILER}; fi 40 | - pip3 install -r requirements.txt 41 | 42 | 43 | script: 44 | - | 45 | PACKAGE_VERSION=$(python3 -c "from _version import __version__; print(__version__.replace('.', '_'))") 46 | export PACKAGE_NAME="SourcetrailPythonIndexer_${PACKAGE_VERSION}-${TRAVIS_OS_NAME}" 47 | - echo ${PACKAGE_NAME} 48 | - git submodule init 49 | - git submodule update 50 | - cd SourcetrailDB 51 | - mkdir build 52 | - cd build 53 | - cmake -DBUILD_BINDINGS_PYTHON=1 -DPYTHON_VERSION=$PYTHON .. 54 | - make 55 | - cd ../.. 56 | - cp SourcetrailDB/build/bindings_python/sourcetraildb.py . 57 | - cp SourcetrailDB/build/bindings_python/_sourcetraildb* _sourcetraildb.so 58 | - pyinstaller freezing.spec 59 | - python3 test.py 60 | - python3 test_shallow.py 61 | 62 | 63 | before_deploy: 64 | - cd $TRAVIS_BUILD_DIR/dist 65 | - mv SourcetrailPythonIndexer ${PACKAGE_NAME} 66 | - mkdir -p ${PACKAGE_NAME}/license/3rd_party_licenses 67 | - cp ../LICENSE.txt ${PACKAGE_NAME}/license/ 68 | - cp ../SourcetrailDB/LICENSE.txt ${PACKAGE_NAME}/license/3rd_party_licenses/license_sourcetraildb.txt 69 | - cp ../SourcetrailDB/external/cpp_sqlite/license_cpp_sqlite.txt ${PACKAGE_NAME}/license/3rd_party_licenses/ 70 | - cp ../SourcetrailDB/external/json/license_json.txt ${PACKAGE_NAME}/license/3rd_party_licenses/ 71 | - zip -r ${PACKAGE_NAME} ${PACKAGE_NAME} 72 | 73 | 74 | deploy: 75 | provider: releases 76 | api_key: 77 | secure: aCJiSdJhxayw/dp8OecP+r3PGVRbHHO/UOoM1X2KzP05fHGvXB3jhWIYCefyVMe6hp1xHjM5aYUOejp+25CEl6xOjRZpLJqkAmdIcBls0nRvmseQNzEY1iIRPogfg2isGsCZG66IkLQuU9/CjiJJz8t5/wMopawbkjD9NDg1I5dXONglNz59h8SPgZvWc4YHrn0PyxE1lSihlNBmGXu3RX1MI40jTUNNy3hByFukAArJAiCNdD96BL1JKeMOFjTob0DjdGN7LHkB26hrcXR4/oNOr2sZW+bELn8vL59YOpJVtMDkBajL21KQ4b9kiGgtbsfLQecF3twHq/MsZIa/oCetRYMyTHW2nNIY0vFPeWwl+HRLEWUl+afpWlRG17ODs9RDxM7CpW3yvVl6bzILiCgBH84e0tbpPsK1Rr7I1ARZgZ7YSJ2moTZMSoo3A1quHRBpxMlGM42ao98HTuT/PQBKxcbol7QkLyPL80IHFDn7ekZKUeVo4e9hT5kNF7aFIDC6KolxitV2ia5dV+yL13JXi4DllotmCXKzDy8dMk4wg9OGFLOSz0S2h97F1r7ajtxxTL02sGysAsLflHT12X53U3nKulWr5Jqm37LfhuIUxEQWKLxvPN5LmCc8+yunSey95sUV3m7cB7n4oHGny1+WBDAotSKdS+ENJdPlEyw= 78 | file_glob: true 79 | file: "$TRAVIS_BUILD_DIR/dist/*.zip" 80 | overwrite: true 81 | skip_cleanup: true 82 | on: 83 | tags: true 84 | repo: CoatiSoftware/SourcetrailPythonIndexer 85 | -------------------------------------------------------------------------------- /AUTHORS.txt: -------------------------------------------------------------------------------- 1 | Main Authors 2 | ============ 3 | 4 | Malte Langkabel (@mlangkabel) 5 | 6 | Code Contributors 7 | ================= 8 | 9 | 10 | 11 | Note: (@user) means a github user name. 12 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | 4 | ## v1.db25.p6 5 | 6 | **2021-03-08** 7 | 8 | * Updated SourcetrailDB dependency to v4.db25.p1 to fix Sourcetrail indexer crash when indexed file used a single "\r" to end a line. 9 | 10 | 11 | ## v1.db25.p5 12 | 13 | **2020-09-14** 14 | 15 | * Removed usage of Python 2 as host environment for running the Python indexer. 16 | * Updated dependencies to jedi 0.17.2. 17 | * Updated to pyinstaller 3.6 to address a security issue pointed out by GitHub. 18 | 19 | 20 | ## v1.db25.p4 21 | 22 | **2020-06-08** 23 | 24 | * Implemented recording "override" edges that point from a method of a class to the overridden method in the class' base class. 25 | * Implemented fallback to derive source file encoding automatically if utf-8 does not work. 26 | * Updated dependencies to parso 0.7.0. 27 | 28 | 29 | ## v1.db25.p3 30 | 31 | **2020-02-24** 32 | 33 | * Updated dependencies to jedi 0.16.0 and parso 0.6.1. 34 | 35 | 36 | ## v1.db25.p2 37 | 38 | **2019-12-10** 39 | 40 | * Fixed an issue that caused the Python indexer to ignore a valid Python environment where the python.exe is located in the root directory on Winodws. 41 | 42 | 43 | ## v1.db25.p1 44 | 45 | **2019-11-26** 46 | 47 | * Switched form Apache License to GNU GENERAL PUBLIC LICENSE. 48 | * Allow to use "unsafe" Python environment if this environment has explicitly been specified by the user. 49 | 50 | 51 | ## v1.db25.p0 52 | 53 | **2019-11-05** 54 | 55 | * Added shallow indexer that is less precide than the normal indexer but much faster. This mode can be invoked by adding the `--shallow` command line argument. 56 | 57 | 58 | ## v1.db24.p2 59 | 60 | **2019-08-26** 61 | 62 | * Implemented recording a reference to the __init__() method of a class for locations where a class object is initialized (issue #49) 63 | * Fixed issue where some virus scanners had a false positive detection for the SourcetrailPythonIndexer (issue #48) 64 | * Updated to jedi 0.15.0 65 | * Fixed crash when looking up names for some builtin symbols 66 | 67 | 68 | ## v1.db24.p1 69 | 70 | **2019-08-06** 71 | 72 | * Updated to jedi 0.14.1 and parso 0.5.1 to fix issues #26, #28 and #30 73 | * Fixed opening and reading source files when using Python 2 74 | 75 | 76 | ## v1.db24.p0 77 | 78 | **2019-05-28** 79 | 80 | * Changed commandline api by moving the current main functionality of indexing a source file to the "index" command 81 | * Added new "check-environment" command that can be used to check whether a given Python environment will be usable by the indexer 82 | 83 | 84 | ## v0.db24.p1 85 | 86 | **2019-05-21** 87 | 88 | * Added exception handling for accessing jedi definition, so that these exceptions only cause one symbol to be unsolved and the rest of the file will still be indexed 89 | * Switched to reading source code using UTF-8 encoding by default 90 | 91 | 92 | ## v0.db24.p0 93 | 94 | **2019-05-20** 95 | 96 | * Updated to Sourcetrail database format version 24 97 | * Implemented recording unsolved symbol locations as "unsolved", so they can be displayed as such by Sourcetrail 98 | * Implemented allowing to record multiple references for one source location (e.g. when different code paths result in different functions being called) 99 | * Implemented printing of detailed error if provided python environment is invalid 100 | * Fixed an issue where global symbols defined in iterable argument are recorded as child of "unsolved symbol" (issue #40) 101 | 102 | 103 | ## v0.db23.p4 104 | 105 | **2019-04-23** 106 | 107 | * Added support for Python 2 108 | * Implemented recording "unsolved symbol" when an exception occurred during name resolution of a symbol 109 | * Implemented resolving usages of "super()" 110 | * Implemented recording errors if imported symbol has not been found 111 | * Merged multiple definitions of a local symbol 112 | * Fixed some name hierarchy related issues 113 | 114 | 115 | ## v0.db23.p3 116 | 117 | **2019-04-02** 118 | 119 | * Implemented recording global variables 120 | * Implemented recording source locations for import statements (issue #4) 121 | * Implemented recording usages of module names within the sourcecode 122 | * Implemented indexer to prepend package names when solving names of symbols 123 | * Implemented recording qualifier locations that can be clicked within Sourcetrail but won't show up if the qualifying symbol is activated 124 | * Implemented recording "unsolved symbol" nodes if the indexer has not been able to deriva a symbol's definition or name 125 | * Changed handling of local variable definitions so that now a single symbol for all (re-)definitions of the same variable within a scope is recorded 126 | * Improved AST logging in "--verbose" mode by printing value and location of visited nodes 127 | * Improved logging by always prepending severity information 128 | * Changed the CLI by adding an optional "--environment-directory-path" parameter that allows to set the python environment used for resolving dependencies within the indexed code 129 | * Changed the CLI by allowing relative paths for the "--source-file-path" and "--database-file-path" parameters 130 | * Added compatibility check to verify if the currently used version of SourcetrailDB supports everything currently used by SourcetrailPythonIndexer (issue #8) 131 | * Fixed CI pipeline did not fail if tests fail 132 | 133 | 134 | ## v0.db23.p2 135 | 136 | **2019-02-26** 137 | 138 | * Added license info to release packages. 139 | * Implemented recording of references (e.g. calls, usages) of built-in functions and classes. 140 | * Multi-line strings will now be recorded as atomic source ranges, which prevents Sourcetrail from splitting them up in the snippet view. 141 | 142 | 143 | ## v0.db23.p1 144 | 145 | **2019-02-18** 146 | 147 | * Added downloadable all-in-one release packages for Mac and Linux. The Windows release did not change. 148 | 149 | 150 | ## v0.db23.p0 151 | 152 | **2019-02-12** 153 | 154 | * First official release of the SourcetrailDB project. 155 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SourcetrailPythonIndexer 2 | Python Indexer for [Sourcetrail](https://www.sourcetrail.com/) based on [jedi](https://github.com/davidhalter/jedi), [parso](https://github.com/davidhalter/parso) and [SourcetrailDB](https://github.com/CoatiSoftware/SourcetrailDB) 3 | 4 | 5 | ## CI Pipelines 6 | Windows: [![Build status](https://ci.appveyor.com/api/projects/status/4vo082swmhmny1a1/branch/master?svg=true)](https://ci.appveyor.com/project/mlangkabel/sourcetrailpythonindexer/branch/master) 7 | 8 | Linux and macOS: [![Build Status](https://travis-ci.org/CoatiSoftware/SourcetrailPythonIndexer.svg?branch=master)](https://travis-ci.org/CoatiSoftware/SourcetrailPythonIndexer) 9 | 10 | ## Description 11 | The SourcetrailPythonIndexer project is a Sourcetrail language extension that brings Python support to Sourcetrail. This project is still in a prototype state, but you can already run it on your Python code! 12 | 13 | !["find field references"](images/readme/field_references.png "find field references") 14 | 15 | 16 | ## Requirements 17 | * [Python 3](https://www.python.org) 18 | * [jedi 0.17.2](https://pypi.org/project/jedi/0.17.2) 19 | * [parso 0.7.0](https://pypi.org/project/parso/0.7.0) 20 | * [SourcetrailDB](https://github.com/CoatiSoftware/SourcetrailDB) Python bindings 21 | 22 | 23 | ## Setup 24 | * Check out this repository 25 | * Install jedi by running `pip install jedi` 26 | * Download the SourcetrailDB Python bindings for your specific Python version [here](https://github.com/CoatiSoftware/SourcetrailDB/releases) and extract both the `_sourcetraildb.pyd` (`_sourcetraildb.so` on unix) and the `sourcetraildb.py` files to the root of the checked out repository 27 | 28 | 29 | ## Running the Source Code 30 | To index an arbitrary Python source file, execute the command: 31 | 32 | ``` 33 | $ python run.py index --source-file-path=path/to/your/python/file.py --database-file-path=path/to/output/database/file.srctrldb 34 | ``` 35 | 36 | This will index the source file and store the data to the provided database filepath. If the database does not exist, an empty database will be created. 37 | 38 | You can access an overview that lists all available commands by providing the `-h` argument, which will print the following output to your console: 39 | ``` 40 | $ python run.py -h 41 | usage: run.py [-h] [--version] {index,check-environment} ... 42 | 43 | Python source code indexer that generates a Sourcetrail compatible database. 44 | 45 | optional arguments: 46 | -h, --help show this help message and exit 47 | --version show program's version number and exit 48 | 49 | commands: 50 | {index,check-environment} 51 | index Index a Python source file and store the indexed data 52 | to a Sourcetrail database file. Run "index -h" for 53 | more info on available arguments. 54 | check-environment Check if the provided path specifies a valid Python 55 | environment. This command exits with code "0" if a 56 | valid Python environment has been provided, otherwise 57 | code "1" is returned. Run "check-environment -h" for 58 | more info on available arguments. 59 | ``` 60 | 61 | You can also view a detailed summary of all available arguments for the `index` command by providing the `-h` argument here. This will print the following output to your console: 62 | ``` 63 | $ python run.py index -h 64 | usage: run.py index [-h] --source-file-path SOURCE_FILE_PATH 65 | --database-file-path DATABASE_FILE_PATH 66 | [--environment-path ENVIRONMENT_PATH] [--clear] 67 | [--verbose] [--shallow] 68 | 69 | optional arguments: 70 | -h, --help show this help message and exit 71 | --source-file-path SOURCE_FILE_PATH 72 | path to the source file to index 73 | --database-file-path DATABASE_FILE_PATH 74 | path to the generated Sourcetrail database file 75 | --environment-path ENVIRONMENT_PATH 76 | path to the Python executable or the directory that 77 | contains the Python environment that should be used to 78 | resolve dependencies within the indexed source code 79 | (if not specified the path to the currently used 80 | interpreter is used) 81 | --clear clear the database before indexing 82 | --verbose enable verbose console output 83 | --shallow use a quick indexing mode that matches references by 84 | name and ignores most of the context 85 | ``` 86 | 87 | 88 | ## Running the Release 89 | 90 | The availble [release packages](https://github.com/CoatiSoftware/SourcetrailPythonIndexer/releases) already contain a functional Python enviroment and all the dependencies. To index an arbitrary Python source file just execute the command: 91 | 92 | ``` 93 | $ path/to/SourcetrailPythonIndexer index --source-file-path=path/to/your/python/file.py --database-file-path=path/to/output/database/file.srctrldb 94 | ``` 95 | 96 | 97 | ## Executing the Tests 98 | To run the tests for this project, execute the command: 99 | ``` 100 | $ python test.py 101 | $ python test_shallow.py 102 | ``` 103 | 104 | 105 | ## Contributing 106 | If you like this project and want to get involved, there are lots of ways you can help: 107 | 108 | * __Spread the word.__ The more people want this project to grow, the greater the motivation for the developers to get things done. 109 | * __Test the indexer.__ Run it on your own source code. There are still things that are not handled at all or edge cases that have not been considered yet. If you find anything, just create an issue here. Best, include some sample code snippet that illustrates the issue, so we can use it as a basis to craft a test case for our continuous integration and no one will ever break that case again. 110 | * __Write some code.__ Don't be shy here. You can implement whole new features or fix some bugs, but you can also do some refactoring if you think that it benefits the readability or the maintainability of the code. Still, no matter if you just want to work on cosmetics or implement new features, it would be best if you create an issue here on the issue tracker before you actually start handing in pull requests, so that we can discuss those changes first and thus raise the probability that those changes will get pulled quickly. 111 | 112 | To create a pull request, follow these steps: 113 | * Fork the Repo on GitHub. 114 | * Make your commits. 115 | * If you added functionality or fixed a bug, please add a test. 116 | * Add your name to the "Code Contributors" section in AUTHORS.txt file. 117 | * Push to your fork and submit a pull request. 118 | 119 | 120 | ## Sourcetrail Integration 121 | To run the lastest release of the Python indexer from within your Sourcetrail installation, follow these steps: 122 | * download the latest [Release](https://github.com/CoatiSoftware/SourcetrailPythonIndexer/releases) for your OS and extract the package to a directory of your choice 123 | * make sure that you are running Sourcetrail 2018.4.45 or a later version 124 | * add a new "Custom Command Source Group" to a new or to an existing Sourcetrail project 125 | * paste the following string into the source group's "Custom Command" field: `path/to/SourcetrailPythonIndexer index --source-file-path=%{SOURCE_FILE_PATH} --database-file-path=%{DATABASE_FILE_PATH}` 126 | * add your Python files (or the folders that contain those files) to the "Files & Directories to Index" list 127 | * add a ".py" entry to the "Source File Extensions" list (including the dot) 128 | * confirm the settings and start the indexing process 129 | 130 | !["pick custom sourcegroup"](images/readme/pick_custom_sourcegroup.png "pick custom sourcegroup")!["fill custom sourcegroup"](images/readme/fill_custom_sourcegroup.png "fill custom sourcegroup") 131 | 132 | 133 | ## Features 134 | 135 | !["view class members"](images/readme/class_members.png "view class members") 136 | 137 | View a class' internal structure to find out which member functions and variables are available and where they are defined. 138 | 139 |
140 | 141 | !["find field references"](images/readme/field_references.png "find field references") 142 | 143 | Find out where a member variable is actually coming from and where it is accessed. 144 | 145 |
146 | 147 | !["inspect function calls"](images/readme/function_calls.png "inspect function calls") 148 | 149 | Inspect call sites of functions all accross the code base. 150 | 151 |
152 | 153 | !["view local variable usages"](images/readme/local_symbols.png "view local variable usages") 154 | 155 | View the definitions of local variables and their usages (note that the definition of `bar` in the `else` branch is not highlighted). 156 | -------------------------------------------------------------------------------- /_version.py: -------------------------------------------------------------------------------- 1 | __version__ = 'v1.db25.p6' 2 | 3 | _sourcetrail_db_version = 'v4.db25.p1' 4 | -------------------------------------------------------------------------------- /appveyor.yml: -------------------------------------------------------------------------------- 1 | version: 0.0.0.{build} 2 | image: Visual Studio 2017 3 | 4 | 5 | environment: 6 | matrix: 7 | - MBITS: 32 8 | PYTHON_VERSION: 37 9 | MSVC_VERSION: 15 10 | DEPLOY: 1 11 | 12 | 13 | install: 14 | # configure variables 15 | - ps: | 16 | if ($env:MBITS -eq "32") { 17 | echo "Architecture set to 32 bit." 18 | $env:PYTHON_PATH="C:/Python$env:PYTHON_VERSION" 19 | $env:CMAKE_GENERATOR="Visual Studio $env:MSVC_VERSION" 20 | } elseif ($env:MBITS -eq "64") { 21 | echo "Architecture set to 64 bit." 22 | $env:PYTHON_PATH="C:/Python$env:PYTHON_VERSION-x64" 23 | $env:CMAKE_GENERATOR="Visual Studio $env:MSVC_VERSION Win64" 24 | } else { 25 | echo "No architecture set. Build will be canceled." 26 | } 27 | - SET PIP_PATH=%PYTHON_PATH%/Scripts 28 | - SET PATH=%PYTHON_PATH%;%PIP_PATH%;%PATH% 29 | # install python dependencies 30 | - cmd: pip install -r requirements.txt 31 | # prepare for SourcetrailDB build 32 | - cmd: git submodule init 33 | - cmd: git submodule update 34 | # Install SWIG by Choco 35 | - ps: choco install -y --no-progress swig --version 4.0.1 36 | 37 | 38 | before_build: 39 | - ps: $env:PACKAGE_VERSION = python -c "from _version import __version__; print(__version__.replace('.', '_'))" 40 | - ps: echo "Package version is $env:PACKAGE_VERSION" 41 | - ps: $env:MAJOR_VERSION = $env:PACKAGE_VERSION.Split("_")[0].TrimStart("v") 42 | - ps: echo "Major version is $env:MAJOR_VERSION" 43 | - ps: $env:DATABASE_VERSION = $env:PACKAGE_VERSION.Split("_")[1].TrimStart("db") 44 | - ps: echo "Database version is $env:DATABASE_VERSION" 45 | - ps: $env:PATCH_VERSION = $env:PACKAGE_VERSION.Split("_")[2].TrimStart("p") 46 | - ps: echo "Patch version is $env:PATCH_VERSION" 47 | - ps: $env:BUILD_VERSION = $env:MAJOR_VERSION + "." + $env:DATABASE_VERSION + "." + $env:PATCH_VERSION + "." + $env:APPVEYOR_BUILD_NUMBER 48 | - ps: echo "update build version to $env:BUILD_VERSION" 49 | - ps: Update-AppveyorBuild -Version $env:BUILD_VERSION 50 | 51 | 52 | build_script: 53 | - cd SourcetrailDB 54 | - mkdir build 55 | - cd build 56 | - cmake -G "%CMAKE_GENERATOR%" ../ -DBUILD_BINDINGS_PYTHON=ON -DPYTHON_LIBRARY="%PYTHON_PATH%/libs/python%PYTHON_VERSION%.lib" 57 | - msbuild /p:configuration=Release /v:m ALL_BUILD.vcxproj 58 | - cd .. 59 | - cd .. 60 | - ps: | 61 | copy SourcetrailDB/build/bindings_python/sourcetraildb.py ./ 62 | copy SourcetrailDB/build/bindings_python/Release/_sourcetraildb.pyd ./ 63 | 64 | 65 | after_build: 66 | - cmd: pyinstaller freezing.spec 67 | - ps: $env:PACKAGE_NAME = 'SourcetrailPythonIndexer_' + $env:PACKAGE_VERSION + '-windows' 68 | - ps: echo $env:PACKAGE_NAME 69 | - mkdir artifacts 70 | - cd artifacts 71 | - mkdir %PACKAGE_NAME% 72 | - cd %PACKAGE_NAME% 73 | - mkdir license 74 | - cd license 75 | - mkdir 3rd_party_licenses 76 | - cd .. 77 | - cd .. 78 | - cd .. 79 | - ps: Copy-Item -Path dist/SourcetrailPythonIndexer/* -Recurse -Destination artifacts/$env:PACKAGE_NAME 80 | - ps: copy LICENSE.txt artifacts/$env:PACKAGE_NAME/license/ 81 | - ps: copy SourcetrailDB/LICENSE.txt artifacts/$env:PACKAGE_NAME/license/3rd_party_licenses/license_sourcetraildb.txt 82 | - ps: copy SourcetrailDB/external/cpp_sqlite/license_cpp_sqlite.txt artifacts/$env:PACKAGE_NAME/license/3rd_party_licenses/ 83 | - ps: copy SourcetrailDB/external/json/license_json.txt artifacts/$env:PACKAGE_NAME/license/3rd_party_licenses/ 84 | - ps: | 85 | $env:ARTIFACTY_TO_DEPLOY = "" 86 | if ($env:DEPLOY -eq "1") { 87 | $env:ARTIFACTY_TO_DEPLOY = $env:PACKAGE_NAME 88 | } 89 | echo $env:ARTIFACTY_TO_DEPLOY 90 | 91 | 92 | test_script: 93 | - cmd: python test.py 94 | - cmd: python test_shallow.py 95 | - ps: $env:SOURCETRAIL_DB_DATABASE_VERSION = python -c "import sourcetraildb; print(sourcetraildb.getSupportedDatabaseVersion())" 96 | - ps: | 97 | if ($env:SOURCETRAIL_DB_DATABASE_VERSION -eq $env:DATABASE_VERSION) { 98 | echo "SourcetrailPythonIndexer matches SourcetrailDB's database version." 99 | } else { 100 | throw "SourcetrailPythonIndexer db version ($env:DATABASE_VERSION) and SourcetrailDB db version ($env:SOURCETRAIL_DB_DATABASE_VERSION) do not match." 101 | } 102 | 103 | 104 | artifacts: 105 | - path: artifacts 106 | name: $(PACKAGE_NAME) 107 | type: Zip 108 | 109 | 110 | deploy: 111 | provider: GitHub 112 | artifact: $(ARTIFACTY_TO_DEPLOY) 113 | auth_token: 114 | secure: MB2DqEW2eCwgCYtz/5BEn18XweV4eU760lzt7zpZ9fGEU5mxxhh79FLzK8Ux++09 115 | on: 116 | appveyor_repo_tag: true 117 | -------------------------------------------------------------------------------- /data/test/pkg/__init__.py: -------------------------------------------------------------------------------- 1 | class PackageLevelClass: 2 | 3 | staticField = 2 4 | 5 | def __init__(self): 6 | self.field = 9 7 | -------------------------------------------------------------------------------- /data/test/pkg/mod.py: -------------------------------------------------------------------------------- 1 | class ModuleLevelClass: 2 | 3 | staticField = 2 4 | 5 | def __init__(self): 6 | self.field = 9 7 | -------------------------------------------------------------------------------- /dependencies/pyinstaller/3.4/bootloader/Windows-32bit/run.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CoatiSoftware/SourcetrailPythonIndexer/eba5d0fe5059431bc479b2b36a814b6a9a21bde4/dependencies/pyinstaller/3.4/bootloader/Windows-32bit/run.exe -------------------------------------------------------------------------------- /dependencies/pyinstaller/3.4/bootloader/Windows-32bit/run_d.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CoatiSoftware/SourcetrailPythonIndexer/eba5d0fe5059431bc479b2b36a814b6a9a21bde4/dependencies/pyinstaller/3.4/bootloader/Windows-32bit/run_d.exe -------------------------------------------------------------------------------- /dependencies/pyinstaller/3.4/bootloader/Windows-32bit/runw.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CoatiSoftware/SourcetrailPythonIndexer/eba5d0fe5059431bc479b2b36a814b6a9a21bde4/dependencies/pyinstaller/3.4/bootloader/Windows-32bit/runw.exe -------------------------------------------------------------------------------- /dependencies/pyinstaller/3.4/bootloader/Windows-32bit/runw_d.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CoatiSoftware/SourcetrailPythonIndexer/eba5d0fe5059431bc479b2b36a814b6a9a21bde4/dependencies/pyinstaller/3.4/bootloader/Windows-32bit/runw_d.exe -------------------------------------------------------------------------------- /freezing.spec: -------------------------------------------------------------------------------- 1 | # -*- mode: python -*- 2 | 3 | import glob 4 | import jedi 5 | import parso 6 | 7 | 8 | block_cipher = None 9 | 10 | 11 | def get_file_list(root_path, package_path, extensions): 12 | files = [] 13 | for directory_info in os.walk(os.path.join(root_path, package_path)): 14 | directory_path = directory_info[0] 15 | rel_path = os.path.relpath(directory_path, root_path) 16 | for extension in extensions: 17 | for file in glob.glob(os.path.join(directory_path, extension)): 18 | files.append((file, rel_path)) 19 | return files 20 | 21 | 22 | def get_binaries(): 23 | binaries = [] 24 | site_packages_path = os.path.dirname(os.path.dirname(os.path.abspath(jedi.__file__))) 25 | print(site_packages_path) 26 | binaries.extend(get_file_list(site_packages_path, 'jedi', ['*.py'])) 27 | binaries.extend(get_file_list(site_packages_path, 'parso', ['*.py', '*.txt'])) 28 | return binaries 29 | 30 | 31 | a = Analysis(['run.py'], 32 | pathex=['./'], 33 | binaries=[], 34 | datas=get_binaries(), 35 | hiddenimports=[], 36 | hookspath=[], 37 | runtime_hooks=[], 38 | excludes=[], 39 | win_no_prefer_redirects=False, 40 | win_private_assemblies=False, 41 | cipher=block_cipher, 42 | noarchive=False) 43 | pyz = PYZ(a.pure, a.zipped_data, 44 | cipher=block_cipher) 45 | exe = EXE(pyz, 46 | a.scripts, 47 | [], 48 | exclude_binaries=True, 49 | name='SourcetrailPythonIndexer', 50 | debug=False, 51 | bootloader_ignore_signals=False, 52 | strip=False, 53 | upx=True, 54 | console=True ) 55 | coll = COLLECT(exe, 56 | a.binaries, 57 | a.zipfiles, 58 | a.datas, 59 | strip=False, 60 | upx=True, 61 | name='SourcetrailPythonIndexer') 62 | -------------------------------------------------------------------------------- /images/readme/class_members.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CoatiSoftware/SourcetrailPythonIndexer/eba5d0fe5059431bc479b2b36a814b6a9a21bde4/images/readme/class_members.png -------------------------------------------------------------------------------- /images/readme/field_references.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CoatiSoftware/SourcetrailPythonIndexer/eba5d0fe5059431bc479b2b36a814b6a9a21bde4/images/readme/field_references.png -------------------------------------------------------------------------------- /images/readme/fill_custom_sourcegroup.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CoatiSoftware/SourcetrailPythonIndexer/eba5d0fe5059431bc479b2b36a814b6a9a21bde4/images/readme/fill_custom_sourcegroup.png -------------------------------------------------------------------------------- /images/readme/function_calls.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CoatiSoftware/SourcetrailPythonIndexer/eba5d0fe5059431bc479b2b36a814b6a9a21bde4/images/readme/function_calls.png -------------------------------------------------------------------------------- /images/readme/local_symbols.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CoatiSoftware/SourcetrailPythonIndexer/eba5d0fe5059431bc479b2b36a814b6a9a21bde4/images/readme/local_symbols.png -------------------------------------------------------------------------------- /images/readme/pick_custom_sourcegroup.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CoatiSoftware/SourcetrailPythonIndexer/eba5d0fe5059431bc479b2b36a814b6a9a21bde4/images/readme/pick_custom_sourcegroup.png -------------------------------------------------------------------------------- /indexer.py: -------------------------------------------------------------------------------- 1 | import codecs 2 | import jedi 3 | import json 4 | import os 5 | import sys 6 | 7 | import sourcetraildb as srctrl 8 | 9 | from jedi.inference import InferenceState 10 | from jedi.api import helpers 11 | from jedi.inference.gradual.conversion import convert_names 12 | from jedi.api import classes 13 | 14 | from _version import __version__ 15 | from _version import _sourcetrail_db_version 16 | 17 | 18 | _virtualFilePath = 'virtual_file.py' 19 | 20 | 21 | class SourcetrailScript(jedi.Script): 22 | def __init__(self, source=None, line=None, column=None, path=None, 23 | encoding='utf-8', sys_path=None, environment=None, 24 | _project=None): 25 | jedi.Script.__init__(self, source, line, column, path, encoding, sys_path, environment, _project) 26 | 27 | def _goto(self, line, column, follow_imports=False, follow_builtin_imports=False, 28 | only_stubs=False, prefer_stubs=False, follow_override=False): 29 | if follow_override: 30 | return super()._goto(line, column, follow_imports=follow_imports, follow_builtin_imports=follow_builtin_imports, only_stubs=only_stubs, prefer_stubs=prefer_stubs) 31 | tree_name = self._module_node.get_name_of_position((line, column)) 32 | if tree_name is None: 33 | # Without a name we really just want to jump to the result e.g. 34 | # executed by `foo()`, if we the cursor is after `)`. 35 | return self.infer(line, column, only_stubs=only_stubs, prefer_stubs=prefer_stubs) 36 | name = self._get_module_context().create_name(tree_name) 37 | 38 | names = list(name.goto()) 39 | 40 | if follow_imports: 41 | names = helpers.filter_follow_imports(names, follow_builtin_imports) 42 | names = convert_names( 43 | names, 44 | only_stubs=only_stubs, 45 | prefer_stubs=prefer_stubs, 46 | ) 47 | 48 | defs = [classes.Name(self._inference_state, d) for d in set(names)] 49 | return list(set(helpers.sorted_definitions(defs))) 50 | 51 | 52 | def isValidEnvironment(environmentPath): 53 | try: 54 | environment = jedi.create_environment(environmentPath, False) 55 | environment._get_subprocess() # check if this environment is really functional 56 | except Exception as e: 57 | if os.name == 'nt' and os.path.isdir(environmentPath): 58 | try: 59 | environment = jedi.create_environment(os.path.join(environmentPath, "python.exe"), False) 60 | environment._get_subprocess() # check if this environment is really functional 61 | return '' 62 | except Exception: 63 | pass 64 | return str(e) 65 | return '' 66 | 67 | 68 | def getEnvironment(environmentPath = None): 69 | if environmentPath is not None: 70 | try: 71 | environment = jedi.create_environment(environmentPath, False) 72 | environment._get_subprocess() # check if this environment is really functional 73 | return environment 74 | except Exception as e: 75 | if os.name == 'nt' and os.path.isdir(environmentPath): 76 | try: 77 | environment = jedi.create_environment(os.path.join(environmentPath, "python.exe"), False) 78 | environment._get_subprocess() # check if this environment is really functional 79 | return environment 80 | except Exception: 81 | pass 82 | print('WARNING: The provided environment path "' + environmentPath + '" does not specify a functional Python ' 83 | 'environment (details: "' + str(e) + '"). Using fallback environment instead.') 84 | 85 | try: 86 | environment = jedi.get_default_environment() 87 | environment._get_subprocess() # check if this environment is really functional 88 | return environment 89 | except Exception: 90 | pass 91 | 92 | try: 93 | for environment in jedi.find_system_environments(): 94 | return environment 95 | except Exception: 96 | pass 97 | 98 | if os.name == 'nt': # this is just a workaround and shall be removed once Jedi is fixed (Pull request https://github.com/davidhalter/jedi/pull/1282) 99 | for version in jedi.api.environment._SUPPORTED_PYTHONS: 100 | for exe in jedi.api.environment._get_executables_from_windows_registry(version): 101 | try: 102 | return jedi.api.environment.Environment(exe) 103 | except jedi.InvalidPythonEnvironment: 104 | pass 105 | 106 | raise jedi.InvalidPythonEnvironment("Unable to find an executable Python environment.") 107 | 108 | 109 | def isSourcetrailDBVersionCompatible(allowLogging = False): 110 | requiredVersion = _sourcetrail_db_version 111 | 112 | try: 113 | usedVersion = srctrl.getVersionString() 114 | except AttributeError: 115 | if allowLogging: 116 | print('ERROR: Used version of SourcetrailDB is incompatible to what is required by this version of SourcetrailPythonIndexer (' + requiredVersion + ').') 117 | return False 118 | 119 | if usedVersion != requiredVersion: 120 | if allowLogging: 121 | print('ERROR: Used version of SourcetrailDB (' + usedVersion + ') is incompatible to what is required by this version of SourcetrailPythonIndexer (' + requiredVersion + ').') 122 | return False 123 | return True 124 | 125 | 126 | def indexSourceCode(sourceCode, workingDirectory, astVisitorClient, isVerbose, environmentPath = None, sysPath = None): 127 | sourceFilePath = _virtualFilePath 128 | 129 | environment = getEnvironment(environmentPath) 130 | 131 | project = jedi.api.project.Project(workingDirectory, environment_path = environment.path) 132 | 133 | evaluator = InferenceState( 134 | project, 135 | environment=environment, 136 | script_path=workingDirectory 137 | ) 138 | 139 | module_node = evaluator.parse( 140 | code=sourceCode, 141 | path=workingDirectory, 142 | cache=False, 143 | diff_cache=False 144 | ) 145 | 146 | if (isVerbose): 147 | astVisitor = VerboseAstVisitor(astVisitorClient, evaluator, sourceFilePath, sourceCode, sysPath) 148 | else: 149 | astVisitor = AstVisitor(astVisitorClient, evaluator, sourceFilePath, sourceCode, sysPath) 150 | 151 | astVisitor.traverseNode(module_node) 152 | 153 | 154 | def indexSourceFile(sourceFilePath, environmentPath, workingDirectory, astVisitorClient, isVerbose): 155 | 156 | if isVerbose: 157 | print('INFO: Indexing source file "' + sourceFilePath + '".') 158 | 159 | sourceCode = '' 160 | try: 161 | with codecs.open(sourceFilePath, 'r', encoding='utf-8') as input: 162 | sourceCode=input.read() 163 | except UnicodeDecodeError: 164 | print('WARNING: Unable to open source file using utf-8 encoding. Trying to derive encoding automatically.') 165 | with codecs.open(sourceFilePath, 'r') as input: 166 | sourceCode=input.read() 167 | 168 | environment = getEnvironment(environmentPath) 169 | 170 | if isVerbose: 171 | print('INFO: Using Python environment at "' + environment.path + '" for indexing.') 172 | 173 | project = jedi.api.project.Project(workingDirectory, environment_path = environment.path) 174 | 175 | evaluator = InferenceState( 176 | project, 177 | environment=environment, 178 | script_path=workingDirectory 179 | ) 180 | 181 | module_node = evaluator.parse( 182 | code=sourceCode, 183 | path=workingDirectory, 184 | cache=False, 185 | diff_cache=False 186 | ) 187 | 188 | if (isVerbose): 189 | astVisitor = VerboseAstVisitor(astVisitorClient, evaluator, sourceFilePath) 190 | else: 191 | astVisitor = AstVisitor(astVisitorClient, evaluator, sourceFilePath) 192 | 193 | astVisitor.traverseNode(module_node) 194 | 195 | 196 | class ContextInfo: 197 | 198 | def __init__(self, id, name, node): 199 | self.id = id 200 | self.name = name 201 | self.node = node 202 | 203 | 204 | class AstVisitor: 205 | 206 | def __init__(self, client, evaluator, sourceFilePath, sourceFileContent = None, sysPath = None): 207 | 208 | self.client = client 209 | self.environment = evaluator.environment 210 | 211 | self.sourceFilePath = sourceFilePath 212 | if sourceFilePath != _virtualFilePath: 213 | self.sourceFilePath = os.path.abspath(self.sourceFilePath) 214 | 215 | self.sourceFileName = os.path.split(self.sourceFilePath)[-1] 216 | self.sourceFileContent = sourceFileContent 217 | 218 | packageRootPath = os.path.dirname(self.sourceFilePath) 219 | while os.path.exists(os.path.join(packageRootPath, '__init__.py')): 220 | packageRootPath = os.path.dirname(packageRootPath) 221 | self.sysPath = [packageRootPath] 222 | 223 | if sysPath is not None: 224 | self.sysPath.extend(sysPath) 225 | else: 226 | baseSysPath = evaluator.environment.get_sys_path() 227 | baseSysPath.sort(reverse=True) 228 | self.sysPath.extend(baseSysPath) 229 | self.sysPath = list(filter(None, self.sysPath)) 230 | 231 | self.contextStack = [] 232 | 233 | fileId = self.client.recordFile(self.sourceFilePath) 234 | if fileId == 0: 235 | print('ERROR: ' + srctrl.getLastError()) 236 | self.client.recordFileLanguage(fileId, 'python') 237 | self.contextStack.append(ContextInfo(fileId, self.sourceFilePath, None)) 238 | 239 | moduleNameHierarchy = self.getNameHierarchyFromModuleFilePath(self.sourceFilePath) 240 | if moduleNameHierarchy is not None: 241 | moduleId = self.client.recordSymbol(moduleNameHierarchy) 242 | self.client.recordSymbolDefinitionKind(moduleId, srctrl.DEFINITION_EXPLICIT) 243 | self.client.recordSymbolKind(moduleId, srctrl.SYMBOL_MODULE) 244 | self.contextStack.append(ContextInfo(moduleId, moduleNameHierarchy.getDisplayString(), None)) 245 | 246 | 247 | def traverseNode(self, node): 248 | if node is None: 249 | return 250 | 251 | if node.type == 'classdef': 252 | self.beginVisitClassdef(node) 253 | elif node.type == 'funcdef': 254 | self.beginVisitFuncdef(node) 255 | if node.type == 'import_from': 256 | self.beginVisitImportFrom(node) 257 | if node.type == 'import_name': 258 | self.beginVisitImportName(node) 259 | elif node.type == 'name': 260 | self.beginVisitName(node) 261 | elif node.type == 'string': 262 | self.beginVisitString(node) 263 | elif node.type == 'error_leaf': 264 | self.beginVisitErrorLeaf(node) 265 | 266 | if hasattr(node, 'children'): 267 | for c in node.children: 268 | self.traverseNode(c) 269 | 270 | if node.type == 'classdef': 271 | self.endVisitClassdef(node) 272 | elif node.type == 'funcdef': 273 | self.endVisitFuncdef(node) 274 | if node.type == 'import_from': 275 | self.endVisitImportFrom(node) 276 | if node.type == 'import_name': 277 | self.endVisitImportName(node) 278 | elif node.type == 'name': 279 | self.endVisitName(node) 280 | elif node.type == 'string': 281 | self.endVisitString(node) 282 | elif node.type == 'error_leaf': 283 | self.endVisitErrorLeaf(node) 284 | 285 | 286 | def beginVisitClassdef(self, node): 287 | nameNode = getFirstDirectChildWithType(node, 'name') 288 | 289 | symbolNameHierarchy = self.getNameHierarchyOfNode(nameNode, self.sourceFilePath) 290 | if symbolNameHierarchy is None: 291 | symbolNameHierarchy = getNameHierarchyForUnsolvedSymbol() 292 | 293 | symbolId = self.client.recordSymbol(symbolNameHierarchy) 294 | self.client.recordSymbolDefinitionKind(symbolId, srctrl.DEFINITION_EXPLICIT) 295 | self.client.recordSymbolKind(symbolId, srctrl.SYMBOL_CLASS) 296 | self.client.recordSymbolLocation(symbolId, getSourceRangeOfNode(nameNode)) 297 | self.client.recordSymbolScopeLocation(symbolId, getSourceRangeOfNode(node)) 298 | self.contextStack.append(ContextInfo(symbolId, symbolNameHierarchy.getDisplayString(), node)) 299 | 300 | 301 | def endVisitClassdef(self, node): 302 | if len(self.contextStack) > 0: 303 | contextNode = self.contextStack[-1].node 304 | if node == contextNode: 305 | self.contextStack.pop() 306 | 307 | 308 | def beginVisitFuncdef(self, node): 309 | nameNode = getFirstDirectChildWithType(node, 'name') 310 | 311 | symbolNameHierarchy = self.getNameHierarchyOfNode(nameNode, self.sourceFilePath) 312 | if symbolNameHierarchy is None: 313 | symbolNameHierarchy = getNameHierarchyForUnsolvedSymbol() 314 | 315 | symbolId = self.client.recordSymbol(symbolNameHierarchy) 316 | self.client.recordSymbolDefinitionKind(symbolId, srctrl.DEFINITION_EXPLICIT) 317 | self.client.recordSymbolKind(symbolId, srctrl.SYMBOL_FUNCTION) 318 | self.client.recordSymbolLocation(symbolId, getSourceRangeOfNode(nameNode)) 319 | self.client.recordSymbolScopeLocation(symbolId, getSourceRangeOfNode(node)) 320 | self.contextStack.append(ContextInfo(symbolId, symbolNameHierarchy.getDisplayString(), node)) 321 | 322 | self.recordFunctionOverrideEdge(nameNode) 323 | 324 | 325 | def recordFunctionOverrideEdge(self, functionNameNode): 326 | try: 327 | functionNameHierarchy = self.getNameHierarchyOfNode(functionNameNode, self.sourceFilePath) 328 | if functionNameHierarchy is None: 329 | return 330 | functionSymbolId = self.client.recordSymbol(functionNameHierarchy) 331 | 332 | (startLine, startColumn) = functionNameNode.start_pos 333 | script = self.createScript(self.sourceFilePath) 334 | for definition in script.goto(line=startLine, column=startColumn, follow_imports=True, follow_override=True): 335 | if definition is None: 336 | continue 337 | 338 | overriddenNameNode = definition._name.tree_name 339 | 340 | if functionNameNode.start_pos == overriddenNameNode.start_pos: 341 | continue 342 | 343 | overriddenNameHierarchy = self.getNameHierarchyOfNode(overriddenNameNode, self.sourceFilePath) 344 | if overriddenNameHierarchy is None: 345 | continue 346 | overriddenSymbolId = self.client.recordSymbol(overriddenNameHierarchy) 347 | 348 | referenceId = self.client.recordReference( 349 | functionSymbolId, 350 | overriddenSymbolId, 351 | srctrl.REFERENCE_OVERRIDE 352 | ) 353 | 354 | self.client.recordReferenceLocation(referenceId, getSourceRangeOfNode(overriddenNameNode)) 355 | except Exception: 356 | pass 357 | 358 | 359 | def endVisitFuncdef(self, node): 360 | if len(self.contextStack) > 0: 361 | contextNode = self.contextStack[-1].node 362 | if node == contextNode: 363 | self.contextStack.pop() 364 | 365 | 366 | def beginVisitImportName(self, node): 367 | self.recordErrorsForUnsolvedImports(node) 368 | 369 | 370 | def endVisitImportName(self, node): 371 | if len(self.contextStack) > 0: 372 | contextNode = self.contextStack[-1].node 373 | if node == contextNode: 374 | self.contextStack.pop() 375 | 376 | 377 | def beginVisitImportFrom(self, node): 378 | self.recordErrorsForUnsolvedImports(node) 379 | 380 | 381 | def endVisitImportFrom(self, node): 382 | if len(self.contextStack) > 0: 383 | contextNode = self.contextStack[-1].node 384 | if node == contextNode: 385 | self.contextStack.pop() 386 | 387 | 388 | def beginVisitName(self, node): 389 | if len(self.contextStack) == 0: 390 | return 391 | 392 | if node.value in ['True', 'False', 'None']: # these are not parsed as "keywords" in Python 2 393 | return 394 | 395 | referenceIsUnsolved = True 396 | for definition in self.getDefinitionsOfNode(node, self.sourceFilePath): 397 | if definition is None: 398 | continue 399 | 400 | try: 401 | if definition.type == 'instance': 402 | if definition.line is None and definition.column is None: 403 | if self.recordInstanceReference(node, definition): 404 | referenceIsUnsolved = False 405 | 406 | elif definition.type == 'module': 407 | if self.recordModuleReference(node, definition): 408 | referenceIsUnsolved = False 409 | 410 | elif definition.type in ['class', 'function']: 411 | (startLine, startColumn) = node.start_pos 412 | if definition.line == startLine and definition.column == startColumn: 413 | # Early exit. We don't record references for locations of classes or functions that are definitions 414 | return 415 | 416 | if definition.type == 'class': 417 | if self.recordClassReference(node, definition): 418 | referenceIsUnsolved = False 419 | 420 | elif definition.type == 'function': 421 | if self.recordFunctionReference(node, definition): 422 | referenceIsUnsolved = False 423 | 424 | elif definition.type == 'param': 425 | if definition.line is None or definition.column is None: 426 | # Early skip and try next definition. For now we don't record references for names that don't have a valid definition location 427 | continue 428 | 429 | if self.recordParamReference(node, definition): 430 | referenceIsUnsolved = False 431 | 432 | elif definition.type == 'statement': 433 | if definition.line is None or definition.column is None: 434 | # Early skip and try next definition. For now we don't record references for names that don't have a valid definition location 435 | continue 436 | 437 | if self.recordStatementReference(node, definition): 438 | referenceIsUnsolved = False 439 | except Exception as e: 440 | print('ERROR: Encountered exception "' + e.__repr__() + '" while trying to solve the definition of node "' + node.value + '" at ' + getSourceRangeOfNode(node).toString() + '.') 441 | 442 | if referenceIsUnsolved: 443 | self.client.recordReferenceToUnsolvedSymhol(self.contextStack[-1].id, srctrl.REFERENCE_USAGE, getSourceRangeOfNode(node)) 444 | 445 | 446 | def endVisitName(self, node): 447 | if len(self.contextStack) > 0: 448 | contextNode = self.contextStack[-1].node 449 | if node == contextNode: 450 | self.contextStack.pop() 451 | 452 | 453 | def beginVisitString(self, node): 454 | sourceRange = getSourceRangeOfNode(node) 455 | if sourceRange.startLine != sourceRange.endLine: 456 | self.client.recordAtomicSourceRange(sourceRange) 457 | 458 | 459 | def endVisitString(self, node): 460 | if len(self.contextStack) > 0: 461 | contextNode = self.contextStack[-1].node 462 | if node == contextNode: 463 | self.contextStack.pop() 464 | 465 | 466 | def beginVisitErrorLeaf(self, node): 467 | self.client.recordError('Unexpected token of type "' + node.token_type + '" encountered.', False, getSourceRangeOfNode(node)) 468 | 469 | 470 | def endVisitErrorLeaf(self, node): 471 | if len(self.contextStack) > 0: 472 | contextNode = self.contextStack[-1].node 473 | if node == contextNode: 474 | self.contextStack.pop() 475 | 476 | 477 | def recordErrorsForUnsolvedImports(self, node): 478 | if node.type == 'import_from': 479 | for c in node.children: 480 | if self.recordErrorsForUnsolvedImports(c) is False: 481 | return False 482 | elif node.type == 'import_as_names': 483 | for c in node.children: 484 | self.recordErrorsForUnsolvedImports(c) 485 | elif node.type == 'import_as_name': 486 | for c in node.children: 487 | if c.type == 'keyword': # we just the children (usually only one) until we hit the "as" keyword 488 | break 489 | self.recordErrorsForUnsolvedImports(c) 490 | elif node.type == 'import_name': 491 | for c in node.children: 492 | self.recordErrorsForUnsolvedImports(c) 493 | elif node.type == 'dotted_as_names': 494 | for c in node.children: 495 | self.recordErrorsForUnsolvedImports(c) 496 | elif node.type == 'dotted_as_name': 497 | for c in node.children: 498 | if c.type == 'keyword': # we just the children (usually only one) until we hit the "as" keyword 499 | break 500 | self.recordErrorsForUnsolvedImports(c) 501 | elif node.type == 'dotted_name': 502 | for c in node.children: 503 | if self.recordErrorsForUnsolvedImports(c) is False: 504 | return False 505 | elif node.type == 'name': 506 | if len(self.getDefinitionsOfNode(node, self.sourceFilePath)) == 0: 507 | self.client.recordError('Imported symbol named "' + node.value + '" has not been found.', False, getSourceRangeOfNode(node)) 508 | return False 509 | return True 510 | 511 | 512 | def recordInstanceReference(self, node, definition): 513 | nameHierarchy = self.getNameHierarchyFromFullNameOfDefinition(definition) 514 | if nameHierarchy is not None: 515 | referencedSymbolId = self.client.recordSymbol(nameHierarchy) 516 | self.client.recordSymbolKind(referencedSymbolId, srctrl.SYMBOL_GLOBAL_VARIABLE) 517 | 518 | referenceKind = srctrl.REFERENCE_USAGE 519 | if getParentWithType(node, 'import_from') is not None: 520 | # this would be the case for "from foo import f as my_f" 521 | # ^ ^ 522 | referenceKind = srctrl.REFERENCE_IMPORT 523 | 524 | referenceId = self.client.recordReference( 525 | self.contextStack[-1].id, 526 | referencedSymbolId, 527 | referenceKind 528 | ) 529 | self.client.recordReferenceLocation(referenceId, getSourceRangeOfNode(node)) 530 | return True 531 | return False 532 | 533 | 534 | def recordModuleReference(self, node, definition): 535 | referencedNameHierarchy = self.getNameHierarchyFromModulePathOfDefinition(definition) 536 | if referencedNameHierarchy is None: 537 | referencedNameHierarchy = self.getNameHierarchyFromFullNameOfDefinition(definition) 538 | if referencedNameHierarchy is None: 539 | return False 540 | 541 | referencedSymbolId = self.client.recordSymbol(referencedNameHierarchy) 542 | 543 | # Record symbol kind. If the used type is within indexed code, we already have this info. In any other case, this is valuable info! 544 | self.client.recordSymbolKind(referencedSymbolId, srctrl.SYMBOL_MODULE) 545 | 546 | if isQualifierNode(node): 547 | self.client.recordQualifierLocation(referencedSymbolId, getSourceRangeOfNode(node)) 548 | else: 549 | referenceKind = srctrl.REFERENCE_USAGE 550 | if getParentWithType(node, 'import_name') is not None: 551 | # this would be the case for "import foo" 552 | # ^ 553 | referenceKind = srctrl.REFERENCE_IMPORT 554 | 555 | referenceId = self.client.recordReference( 556 | self.contextStack[-1].id, 557 | referencedSymbolId, 558 | referenceKind 559 | ) 560 | 561 | self.client.recordReferenceLocation(referenceId, getSourceRangeOfNode(node)) 562 | return True 563 | 564 | 565 | def recordClassReference(self, node, definition): 566 | referencedNameHierarchy = self.getNameHierarchyOfClassOrFunctionDefinition(definition) 567 | if referencedNameHierarchy is None: 568 | return False 569 | 570 | referencedSymbolId = self.client.recordSymbol(referencedNameHierarchy) 571 | 572 | # Record symbol kind. If the used type is within indexed code, we already have this info. In any other case, this is valuable info! 573 | self.client.recordSymbolKind(referencedSymbolId, srctrl.SYMBOL_CLASS) 574 | 575 | if isQualifierNode(node): 576 | self.client.recordQualifierLocation(referencedSymbolId, getSourceRangeOfNode(node)) 577 | else: 578 | referenceKind = srctrl.REFERENCE_TYPE_USAGE 579 | if node.parent is not None: 580 | if node.parent.type == 'classdef': 581 | # this would be the case for "class Foo(Bar)" 582 | # ^ 583 | referenceKind = srctrl.REFERENCE_INHERITANCE 584 | elif node.parent.type in ['arglist', 'testlist'] and node.parent.parent is not None and node.parent.parent.type == 'classdef': 585 | # this would be the case for "class Foo(Bar, Baz)" 586 | # ^ ^ 587 | referenceKind = srctrl.REFERENCE_INHERITANCE 588 | elif getParentWithType(node, 'import_from') is not None: 589 | # this would be the case for "from foo import Foo as F" 590 | # ^ ^ 591 | referenceKind = srctrl.REFERENCE_IMPORT 592 | 593 | referenceId = self.client.recordReference( 594 | self.contextStack[-1].id, 595 | referencedSymbolId, 596 | referenceKind 597 | ) 598 | self.client.recordReferenceLocation(referenceId, getSourceRangeOfNode(node)) 599 | 600 | if referenceKind == srctrl.REFERENCE_TYPE_USAGE and isCallNode(node): 601 | constructorNameHierarchy = referencedNameHierarchy.copy() 602 | constructorNameHierarchy.nameElements.append(NameElement('__init__')) 603 | constructorSymbolId = self.client.recordSymbol(constructorNameHierarchy) 604 | self.client.recordSymbolKind(constructorSymbolId, srctrl.SYMBOL_METHOD) 605 | callReferenceId = self.client.recordReference( 606 | self.contextStack[-1].id, 607 | constructorSymbolId, 608 | srctrl.REFERENCE_CALL 609 | ) 610 | self.client.recordReferenceLocation(callReferenceId, getSourceRangeOfNode(node)) 611 | 612 | return True 613 | 614 | 615 | def recordFunctionReference(self, node, definition): 616 | referencedNameHierarchy = self.getNameHierarchyOfClassOrFunctionDefinition(definition) 617 | if referencedNameHierarchy is None: 618 | return False 619 | 620 | referencedSymbolId = self.client.recordSymbol(referencedNameHierarchy) 621 | 622 | # Record symbol kind. If the called function is within indexed code, we already have this info. In any other case, this is valuable info! 623 | self.client.recordSymbolKind(referencedSymbolId, srctrl.SYMBOL_FUNCTION) 624 | 625 | referenceKind = -1 626 | if isCallNode(node): 627 | referenceKind = srctrl.REFERENCE_CALL 628 | elif getParentWithType(node, 'import_from'): 629 | referenceKind = srctrl.REFERENCE_IMPORT 630 | 631 | if referenceKind == -1: 632 | return False 633 | 634 | referenceId = self.client.recordReference( 635 | self.contextStack[-1].id, 636 | referencedSymbolId, 637 | referenceKind 638 | ) 639 | 640 | self.client.recordReferenceLocation(referenceId, getSourceRangeOfNode(node)) 641 | return True 642 | 643 | 644 | def recordParamReference(self, node, definition): 645 | localSymbolId = self.client.recordLocalSymbol(self.getLocalSymbolName(definition)) 646 | self.client.recordLocalSymbolLocation(localSymbolId, getSourceRangeOfNode(node)) 647 | return True 648 | 649 | 650 | def recordStatementReference(self, node, definition): 651 | definitionModulePath = definition.module_path 652 | if definitionModulePath is None: 653 | if self.sourceFilePath == _virtualFilePath: 654 | definitionModulePath = self.sourceFilePath 655 | else: 656 | return False 657 | 658 | symbolKind = None 659 | referenceKind = None 660 | definitionKind = None 661 | 662 | definitionNameNode = definition._name.tree_name 663 | namedDefinitionParentNode = getParentWithTypeInList(definitionNameNode, ['classdef', 'funcdef']) 664 | if namedDefinitionParentNode is not None: 665 | if namedDefinitionParentNode.type in ['classdef']: 666 | if getNamedParentNode(definitionNameNode) == namedDefinitionParentNode: 667 | # definition is not local to some other field instantiation but instead it is a static member variable 668 | if definitionNameNode.start_pos == node.start_pos and definitionNameNode.end_pos == node.end_pos: 669 | # node is the definition of the static member variable 670 | symbolKind = srctrl.SYMBOL_FIELD 671 | definitionKind = srctrl.DEFINITION_EXPLICIT 672 | else: 673 | # node is a usage of the static member variable 674 | referenceKind = srctrl.REFERENCE_USAGE 675 | elif namedDefinitionParentNode.type in ['funcdef']: 676 | # definition may be a non-static member variable 677 | if definitionNameNode.parent is not None and definitionNameNode.parent.type == 'trailer': 678 | potentialParamNode = getNamedParentNode(definitionNameNode) 679 | if potentialParamNode is not None: 680 | for potentialParamDefinition in self.getDefinitionsOfNode(potentialParamNode, definitionModulePath): 681 | if potentialParamDefinition is not None and potentialParamDefinition.type == 'param': 682 | paramDefinitionNameNode = potentialParamDefinition._name.tree_name 683 | potentialFuncdefNode = getNamedParentNode(paramDefinitionNameNode) 684 | if potentialFuncdefNode is not None and potentialFuncdefNode.type == 'funcdef': 685 | potentialClassdefNode = getNamedParentNode(potentialFuncdefNode) 686 | if potentialClassdefNode is not None and potentialClassdefNode.type == 'classdef': 687 | preceedingNode = paramDefinitionNameNode.parent.get_previous_sibling() 688 | if preceedingNode is not None and preceedingNode.type != 'param': 689 | # 'paramDefinitionNameNode' is the first parameter of a member function (aka. 'self') 690 | referenceKind = srctrl.REFERENCE_USAGE 691 | if definitionNameNode.start_pos == node.start_pos and definitionNameNode.end_pos == node.end_pos: 692 | symbolKind = srctrl.SYMBOL_FIELD 693 | definitionKind = srctrl.DEFINITION_EXPLICIT 694 | else: 695 | symbolKind = srctrl.SYMBOL_GLOBAL_VARIABLE 696 | if definitionNameNode.start_pos == node.start_pos and definitionNameNode.end_pos == node.end_pos: 697 | # node is the definition of a global variable 698 | definitionKind = srctrl.DEFINITION_EXPLICIT 699 | elif getParentWithType(node, 'import_from') is not None: 700 | # this would be the case for "from foo import f as my_f" 701 | # ^ ^ 702 | referenceKind = srctrl.REFERENCE_IMPORT 703 | else: 704 | referenceKind = srctrl.REFERENCE_USAGE 705 | 706 | sourceRange = getSourceRangeOfNode(node) 707 | 708 | if symbolKind is not None or referenceKind is not None: 709 | symbolNameHierarchy = self.getNameHierarchyOfNode(definitionNameNode, definitionModulePath) 710 | if symbolNameHierarchy is None: 711 | return False 712 | 713 | symbolId = self.client.recordSymbol(symbolNameHierarchy) 714 | 715 | if symbolKind is not None: 716 | self.client.recordSymbolKind(symbolId, symbolKind) 717 | 718 | if definitionKind is not None: 719 | self.client.recordSymbolDefinitionKind(symbolId, definitionKind) 720 | self.client.recordSymbolLocation(symbolId, sourceRange) 721 | 722 | if referenceKind is not None: 723 | referenceId = self.client.recordReference( 724 | self.contextStack[-1].id, 725 | symbolId, 726 | referenceKind 727 | ) 728 | self.client.recordReferenceLocation(referenceId, sourceRange) 729 | else: 730 | localSymbolId = self.client.recordLocalSymbol(self.getLocalSymbolName(definition)) 731 | self.client.recordLocalSymbolLocation(localSymbolId, sourceRange) 732 | return True 733 | 734 | 735 | def getLocalSymbolName(self, definition): 736 | definitionNameNode = definition._name.tree_name 737 | 738 | definitionModulePath = definition.module_path 739 | if definitionModulePath is None: 740 | if self.sourceFilePath == _virtualFilePath: 741 | definitionModulePath = self.sourceFilePath 742 | 743 | contextName = '' 744 | if definitionModulePath is not None: 745 | parentFuncdef = getParentWithType(definitionNameNode, 'funcdef') 746 | if parentFuncdef is not None: 747 | parentFuncdefNameNode = getFirstDirectChildWithType(parentFuncdef, 'name') 748 | if parentFuncdefNameNode is not None: 749 | parentFuncdefNameHierarchy = self.getNameHierarchyOfNode(parentFuncdefNameNode, definitionModulePath) 750 | if parentFuncdefNameHierarchy is not None: 751 | contextName = parentFuncdefNameHierarchy.getDisplayString() 752 | 753 | if len(contextName) == 0: 754 | contextName = str(self.contextStack[-1].name) 755 | 756 | return contextName + '<' + definitionNameNode.value + '>' 757 | 758 | 759 | def getNameHierarchyFromModuleFilePath(self, filePath): 760 | if filePath is None: 761 | return None 762 | 763 | if filePath == _virtualFilePath: 764 | return NameHierarchy(NameElement(os.path.splitext(_virtualFilePath)[0]), '.') 765 | 766 | filePath = os.path.abspath(filePath) 767 | filePath = os.path.splitext(filePath)[0] 768 | 769 | sysPath = [] 770 | 771 | jediPath = os.path.dirname(jedi.__file__) 772 | major = self.environment.version_info.major 773 | minor = self.environment.version_info.minor 774 | if major == 2: 775 | sysPath.append(os.path.abspath(jediPath + '/third_party/typeshed/stdlib/2')) 776 | if major == 2 or major == 3: 777 | sysPath.append(os.path.abspath(jediPath + '/third_party/typeshed/stdlib/2and3')) 778 | if major == 3: 779 | sysPath.append(os.path.abspath(jediPath + '/third_party/typeshed/stdlib/3')) 780 | if minor == 5: 781 | sysPath.append(os.path.abspath(jediPath + '/third_party/typeshed/stdlib/3.5')) 782 | if minor == 6: 783 | sysPath.append(os.path.abspath(jediPath + '/third_party/typeshed/stdlib/3.6')) 784 | if minor == 7: 785 | sysPath.append(os.path.abspath(jediPath + '/third_party/typeshed/stdlib/3.7')) 786 | 787 | sysPath.extend(self.sysPath) 788 | 789 | for p in sysPath: 790 | if filePath.startswith(p): 791 | rest = filePath[len(p):] 792 | if rest.startswith(os.path.sep): 793 | # Remove a slash in cases it's still there. 794 | rest = rest[1:] 795 | if rest: 796 | split = rest.split(os.path.sep) 797 | for string in split: 798 | if not string: 799 | return None 800 | 801 | if split[-1] == '__init__': 802 | split = split[:-1] 803 | if split[-1] == '__builtin__': 804 | split = split[:-1] 805 | split.insert(0, 'builtins') 806 | 807 | nameHierarchy = None 808 | for namePart in split: 809 | if nameHierarchy is None: 810 | nameHierarchy = NameHierarchy(NameElement(namePart), '.') 811 | else: 812 | nameHierarchy.nameElements.append(NameElement(namePart)) 813 | return nameHierarchy 814 | 815 | return None 816 | 817 | 818 | def getNameHierarchyFromModulePathOfDefinition(self, definition): 819 | nameHierarchy = self.getNameHierarchyFromModuleFilePath(definition.module_path) 820 | if nameHierarchy is not None: 821 | if nameHierarchy.nameElements[-1].name != definition.name: 822 | nameHierarchy.nameElements.append(NameElement(definition.name)) 823 | return nameHierarchy 824 | 825 | 826 | def getNameHierarchyFromFullNameOfDefinition(self, definition): 827 | nameHierarchy = None 828 | for namePart in definition.full_name.split('.'): 829 | if nameHierarchy is None: 830 | nameHierarchy = NameHierarchy(NameElement(namePart), '.') 831 | else: 832 | nameHierarchy.nameElements.append(NameElement(namePart)) 833 | return nameHierarchy 834 | 835 | 836 | def getNameHierarchyOfClassOrFunctionDefinition(self, definition): 837 | if definition is None: 838 | return None 839 | 840 | if definition.line is None and definition.column is None: 841 | if definition.module_name in ['builtins', '__builtin__']: 842 | nameHierarchy = NameHierarchy(NameElement('builtins'), '.') 843 | if definition.full_name is not None: 844 | for namePart in definition.full_name.split('.'): 845 | nameHierarchy.nameElements.append(NameElement(namePart)) 846 | else: 847 | for namePart in definition.name.split('.'): 848 | nameHierarchy.nameElements.append(NameElement(namePart)) 849 | return nameHierarchy 850 | else: 851 | return self.getNameHierarchyFromFullNameOfDefinition(definition) 852 | 853 | else: 854 | if definition._name is None or definition._name.tree_name is None: 855 | return None 856 | 857 | definitionModulePath = definition.module_path 858 | if definitionModulePath is None: 859 | if self.sourceFilePath == _virtualFilePath: 860 | definitionModulePath = self.sourceFilePath 861 | else: 862 | return None 863 | 864 | return self.getNameHierarchyOfNode(definition._name.tree_name, definitionModulePath) 865 | 866 | 867 | def getDefinitionsOfNode(self, node, nodeSourceFilePath): 868 | try: 869 | (startLine, startColumn) = node.start_pos 870 | script = self.createScript(nodeSourceFilePath) 871 | return script.goto(line=startLine, column=startColumn, follow_imports=True) 872 | 873 | except Exception: 874 | return [] 875 | 876 | 877 | def getNameHierarchyOfNode(self, node, nodeSourceFilePath): 878 | if node is None: 879 | return None 880 | 881 | if node.type == 'name': 882 | nameNode = node 883 | else: 884 | nameNode = getFirstDirectChildWithType(node, 'name') 885 | 886 | if nameNode is None: 887 | return None 888 | 889 | # we derive the name for the canonical node (e.g. the node's definition) 890 | for definition in self.getDefinitionsOfNode(nameNode, nodeSourceFilePath): 891 | if definition is None: 892 | continue 893 | 894 | definitionModulePath = definition.module_path 895 | if definitionModulePath is None: 896 | if self.sourceFilePath == _virtualFilePath: 897 | definitionModulePath = self.sourceFilePath 898 | else: 899 | continue 900 | 901 | definitionNameNode = definition._name.tree_name 902 | if definitionNameNode is None: 903 | continue 904 | 905 | parentNode = getParentWithTypeInList(definitionNameNode.parent, ['classdef', 'funcdef']) 906 | potentialSelfNode = getNamedParentNode(definitionNameNode) 907 | # if the node is defines as a non-static member variable, we remove the "function_name.self" from the 908 | # name hierarchy (e.g. "Foo.__init__.self.bar" gets shortened to "Foo.bar") 909 | if potentialSelfNode is not None: 910 | potentialSelfNameNode = getFirstDirectChildWithType(potentialSelfNode, 'name') 911 | if potentialSelfNameNode is not None: 912 | for potentialSelfDefinition in self.getDefinitionsOfNode(potentialSelfNameNode, definitionModulePath): 913 | if potentialSelfDefinition is None or potentialSelfDefinition.type != 'param': 914 | continue 915 | 916 | potentialSelfDefinitionNameNode = potentialSelfDefinition._name.tree_name 917 | 918 | potentialFuncdefNode = getNamedParentNode(potentialSelfDefinitionNameNode) 919 | if potentialFuncdefNode is None or potentialFuncdefNode.type != 'funcdef': 920 | continue 921 | 922 | potentialClassdefNode = getNamedParentNode(potentialFuncdefNode) 923 | if potentialClassdefNode is None or potentialClassdefNode.type != 'classdef': 924 | continue 925 | 926 | preceedingNode = potentialSelfDefinitionNameNode.parent.get_previous_sibling() 927 | if preceedingNode is not None and preceedingNode.type != 'param': 928 | # 'node' is the first parameter of a member function (aka. 'self') 929 | parentNode = potentialClassdefNode 930 | 931 | nameElement = NameElement(definitionNameNode.value) 932 | 933 | if parentNode is not None: 934 | parentNodeNameHierarchy = self.getNameHierarchyOfNode(parentNode, definitionModulePath) 935 | if parentNodeNameHierarchy is None: 936 | return None 937 | parentNodeNameHierarchy.nameElements.append(nameElement) 938 | return parentNodeNameHierarchy 939 | 940 | nameHierarchy = self.getNameHierarchyFromModuleFilePath(nodeSourceFilePath) 941 | if nameHierarchy is None: 942 | return None 943 | nameHierarchy.nameElements.append(nameElement) 944 | return nameHierarchy 945 | 946 | return None 947 | 948 | 949 | def createScript(self, sourceFilePath): 950 | if sourceFilePath == _virtualFilePath: # we are indexing a provided code snippet 951 | return SourcetrailScript( 952 | source = self.sourceFileContent, 953 | environment = self.environment, 954 | sys_path = self.sysPath 955 | ) 956 | else: # we are indexing a real file 957 | return SourcetrailScript( 958 | source = None, 959 | path = sourceFilePath, 960 | environment = self.environment, 961 | sys_path = self.sysPath 962 | ) 963 | 964 | 965 | class VerboseAstVisitor(AstVisitor): 966 | 967 | def __init__(self, client, evaluator, sourceFilePath, sourceFileContent = None, sysPath = None): 968 | AstVisitor.__init__(self, client, evaluator, sourceFilePath, sourceFileContent, sysPath) 969 | self.indentationLevel = 0 970 | self.indentationToken = '| ' 971 | 972 | 973 | def traverseNode(self, node): 974 | currentString = '' 975 | for i in range(0, self.indentationLevel): 976 | currentString += self.indentationToken 977 | 978 | currentString += node.type 979 | 980 | if hasattr(node, 'value'): 981 | currentString += ' (' + repr(node.value) + ')' 982 | 983 | currentString += ' ' + getSourceRangeOfNode(node).toString() 984 | 985 | print('AST: ' + currentString) 986 | 987 | self.indentationLevel += 1 988 | AstVisitor.traverseNode(self, node) 989 | self.indentationLevel -= 1 990 | 991 | 992 | class AstVisitorClient: 993 | 994 | def __init__(self): 995 | self.indexedFileId = 0 996 | if srctrl.isCompatible(): 997 | print('INFO: Loaded database is compatible.') 998 | else: 999 | print('WARNING: Loaded database is not compatible.') 1000 | print('INFO: Supported DB Version: ' + str(srctrl.getSupportedDatabaseVersion())) 1001 | print('INFO: Loaded DB Version: ' + str(srctrl.getLoadedDatabaseVersion())) 1002 | 1003 | 1004 | def recordSymbol(self, nameHierarchy): 1005 | if nameHierarchy is not None: 1006 | symbolId = srctrl.recordSymbol(nameHierarchy.serialize()) 1007 | return symbolId 1008 | return 0 1009 | 1010 | 1011 | def recordSymbolDefinitionKind(self, symbolId, symbolDefinitionKind): 1012 | srctrl.recordSymbolDefinitionKind(symbolId, symbolDefinitionKind) 1013 | 1014 | 1015 | def recordSymbolKind(self, symbolId, symbolKind): 1016 | srctrl.recordSymbolKind(symbolId, symbolKind) 1017 | 1018 | 1019 | def recordSymbolLocation(self, symbolId, sourceRange): 1020 | srctrl.recordSymbolLocation( 1021 | symbolId, 1022 | self.indexedFileId, 1023 | sourceRange.startLine, 1024 | sourceRange.startColumn, 1025 | sourceRange.endLine, 1026 | sourceRange.endColumn 1027 | ) 1028 | 1029 | 1030 | def recordSymbolScopeLocation(self, symbolId, sourceRange): 1031 | srctrl.recordSymbolScopeLocation( 1032 | symbolId, 1033 | self.indexedFileId, 1034 | sourceRange.startLine, 1035 | sourceRange.startColumn, 1036 | sourceRange.endLine, 1037 | sourceRange.endColumn 1038 | ) 1039 | 1040 | 1041 | def recordSymbolSignatureLocation(self, symbolId, sourceRange): 1042 | srctrl.recordSymbolSignatureLocation( 1043 | symbolId, 1044 | self.indexedFileId, 1045 | sourceRange.startLine, 1046 | sourceRange.startColumn, 1047 | sourceRange.endLine, 1048 | sourceRange.endColumn 1049 | ) 1050 | 1051 | 1052 | def recordReference(self, contextSymbolId, referencedSymbolId, referenceKind): 1053 | return srctrl.recordReference( 1054 | contextSymbolId, 1055 | referencedSymbolId, 1056 | referenceKind 1057 | ) 1058 | 1059 | 1060 | def recordReferenceLocation(self, referenceId, sourceRange): 1061 | srctrl.recordReferenceLocation( 1062 | referenceId, 1063 | self.indexedFileId, 1064 | sourceRange.startLine, 1065 | sourceRange.startColumn, 1066 | sourceRange.endLine, 1067 | sourceRange.endColumn 1068 | ) 1069 | 1070 | 1071 | def recordReferenceIsAmbiguous(self, referenceId): 1072 | return srctrl.recordReferenceIsAmbiguous(referenceId) 1073 | 1074 | 1075 | def recordReferenceToUnsolvedSymhol(self, contextSymbolId, referenceKind, sourceRange): 1076 | return srctrl.recordReferenceToUnsolvedSymhol( 1077 | contextSymbolId, 1078 | referenceKind, 1079 | self.indexedFileId, 1080 | sourceRange.startLine, 1081 | sourceRange.startColumn, 1082 | sourceRange.endLine, 1083 | sourceRange.endColumn 1084 | ) 1085 | 1086 | 1087 | def recordQualifierLocation(self, referencedSymbolId, sourceRange): 1088 | return srctrl.recordQualifierLocation( 1089 | referencedSymbolId, 1090 | self.indexedFileId, 1091 | sourceRange.startLine, 1092 | sourceRange.startColumn, 1093 | sourceRange.endLine, 1094 | sourceRange.endColumn 1095 | ) 1096 | 1097 | 1098 | def recordFile(self, filePath): 1099 | self.indexedFileId = srctrl.recordFile(filePath.replace('\\', '/')) 1100 | srctrl.recordFileLanguage(self.indexedFileId, 'python') 1101 | return self.indexedFileId 1102 | 1103 | 1104 | def recordFileLanguage(self, fileId, languageIdentifier): 1105 | srctrl.recordFileLanguage(fileId, languageIdentifier) 1106 | 1107 | 1108 | def recordLocalSymbol(self, name): 1109 | return srctrl.recordLocalSymbol(name) 1110 | 1111 | 1112 | def recordLocalSymbolLocation(self, localSymbolId, sourceRange): 1113 | srctrl.recordLocalSymbolLocation( 1114 | localSymbolId, 1115 | self.indexedFileId, 1116 | sourceRange.startLine, 1117 | sourceRange.startColumn, 1118 | sourceRange.endLine, 1119 | sourceRange.endColumn 1120 | ) 1121 | 1122 | 1123 | def recordAtomicSourceRange(self, sourceRange): 1124 | srctrl.recordAtomicSourceRange( 1125 | self.indexedFileId, 1126 | sourceRange.startLine, 1127 | sourceRange.startColumn, 1128 | sourceRange.endLine, 1129 | sourceRange.endColumn 1130 | ) 1131 | 1132 | 1133 | def recordError(self, message, fatal, sourceRange): 1134 | srctrl.recordError( 1135 | message, 1136 | fatal, 1137 | self.indexedFileId, 1138 | sourceRange.startLine, 1139 | sourceRange.startColumn, 1140 | sourceRange.endLine, 1141 | sourceRange.endColumn 1142 | ) 1143 | 1144 | 1145 | class SourceRange: 1146 | 1147 | def __init__(self, startLine, startColumn, endLine, endColumn): 1148 | self.startLine = startLine 1149 | self.startColumn = startColumn 1150 | self.endLine = endLine 1151 | self.endColumn = endColumn 1152 | 1153 | 1154 | def toString(self): 1155 | return '[' + str(self.startLine) + ':' + str(self.startColumn) + '|' + str(self.endLine) + ':' + str(self.endColumn) + ']' 1156 | 1157 | 1158 | class NameHierarchy(): 1159 | 1160 | unsolvedSymbolName = 'unsolved symbol' # this name should not collide with normal symbol name, because they cannot contain space characters 1161 | 1162 | def __init__(self, nameElement, delimiter): 1163 | self.nameElements = [] 1164 | if nameElement is not None: 1165 | self.nameElements.append(nameElement) 1166 | self.delimiter = delimiter 1167 | 1168 | def copy(self): 1169 | ret = NameHierarchy(None, self.delimiter) 1170 | for nameElement in self.nameElements: 1171 | ret.nameElements.append(NameElement(nameElement.name, nameElement.prefix, nameElement.postfix)) 1172 | return ret 1173 | 1174 | 1175 | def serialize(self): 1176 | return json.dumps(self, cls=NameHierarchyEncoder) 1177 | 1178 | 1179 | def getDisplayString(self): 1180 | displayString = '' 1181 | isFirst = True 1182 | for nameElement in self.nameElements: 1183 | if not isFirst: 1184 | displayString += self.delimiter 1185 | isFirst = False 1186 | if len(nameElement.prefix) > 0: 1187 | displayString += nameElement.prefix + ' ' 1188 | displayString += nameElement.name 1189 | if len(nameElement.postfix) > 0: 1190 | displayString += nameElement.postfix 1191 | return displayString 1192 | 1193 | 1194 | class NameElement: 1195 | 1196 | def __init__(self, name, prefix = '', postfix = ''): 1197 | self.name = name 1198 | self.prefix = prefix 1199 | self.postfix = postfix 1200 | 1201 | 1202 | class NameHierarchyEncoder(json.JSONEncoder): 1203 | 1204 | def default(self, obj): 1205 | if isinstance(obj, NameHierarchy): 1206 | return { 1207 | 'name_delimiter': obj.delimiter, 1208 | 'name_elements': [nameElement.__dict__ for nameElement in obj.nameElements] 1209 | } 1210 | # Let the base class default method raise the TypeError 1211 | return json.JSONEncoder.default(self, obj) 1212 | 1213 | 1214 | def getNameHierarchyForUnsolvedSymbol(): 1215 | return NameHierarchy(NameElement(NameHierarchy.unsolvedSymbolName), '') 1216 | 1217 | 1218 | def isQualifierNode(node): 1219 | nextNode = getNext(node) 1220 | if nextNode is not None and nextNode.type == 'trailer': 1221 | nextNode = getNext(nextNode) 1222 | if nextNode is not None and nextNode.type == 'operator' and nextNode.value == '.': 1223 | return True 1224 | return False 1225 | 1226 | 1227 | def isCallNode(node): 1228 | nextNode = getNext(node) 1229 | if nextNode is not None and nextNode.type == 'trailer': 1230 | if len(nextNode.children) >= 2 and nextNode.children[0].value == '(' and nextNode.children[-1].value == ')': 1231 | return True 1232 | return False 1233 | 1234 | 1235 | def getSourceRangeOfNode(node): 1236 | startLine, startColumn = node.start_pos 1237 | endLine, endColumn = node.end_pos 1238 | return SourceRange(startLine, startColumn + 1, endLine, endColumn) 1239 | 1240 | 1241 | def getNamedParentNode(node): 1242 | if node is None: 1243 | return None 1244 | 1245 | parentNode = node.parent 1246 | 1247 | if node.type == 'name' and parentNode is not None: 1248 | parentNode = parentNode.parent 1249 | 1250 | while parentNode is not None: 1251 | if getFirstDirectChildWithType(parentNode, 'name') is not None: 1252 | return parentNode 1253 | parentNode = parentNode.parent 1254 | 1255 | return None 1256 | 1257 | 1258 | def getParentWithType(node, type): 1259 | if node == None: 1260 | return None 1261 | parentNode = node.parent 1262 | if parentNode == None: 1263 | return None 1264 | if parentNode.type == type: 1265 | return parentNode 1266 | return getParentWithType(parentNode, type) 1267 | 1268 | 1269 | def getParentWithTypeInList(node, typeList): 1270 | if node == None: 1271 | return None 1272 | parentNode = node.parent 1273 | if parentNode == None: 1274 | return None 1275 | if parentNode.type in typeList: 1276 | return parentNode 1277 | return getParentWithTypeInList(parentNode, typeList) 1278 | 1279 | 1280 | def getFirstDirectChildWithType(node, type): 1281 | for c in node.children: 1282 | if c.type == type: 1283 | return c 1284 | return None 1285 | 1286 | 1287 | def getDirectChildrenWithType(node, type): 1288 | children = [] 1289 | for c in node.children: 1290 | if c.type == type: 1291 | children.append(c) 1292 | return children 1293 | 1294 | 1295 | def getNext(node): 1296 | if hasattr(node, 'children'): 1297 | for c in node.children: 1298 | return c 1299 | 1300 | siblingSource = node 1301 | while siblingSource is not None and siblingSource.parent is not None: 1302 | sibling = siblingSource.get_next_sibling() 1303 | if sibling is not None: 1304 | return sibling 1305 | siblingSource = siblingSource.parent 1306 | 1307 | return None 1308 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | parso==0.7.0 2 | jedi==0.17.2 3 | pyinstaller==3.6 4 | -------------------------------------------------------------------------------- /run.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import indexer 3 | import shallow_indexer 4 | import os 5 | import sourcetraildb as srctrl 6 | 7 | 8 | def main(): 9 | parser = argparse.ArgumentParser(description='Python source code indexer that generates a Sourcetrail compatible database.') 10 | parser.add_argument('--version', action='version', version='SourcetrailPythonIndexer {version}'.format(version=indexer.__version__)) 11 | 12 | subparsers = parser.add_subparsers(title='commands', dest='command') 13 | 14 | indexCommandName = 'index' 15 | parserIndex = subparsers.add_parser( 16 | indexCommandName, 17 | help='Index a Python source file and store the indexed data to a Sourcetrail database file. Run "' + indexCommandName + ' -h" for more info on available arguments.' 18 | ) 19 | parserIndex.add_argument('--source-file-path', help='path to the source file to index', type=str, required=True) 20 | parserIndex.add_argument('--database-file-path', help='path to the generated Sourcetrail database file', type=str, required=True) 21 | parserIndex.add_argument( 22 | '--environment-path', 23 | help='path to the Python executable or the directory that contains the Python environment that should be used to resolve dependencies within the indexed source ' 24 | 'code (if not specified the path to the currently used interpreter is used)', 25 | type=str, 26 | required=False 27 | ) 28 | parserIndex.add_argument('--clear', help='clear the database before indexing', action='store_true', required=False) 29 | parserIndex.add_argument('--verbose', help='enable verbose console output', action='store_true', required=False) 30 | parserIndex.add_argument('--shallow', help='use a quick indexing mode that matches references by name and ignores most of the context', action='store_true', required=False) 31 | 32 | checkEnvironmentCommandName = 'check-environment' 33 | parserCheckEnvironment = subparsers.add_parser( 34 | checkEnvironmentCommandName, 35 | help='Check if the provided path specifies a valid Python environment. This command exits with code "0" if a valid Python environment has been provided, otherwise ' 36 | 'code "1" is returned. Run "' + checkEnvironmentCommandName + ' -h" for more info on available arguments.' 37 | ) 38 | parserCheckEnvironment.add_argument( 39 | '--environment-path', 40 | help='path to the Python executable or the directory that contains the Python environment that should be checked for compatibility', 41 | type=str, 42 | required=True 43 | ) 44 | 45 | args = parser.parse_args() # code exits here for "--version" and "--help" 46 | 47 | if args.command == indexCommandName: 48 | processIndexCommand(args) 49 | elif args.command == checkEnvironmentCommandName: 50 | processCheckEnvironmentCommand(args) 51 | else: 52 | os.write(2, b"Error: No command has been specified.") # write to stderr 53 | return 1 54 | return 0 55 | 56 | 57 | def processIndexCommand(args): 58 | workingDirectory = os.getcwd() 59 | 60 | if not indexer.isSourcetrailDBVersionCompatible(True): 61 | return 62 | 63 | databaseFilePath = args.database_file_path 64 | if not os.path.isabs(databaseFilePath): 65 | databaseFilePath = os.path.join(workingDirectory, databaseFilePath) 66 | 67 | sourceFilePath = args.source_file_path 68 | if not os.path.isabs(sourceFilePath): 69 | sourceFilePath = os.path.join(workingDirectory, sourceFilePath) 70 | 71 | environmentPath = args.environment_path 72 | if environmentPath is not None and not os.path.isabs(environmentPath): 73 | environmentPath = os.path.join(workingDirectory, environmentPath) 74 | 75 | if not srctrl.open(databaseFilePath): 76 | print('ERROR: ' + srctrl.getLastError()) 77 | 78 | if args.clear: 79 | if args.verbose: 80 | print('INFO: Clearing database...') 81 | if not srctrl.clear(): 82 | print('ERROR: ' + srctrl.getLastError()) 83 | else: 84 | if args.verbose: 85 | print('INFO: Clearing done.') 86 | 87 | if args.verbose: 88 | if srctrl.isEmpty(): 89 | print('INFO: Loaded database is empty.') 90 | else: 91 | print('INFO: Loaded database contains data.') 92 | 93 | srctrl.beginTransaction() 94 | indexSourceFile(sourceFilePath, environmentPath, workingDirectory, args.verbose, args.shallow) 95 | srctrl.commitTransaction() 96 | 97 | if not srctrl.close(): 98 | print('ERROR: ' + srctrl.getLastError()) 99 | 100 | 101 | def processCheckEnvironmentCommand(args): 102 | workingDirectory = os.getcwd() 103 | 104 | environmentPath = args.environment_path 105 | if environmentPath is not None and not os.path.isabs(environmentPath): 106 | environmentPath = os.path.join(workingDirectory, environmentPath) 107 | 108 | message = indexer.isValidEnvironment(environmentPath) 109 | if not message: 110 | print('The provided path is a valid Python environment.') 111 | else: 112 | print('The provided path is not a valid Python environment: ' + message) 113 | 114 | 115 | def indexSourceFile(sourceFilePath, environmentPath, workingDirectory, verbose, shallow): 116 | if shallow: 117 | astVisitorClient = shallow_indexer.AstVisitorClient() 118 | shallow_indexer.indexSourceFile(sourceFilePath, environmentPath, workingDirectory, astVisitorClient, verbose) 119 | else: 120 | astVisitorClient = indexer.AstVisitorClient() 121 | indexer.indexSourceFile(sourceFilePath, environmentPath, workingDirectory, astVisitorClient, verbose) 122 | 123 | 124 | if __name__ == '__main__': 125 | main() 126 | -------------------------------------------------------------------------------- /shallow_indexer.py: -------------------------------------------------------------------------------- 1 | import parso 2 | import json 3 | import os 4 | from enum import Enum 5 | import sys 6 | 7 | import sourcetraildb as srctrl 8 | from _version import __version__ 9 | from _version import _sourcetrail_db_version 10 | 11 | from indexer import AstVisitorClient 12 | from indexer import SourceRange 13 | from indexer import NameHierarchy 14 | from indexer import NameElement 15 | from indexer import NameHierarchyEncoder 16 | 17 | 18 | _virtualFilePath = 'virtual_file.py' 19 | 20 | 21 | def isSourcetrailDBVersionCompatible(allowLogging = False): 22 | requiredVersion = _sourcetrail_db_version 23 | 24 | try: 25 | usedVersion = srctrl.getVersionString() 26 | except AttributeError: 27 | if allowLogging: 28 | print('ERROR: Used version of SourcetrailDB is incompatible to what is required by this version of SourcetrailPythonIndexer (' + requiredVersion + ').') 29 | return False 30 | 31 | if usedVersion != requiredVersion: 32 | if allowLogging: 33 | print('ERROR: Used version of SourcetrailDB (' + usedVersion + ') is incompatible to what is required by this version of SourcetrailPythonIndexer (' + requiredVersion + ').') 34 | return False 35 | return True 36 | 37 | 38 | def indexSourceCode(sourceCode, workingDirectory, astVisitorClient, isVerbose, sysPath = None): 39 | sourceFilePath = _virtualFilePath 40 | 41 | moduleNode = parso.parse(sourceCode) 42 | 43 | if (isVerbose): 44 | astVisitor = VerboseAstVisitor(astVisitorClient, sourceFilePath, sourceCode, sysPath) 45 | else: 46 | astVisitor = AstVisitor(astVisitorClient, sourceFilePath, sourceCode, sysPath) 47 | 48 | astVisitor.traverseNode(moduleNode) 49 | 50 | 51 | def indexSourceFile(sourceFilePath, environmentDirectoryPath, workingDirectory, astVisitorClient, isVerbose): 52 | 53 | if isVerbose: 54 | print('INFO: Indexing source file "' + sourceFilePath + '".') 55 | 56 | sourceCode = '' 57 | with open(sourceFilePath, 'r', encoding='utf-8') as input: 58 | sourceCode=input.read() 59 | 60 | moduleNode = parso.parse(sourceCode) 61 | if (isVerbose): 62 | astVisitor = VerboseAstVisitor(astVisitorClient, sourceFilePath) 63 | else: 64 | astVisitor = AstVisitor(astVisitorClient, sourceFilePath) 65 | 66 | astVisitor.traverseNode(moduleNode) 67 | 68 | class ContextType(Enum): 69 | FILE = 1 70 | MODULE = 2 71 | CLASS = 3 72 | FUNCTION = 4 73 | METHOD = 5 74 | 75 | 76 | class ContextInfo: 77 | 78 | def __init__(self, id, contextType, name, node): 79 | self.id = id 80 | self.name = name 81 | self.node = node 82 | self.selfParamName = None 83 | self.localSymbolNames = [] 84 | self.contextType = contextType 85 | 86 | 87 | class ReferenceKindInfo: 88 | 89 | def __init__(self, kind, node): 90 | self.kind = kind 91 | self.node = node 92 | 93 | class AstVisitor: 94 | 95 | def __init__(self, client, sourceFilePath, sourceFileContent = None, sysPath = None): 96 | 97 | self.client = client 98 | 99 | self.sourceFilePath = sourceFilePath 100 | if sourceFilePath != _virtualFilePath: 101 | self.sourceFilePath = os.path.abspath(self.sourceFilePath) 102 | 103 | self.sourceFileName = os.path.split(self.sourceFilePath)[-1] 104 | self.sourceFileContent = sourceFileContent 105 | 106 | packageRootPath = os.path.dirname(self.sourceFilePath) 107 | while os.path.exists(os.path.join(packageRootPath, '__init__.py')): 108 | packageRootPath = os.path.dirname(packageRootPath) 109 | self.sysPath = [packageRootPath] 110 | 111 | if sysPath is not None: 112 | self.sysPath.extend(sysPath) 113 | # else: 114 | # baseSysPath = evaluator.project._get_base_sys_path(self.environment) 115 | # baseSysPath.sort(reverse=True) 116 | # self.sysPath.extend(baseSysPath) 117 | self.sysPath = list(filter(None, self.sysPath)) 118 | 119 | self.contextStack = [] 120 | self.referenceKindStack = [] 121 | 122 | fileId = self.client.recordFile(self.sourceFilePath) 123 | if fileId == 0: 124 | print('ERROR: ' + srctrl.getLastError()) 125 | self.client.recordFileLanguage(fileId, 'python') 126 | self.contextStack.append(ContextInfo(fileId, ContextType.FILE, self.sourceFilePath, None)) 127 | 128 | moduleNameHierarchy = self.getNameHierarchyFromModuleFilePath(self.sourceFilePath) 129 | if moduleNameHierarchy is not None: 130 | moduleId = self.client.recordSymbol(moduleNameHierarchy) 131 | self.client.recordSymbolDefinitionKind(moduleId, srctrl.DEFINITION_EXPLICIT) 132 | self.client.recordSymbolKind(moduleId, srctrl.SYMBOL_MODULE) 133 | self.contextStack.append(ContextInfo(moduleId, ContextType.MODULE, moduleNameHierarchy.getDisplayString(), None)) 134 | 135 | 136 | def traverseNode(self, node): 137 | if node is None: 138 | return 139 | 140 | if node.type == 'classdef': 141 | self.traverseClassdef(node) 142 | elif node.type == 'funcdef': 143 | self.traverseFuncdef(node) 144 | elif node.type == 'param': 145 | self.traverseParam(node) 146 | elif node.type == 'argument': 147 | self.traverseArgument(node) 148 | elif node.type == 'import_from': 149 | self.traverseImportFrom(node) 150 | elif node.type == 'dotted_as_name': 151 | self.traverseDottedAsNameOrImportAsName(node) 152 | elif node.type == 'import_as_name': 153 | self.traverseDottedAsNameOrImportAsName(node) 154 | else: 155 | if node.type == 'name': 156 | self.beginVisitName(node) 157 | elif node.type == 'string': 158 | self.beginVisitString(node) 159 | elif node.type == 'error_leaf': 160 | self.beginVisitErrorLeaf(node) 161 | elif node.type == 'import_name': 162 | self.beginVisitImportName(node) 163 | 164 | if hasattr(node, 'children'): 165 | for c in node.children: 166 | self.traverseNode(c) 167 | 168 | if node.type == 'name': 169 | self.endVisitName(node) 170 | elif node.type == 'string': 171 | self.endVisitString(node) 172 | elif node.type == 'error_leaf': 173 | self.endVisitErrorLeaf(node) 174 | elif node.type == 'import_name': 175 | self.endVisitImportName(node) 176 | 177 | #---------------- 178 | 179 | def traverseClassdef(self, node): 180 | if node is None: 181 | return 182 | 183 | self.beginVisitClassdef(node) 184 | 185 | superArglist = node.get_super_arglist() 186 | if superArglist is not None: 187 | self.beginVisitClassdefSuperArglist(superArglist) 188 | self.traverseNode(superArglist) 189 | self.endVisitClassdefSuperArglist(superArglist) 190 | self.traverseNode(node.get_suite()) 191 | 192 | self.endVisitClassdef(node) 193 | 194 | 195 | def traverseFuncdef(self, node): 196 | if node is None: 197 | return 198 | 199 | self.beginVisitFuncdef(node) 200 | 201 | for n in node.get_params(): 202 | self.traverseNode(n) 203 | self.traverseNode(node.get_suite()) 204 | 205 | self.endVisitFuncdef(node) 206 | 207 | 208 | def traverseParam(self, node): 209 | if node is None: 210 | return 211 | 212 | self.beginVisitParam(node) 213 | 214 | self.traverseNode(node.default) 215 | 216 | self.endVisitParam(node) 217 | 218 | 219 | def traverseArgument(self, node): 220 | if node is None: 221 | return 222 | 223 | childTraverseStartIndex = 0 224 | 225 | for i in range(len(node.children)): 226 | if node.children[i].type == 'operator' and node.children[i].value == '=': 227 | childTraverseStartIndex = i + 1 228 | break 229 | 230 | for i in range(childTraverseStartIndex, len(node.children)): 231 | self.traverseNode(node.children[i]) 232 | 233 | 234 | def traverseImportFrom(self, node): 235 | if node is None: 236 | return 237 | 238 | referenceKindAdded = False 239 | 240 | for c in node.children: 241 | self.traverseNode(c) 242 | if c.type == 'keyword' and c.value == 'import' and not referenceKindAdded: 243 | self.referenceKindStack.append(ReferenceKindInfo(srctrl.REFERENCE_IMPORT, node)) 244 | referenceKindAdded = True 245 | 246 | if referenceKindAdded: 247 | self.referenceKindStack.pop() 248 | 249 | 250 | def traverseDottedAsNameOrImportAsName(self, node): 251 | if node is None: 252 | return 253 | 254 | referenceKindRemoved = False 255 | previousReferenceKind = None 256 | 257 | for c in node.children: 258 | self.traverseNode(c) 259 | if c.type == 'keyword' and c.value == 'as' and not referenceKindRemoved and len(self.referenceKindStack) > 0: 260 | previousReferenceKind = self.referenceKindStack[-1] 261 | self.referenceKindStack.pop() 262 | referenceKindRemoved = True 263 | 264 | if referenceKindRemoved: 265 | self.referenceKindStack.append(previousReferenceKind) 266 | 267 | 268 | #---------------- 269 | 270 | def beginVisitClassdef(self, node): 271 | nameNode = node.name 272 | 273 | symbolNameHierarchy = self.getNameHierarchyOfNode(nameNode) 274 | if symbolNameHierarchy is None: 275 | symbolNameHierarchy = getNameHierarchyForUnsolvedSymbol() 276 | 277 | symbolId = self.client.recordSymbol(symbolNameHierarchy) 278 | self.client.recordSymbolDefinitionKind(symbolId, srctrl.DEFINITION_EXPLICIT) 279 | self.client.recordSymbolKind(symbolId, srctrl.SYMBOL_CLASS) 280 | self.client.recordSymbolLocation(symbolId, getSourceRangeOfNode(nameNode)) 281 | self.client.recordSymbolScopeLocation(symbolId, getSourceRangeOfNode(node)) 282 | self.contextStack.append(ContextInfo(symbolId, ContextType.CLASS, symbolNameHierarchy.getDisplayString(), node)) 283 | 284 | 285 | def endVisitClassdef(self, node): 286 | if len(self.contextStack) > 0: 287 | contextNode = self.contextStack[-1].node 288 | if node == contextNode: 289 | self.contextStack.pop() 290 | 291 | 292 | def beginVisitClassdefSuperArglist(self, node): 293 | self.referenceKindStack.append(ReferenceKindInfo(srctrl.REFERENCE_INHERITANCE, node)) 294 | 295 | 296 | def endVisitClassdefSuperArglist(self, node): 297 | if len(self.referenceKindStack) > 0: 298 | referenceKindNode = self.referenceKindStack[-1].node 299 | if node == referenceKindNode: 300 | self.referenceKindStack.pop() 301 | 302 | 303 | def beginVisitFuncdef(self, node): 304 | nameNode = node.name 305 | 306 | symbolNameHierarchy = self.getNameHierarchyOfNode(nameNode) 307 | if symbolNameHierarchy is None: 308 | symbolNameHierarchy = getNameHierarchyForUnsolvedSymbol() 309 | 310 | selfParamName = None 311 | localSymbolNames = [] 312 | 313 | contextType = ContextType.FUNCTION 314 | symbolKind = srctrl.SYMBOL_FUNCTION 315 | if self.contextStack[-1].contextType == ContextType.CLASS: 316 | contextType = ContextType.METHOD 317 | symbolKind = srctrl.SYMBOL_METHOD 318 | 319 | for param in node.get_params(): 320 | if contextType == ContextType.METHOD and selfParamName is None: 321 | selfParamName = param.name.value 322 | localSymbolNames.append(param.name.value) 323 | 324 | symbolId = self.client.recordSymbol(symbolNameHierarchy) 325 | self.client.recordSymbolDefinitionKind(symbolId, srctrl.DEFINITION_EXPLICIT) 326 | self.client.recordSymbolKind(symbolId, symbolKind) 327 | self.client.recordSymbolLocation(symbolId, getSourceRangeOfNode(nameNode)) 328 | self.client.recordSymbolScopeLocation(symbolId, getSourceRangeOfNode(node)) 329 | contextInfo = ContextInfo(symbolId, contextType, symbolNameHierarchy.getDisplayString(), node) 330 | contextInfo.selfParamName = selfParamName 331 | contextInfo.localSymbolNames.extend(localSymbolNames) 332 | self.contextStack.append(contextInfo) 333 | 334 | 335 | def endVisitFuncdef(self, node): 336 | if len(self.contextStack) > 0: 337 | contextNode = self.contextStack[-1].node 338 | if node == contextNode: 339 | self.contextStack.pop() 340 | 341 | 342 | def beginVisitParam(self, node): 343 | nameNode = node.name 344 | localSymbolId = self.client.recordLocalSymbol(self.getLocalSymbolName(nameNode)) 345 | self.client.recordLocalSymbolLocation(localSymbolId, getSourceRangeOfNode(nameNode)) 346 | 347 | 348 | def endVisitParam(self, node): 349 | if len(self.contextStack) > 0: 350 | contextNode = self.contextStack[-1].node 351 | if node == contextNode: 352 | self.contextStack.pop() 353 | 354 | 355 | def beginVisitName(self, node): 356 | if len(self.contextStack) == 0: 357 | return 358 | 359 | if node.value in ['True', 'False', 'None']: # these are not parsed as "keywords" in Python 2 360 | return 361 | 362 | nextLeafNode = getNextLeaf(node) 363 | 364 | if nextLeafNode is not None and nextLeafNode.type == "operator" and nextLeafNode.value == ".": 365 | symbolNameHierarchy = getNameHierarchyForUnsolvedSymbol() 366 | symbolId = self.client.recordSymbol(symbolNameHierarchy) 367 | self.client.recordQualifierLocation(symbolId, getSourceRangeOfNode(node)) 368 | return 369 | 370 | if len(self.referenceKindStack) > 0 and self.referenceKindStack[-1] is not None: 371 | if self.referenceKindStack[-1].kind == srctrl.REFERENCE_INHERITANCE: 372 | self.client.recordReferenceToUnsolvedSymhol(self.contextStack[-1].id, srctrl.REFERENCE_INHERITANCE, getSourceRangeOfNode(node)) 373 | return 374 | if self.referenceKindStack[-1].kind == srctrl.REFERENCE_IMPORT: 375 | self.client.recordReferenceToUnsolvedSymhol(self.contextStack[-1].id, srctrl.REFERENCE_IMPORT, getSourceRangeOfNode(node)) 376 | return 377 | 378 | referenceKind = srctrl.REFERENCE_USAGE 379 | if nextLeafNode is not None and nextLeafNode.type == "operator" and nextLeafNode.value == "(": 380 | referenceKind = srctrl.REFERENCE_CALL 381 | 382 | if node.is_definition(): 383 | namedDefinitionParentNode = getParentWithTypeInList(node, ['classdef', 'funcdef']) 384 | if namedDefinitionParentNode is not None: 385 | if namedDefinitionParentNode.type in ['classdef']: 386 | if getNamedParentNode(node) == namedDefinitionParentNode: 387 | # definition is not local to some other field instantiation but instead it is a static member variable 388 | # node is the definition of the static member variable 389 | symbolNameHierarchy = self.getNameHierarchyOfNode(node) 390 | if symbolNameHierarchy is not None: 391 | symbolId = self.client.recordSymbol(symbolNameHierarchy) 392 | self.client.recordSymbolKind(symbolId, srctrl.SYMBOL_FIELD) 393 | self.client.recordSymbolDefinitionKind(symbolId, srctrl.DEFINITION_EXPLICIT) 394 | self.client.recordSymbolLocation(symbolId, getSourceRangeOfNode(node)) 395 | return 396 | elif namedDefinitionParentNode.type in ['funcdef']: 397 | # definition may be a non-static member variable 398 | if node.parent is not None and node.parent.type == 'trailer' and node.get_previous_sibling() is not None and node.get_previous_sibling().value == '.': 399 | potentialSelfParamNode = getNamedParentNode(node) 400 | if potentialSelfParamNode is not None and getFirstDirectChildWithType(potentialSelfParamNode, 'name').value == self.contextStack[-1].selfParamName: 401 | # definition is a non-static member variable 402 | symbolNameHierarchy = self.getNameHierarchyOfNode(node) 403 | if symbolNameHierarchy is not None: 404 | sourceRange = getSourceRangeOfNode(node) 405 | 406 | symbolId = self.client.recordSymbol(symbolNameHierarchy) 407 | self.client.recordSymbolKind(symbolId, srctrl.SYMBOL_FIELD) 408 | self.client.recordSymbolDefinitionKind(symbolId, srctrl.DEFINITION_EXPLICIT) 409 | self.client.recordSymbolLocation(symbolId, sourceRange) 410 | 411 | referenceId = self.client.recordReference(self.contextStack[-1].id, symbolId, referenceKind) 412 | self.client.recordReferenceLocation(referenceId, sourceRange) 413 | return 414 | else: 415 | # despite "node.is_definition()" says so, this is just a re-definition of an other class' member 416 | self.client.recordReferenceToUnsolvedSymhol(self.contextStack[-1].id, referenceKind, getSourceRangeOfNode(node)) 417 | return 418 | localSymbolId = self.client.recordLocalSymbol(self.getLocalSymbolName(node)) 419 | self.client.recordLocalSymbolLocation(localSymbolId, getSourceRangeOfNode(node)) 420 | self.contextStack[-1].localSymbolNames.append(node.value) 421 | return 422 | else: 423 | symbolNameHierarchy = self.getNameHierarchyOfNode(node) 424 | if symbolNameHierarchy is not None: 425 | symbolId = self.client.recordSymbol(symbolNameHierarchy) 426 | self.client.recordSymbolKind(symbolId, srctrl.SYMBOL_GLOBAL_VARIABLE) 427 | self.client.recordSymbolDefinitionKind(symbolId, srctrl.DEFINITION_EXPLICIT) 428 | self.client.recordSymbolLocation(symbolId, getSourceRangeOfNode(node)) 429 | return 430 | else: # if not node.is_definition(): 431 | recordLocalSymbolUsage = True 432 | 433 | if node.parent is not None and node.parent.type == 'trailer' and node.get_previous_sibling() is not None and node.get_previous_sibling().value == '.': 434 | recordLocalSymbolUsage = False 435 | 436 | if recordLocalSymbolUsage: 437 | if node.value in self.contextStack[-1].localSymbolNames: 438 | localSymbolId = self.client.recordLocalSymbol(self.getLocalSymbolName(node)) 439 | self.client.recordLocalSymbolLocation(localSymbolId, getSourceRangeOfNode(node)) 440 | return 441 | 442 | # fallback if not returned before 443 | self.client.recordReferenceToUnsolvedSymhol(self.contextStack[-1].id, referenceKind, getSourceRangeOfNode(node)) 444 | 445 | 446 | def endVisitName(self, node): 447 | if len(self.contextStack) > 0: 448 | contextNode = self.contextStack[-1].node 449 | if node == contextNode: 450 | self.contextStack.pop() 451 | 452 | 453 | def beginVisitString(self, node): 454 | sourceRange = getSourceRangeOfNode(node) 455 | if sourceRange.startLine != sourceRange.endLine: 456 | self.client.recordAtomicSourceRange(sourceRange) 457 | 458 | 459 | def endVisitString(self, node): 460 | if len(self.contextStack) > 0: 461 | contextNode = self.contextStack[-1].node 462 | if node == contextNode: 463 | self.contextStack.pop() 464 | 465 | 466 | def beginVisitErrorLeaf(self, node): 467 | self.client.recordError('Unexpected token of type "' + node.token_type + '" encountered.', False, getSourceRangeOfNode(node)) 468 | 469 | 470 | def endVisitErrorLeaf(self, node): 471 | if len(self.contextStack) > 0: 472 | contextNode = self.contextStack[-1].node 473 | if node == contextNode: 474 | self.contextStack.pop() 475 | 476 | 477 | def beginVisitImportName(self, node): 478 | self.referenceKindStack.append(ReferenceKindInfo(srctrl.REFERENCE_IMPORT, node)) 479 | 480 | 481 | def endVisitImportName(self, node): 482 | if len(self.referenceKindStack) > 0: 483 | referenceKindNode = self.referenceKindStack[-1].node 484 | if node == referenceKindNode: 485 | self.referenceKindStack.pop() 486 | 487 | 488 | #---------------- 489 | 490 | def getLocalSymbolName(self, nameNode): 491 | return str(self.contextStack[-1].name) + '<' + nameNode.value + '>' 492 | 493 | 494 | def getNameHierarchyFromModuleFilePath(self, filePath): 495 | if filePath is None: 496 | return None 497 | 498 | if filePath == _virtualFilePath: 499 | return NameHierarchy(NameElement(os.path.splitext(_virtualFilePath)[0]), '.') 500 | 501 | filePath = os.path.abspath(filePath) 502 | # First remove the suffix. 503 | for suffix in ['.py']: 504 | if filePath.endswith(suffix): 505 | filePath = filePath[:-len(suffix)] 506 | break 507 | 508 | for p in self.sysPath: 509 | if filePath.startswith(p): 510 | rest = filePath[len(p):] 511 | if rest.startswith(os.path.sep): 512 | # Remove a slash in cases it's still there. 513 | rest = rest[1:] 514 | if rest: 515 | split = rest.split(os.path.sep) 516 | for string in split: 517 | if not string: 518 | return None 519 | 520 | if split[-1] == '__init__': 521 | split = split[:-1] 522 | 523 | nameHierarchy = None 524 | for namePart in split: 525 | if nameHierarchy is None: 526 | nameHierarchy = NameHierarchy(NameElement(namePart), '.') 527 | else: 528 | nameHierarchy.nameElements.append(NameElement(namePart)) 529 | return nameHierarchy 530 | 531 | return None 532 | 533 | 534 | def getNameHierarchyOfNode(self, node): 535 | if node is None: 536 | return None 537 | 538 | if node.type == 'name': 539 | nameNode = node 540 | else: 541 | nameNode = getFirstDirectChildWithType(node, 'name') 542 | 543 | if nameNode is None: 544 | return None 545 | 546 | parentNode = getParentWithTypeInList(nameNode.parent, ['classdef', 'funcdef']) 547 | 548 | if self.contextStack[-1].contextType == ContextType.METHOD: 549 | potentialSelfNode = getNamedParentNode(node) 550 | if potentialSelfNode is not None: 551 | potentialSelfNameNode = getFirstDirectChildWithType(potentialSelfNode, 'name') 552 | if potentialSelfNameNode is not None and potentialSelfNameNode.value == self.contextStack[-1].selfParamName: 553 | parentNode = self.contextStack[-2].node 554 | 555 | nameElement = NameElement(nameNode.value) 556 | 557 | if parentNode is not None: 558 | parentNodeNameHierarchy = self.getNameHierarchyOfNode(parentNode) 559 | if parentNodeNameHierarchy is None: 560 | return None 561 | parentNodeNameHierarchy.nameElements.append(nameElement) 562 | return parentNodeNameHierarchy 563 | 564 | nameHierarchy = self.getNameHierarchyFromModuleFilePath(self.sourceFilePath) 565 | if nameHierarchy is None: 566 | return None 567 | nameHierarchy.nameElements.append(nameElement) 568 | return nameHierarchy 569 | 570 | return None 571 | 572 | 573 | class VerboseAstVisitor(AstVisitor): 574 | 575 | def __init__(self, client, sourceFilePath, sourceFileContent = None, sysPath = None): 576 | AstVisitor.__init__(self, client, sourceFilePath, sourceFileContent, sysPath) 577 | self.indentationLevel = 0 578 | self.indentationToken = '| ' 579 | 580 | 581 | def traverseNode(self, node): 582 | if node is None: 583 | return 584 | 585 | currentString = '' 586 | for i in range(0, self.indentationLevel): 587 | currentString += self.indentationToken 588 | 589 | currentString += node.type 590 | 591 | if hasattr(node, 'value'): 592 | currentString += ' (' + repr(node.value) + ')' 593 | 594 | currentString += ' ' + getSourceRangeOfNode(node).toString() 595 | 596 | print('AST: ' + currentString) 597 | 598 | self.indentationLevel += 1 599 | AstVisitor.traverseNode(self, node) 600 | self.indentationLevel -= 1 601 | 602 | 603 | def getNameHierarchyForUnsolvedSymbol(): 604 | return NameHierarchy(NameElement(NameHierarchy.unsolvedSymbolName), '') 605 | 606 | 607 | def isQualifierNode(node): 608 | nextNode = getNext(node) 609 | if nextNode is not None and nextNode.type == 'trailer': 610 | nextNode = getNext(nextNode) 611 | if nextNode is not None and nextNode.type == 'operator' and nextNode.value == '.': 612 | return True 613 | return False 614 | 615 | 616 | def getSourceRangeOfNode(node): 617 | startLine, startColumn = node.start_pos 618 | endLine, endColumn = node.end_pos 619 | return SourceRange(startLine, startColumn + 1, endLine, endColumn) 620 | 621 | 622 | def getNamedParentNode(node): 623 | if node is None: 624 | return None 625 | 626 | parentNode = node.parent 627 | 628 | if node.type == 'name' and parentNode is not None: 629 | parentNode = parentNode.parent 630 | 631 | while parentNode is not None: 632 | if getFirstDirectChildWithType(parentNode, 'name') is not None: 633 | return parentNode 634 | parentNode = parentNode.parent 635 | 636 | return None 637 | 638 | 639 | def getParentWithType(node, type): 640 | if node == None: 641 | return None 642 | parentNode = node.parent 643 | if parentNode == None: 644 | return None 645 | if parentNode.type == type: 646 | return parentNode 647 | return getParentWithType(parentNode, type) 648 | 649 | 650 | def getParentWithTypeInList(node, typeList): 651 | if node == None: 652 | return None 653 | parentNode = node.parent 654 | if parentNode == None: 655 | return None 656 | if parentNode.type in typeList: 657 | return parentNode 658 | return getParentWithTypeInList(parentNode, typeList) 659 | 660 | 661 | def getFirstDirectChildWithType(node, type): 662 | for c in node.children: 663 | if c.type == type: 664 | return c 665 | return None 666 | 667 | 668 | def getDirectChildrenWithType(node, type): 669 | children = [] 670 | for c in node.children: 671 | if c.type == type: 672 | children.append(c) 673 | return children 674 | 675 | 676 | def getNext(node): 677 | if hasattr(node, 'children'): 678 | for c in node.children: 679 | return c 680 | 681 | siblingSource = node 682 | while siblingSource is not None and siblingSource.parent is not None: 683 | sibling = siblingSource.get_next_sibling() 684 | if sibling is not None: 685 | return sibling 686 | siblingSource = siblingSource.parent 687 | 688 | return None 689 | 690 | 691 | 692 | def getNextLeaf(node): 693 | nextNode = getNext(node) 694 | while nextNode is not None and hasattr(nextNode, 'children'): 695 | nextNode = getNext(nextNode) 696 | return nextNode 697 | 698 | -------------------------------------------------------------------------------- /test.py: -------------------------------------------------------------------------------- 1 | import indexer 2 | import multiprocessing 3 | import os 4 | import sourcetraildb as srctrl 5 | import sys 6 | import unittest 7 | 8 | 9 | class TestPythonIndexer(unittest.TestCase): 10 | 11 | # Test Recording Symbols 12 | 13 | def test_indexer_records_module_for_source_file(self): 14 | client = self.indexSourceCode( 15 | '\n' 16 | ) 17 | self.assertTrue('MODULE: virtual_file' in client.symbols) 18 | 19 | 20 | def test_indexer_records_module_scope_variable_as_global_variable(self): 21 | client = self.indexSourceCode( 22 | 'foo = 9:\n' 23 | ) 24 | self.assertTrue('GLOBAL_VARIABLE: virtual_file.foo at [1:1|1:3]' in client.symbols) 25 | 26 | 27 | def test_indexer_records_function_definition(self): 28 | client = self.indexSourceCode( 29 | 'def foo():\n' 30 | ' pass\n' 31 | ) 32 | self.assertTrue('FUNCTION: virtual_file.foo at [1:5|1:7] with scope [1:1|3:0]' in client.symbols) 33 | 34 | 35 | def test_indexer_records_class_definition(self): 36 | client = self.indexSourceCode( 37 | 'class Foo:\n' 38 | ' pass\n' 39 | ) 40 | self.assertTrue('CLASS: virtual_file.Foo at [1:7|1:9] with scope [1:1|3:0]' in client.symbols) 41 | 42 | 43 | def test_indexer_records_member_function_definition(self): 44 | client = self.indexSourceCode( 45 | 'class Foo:\n' 46 | ' def bar(self):\n' 47 | ' pass\n' 48 | ) 49 | self.assertTrue('FUNCTION: virtual_file.Foo.bar at [2:6|2:8] with scope [2:2|4:0]' in client.symbols) 50 | 51 | 52 | def test_indexer_records_static_field_definition(self): 53 | client = self.indexSourceCode( 54 | 'class Foo:\n' 55 | ' bar = None\n' 56 | ) 57 | self.assertTrue('FIELD: virtual_file.Foo.bar at [2:2|2:4]' in client.symbols) 58 | 59 | 60 | def test_indexer_records_non_static_field_definition(self): 61 | client = self.indexSourceCode( 62 | 'class Foo:\n' 63 | ' def bar(self):\n' 64 | ' self.x = None\n' 65 | ) 66 | self.assertTrue('FIELD: virtual_file.Foo.x at [3:8|3:8]' in client.symbols) 67 | 68 | 69 | # Test Recording Local Symbols 70 | 71 | def test_indexer_records_usage_of_variable_with_multiple_definitions_as_single_local_symbols(self): 72 | client = self.indexSourceCode( 73 | 'def foo(bar):\n' 74 | ' if bar:\n' 75 | ' baz = 9\n' 76 | ' else:\n' 77 | ' baz = 3\n' 78 | ' return baz\n' 79 | 'foo(True)\n' 80 | 'foo(False)\n' 81 | ) 82 | self.assertTrue('virtual_file.foo at [6:9|6:11]' in client.localSymbols) 83 | self.assertTrue('virtual_file.foo at [6:9|6:11]' in client.localSymbols) 84 | 85 | 86 | def test_indexer_records_function_parameter_as_local_symbol(self): 87 | client = self.indexSourceCode( 88 | 'def foo(bar):\n' 89 | ' pass\n' 90 | ) 91 | self.assertTrue('virtual_file.foo at [1:9|1:11]' in client.localSymbols) 92 | 93 | 94 | def test_indexer_records_usage_of_function_parameter_as_local_symbol(self): 95 | client = self.indexSourceCode( 96 | 'def foo(bar):\n' 97 | ' x = bar\n' 98 | ) 99 | self.assertTrue('virtual_file.foo at [2:6|2:8]' in client.localSymbols) 100 | 101 | 102 | def test_indexer_records_function_scope_variable_as_local_symbol(self): 103 | client = self.indexSourceCode( 104 | 'def foo():\n' 105 | ' x = 5\n' 106 | ) 107 | self.assertTrue('virtual_file.foo at [2:2|2:2]' in client.localSymbols) 108 | 109 | 110 | def test_indexer_records_usage_of_function_scope_variable_as_local_symbol(self): 111 | client = self.indexSourceCode( 112 | 'def foo():\n' 113 | ' x = 5\n' 114 | ' y = x\n' 115 | ) 116 | self.assertTrue('virtual_file.foo at [3:6|3:6]' in client.localSymbols) 117 | 118 | 119 | def test_indexer_records_method_scope_variable_as_local_symbol(self): 120 | client = self.indexSourceCode( 121 | 'class Foo:\n' 122 | ' def bar(self):\n' 123 | ' baz = 6\n' 124 | ) 125 | self.assertTrue('virtual_file.Foo.bar at [3:3|3:5]' in client.localSymbols) 126 | 127 | 128 | # Test Recording References 129 | 130 | def test_indexer_records_import_of_builtin_module(self): 131 | client = self.indexSourceCode( 132 | 'import itertools\n' 133 | ) 134 | self.assertTrue('IMPORT: virtual_file -> itertools at [1:8|1:16]' in client.references) 135 | 136 | 137 | def test_indexer_records_import_of_custom_module(self): 138 | client = self.indexSourceCode( 139 | 'import re\n' 140 | ) 141 | self.assertTrue('IMPORT: virtual_file -> re at [1:8|1:9]' in client.references) 142 | 143 | 144 | def test_indexer_records_import_of_multiple_modules_with_single_import_statement(self): 145 | client = self.indexSourceCode( 146 | 'import itertools, re\n' 147 | ) 148 | self.assertTrue('IMPORT: virtual_file -> itertools at [1:8|1:16]' in client.references) 149 | self.assertTrue('IMPORT: virtual_file -> re at [1:19|1:20]' in client.references) 150 | 151 | 152 | def test_indexer_records_import_of_aliased_module(self): 153 | client = self.indexSourceCode( 154 | 'import itertools as it\n' 155 | ) 156 | self.assertTrue('IMPORT: virtual_file -> itertools at [1:8|1:16]' in client.references) 157 | self.assertTrue('IMPORT: virtual_file -> itertools at [1:21|1:22]' in client.references) 158 | 159 | 160 | def test_indexer_records_import_of_multiple_alised_modules_with_single_import_statement(self): 161 | client = self.indexSourceCode( 162 | 'import itertools as it, re as regex\n' 163 | ) 164 | self.assertTrue('IMPORT: virtual_file -> itertools at [1:8|1:16]' in client.references) 165 | self.assertTrue('IMPORT: virtual_file -> itertools at [1:21|1:22]' in client.references) 166 | self.assertTrue('IMPORT: virtual_file -> re at [1:25|1:26]' in client.references) 167 | self.assertTrue('IMPORT: virtual_file -> re at [1:31|1:35]' in client.references) 168 | 169 | 170 | def test_indexer_records_import_of_function(self): 171 | client = self.indexSourceCode( 172 | 'from re import match\n' 173 | ) 174 | self.assertTrue('USAGE: virtual_file -> re at [1:6|1:7]' in client.references) 175 | self.assertTrue('IMPORT: virtual_file -> re.match at [1:16|1:20]' in client.references) 176 | 177 | 178 | def test_indexer_records_import_of_aliased_function(self): 179 | client = self.indexSourceCode( 180 | 'from re import match as m\n' 181 | ) 182 | self.assertTrue('USAGE: virtual_file -> re at [1:6|1:7]' in client.references) 183 | self.assertTrue('IMPORT: virtual_file -> re.match at [1:16|1:20]' in client.references) 184 | self.assertTrue('IMPORT: virtual_file -> re.match at [1:25|1:25]' in client.references) 185 | 186 | 187 | def test_indexer_records_import_of_multiple_aliased_functions_with_single_import_statement(self): 188 | client = self.indexSourceCode( 189 | 'from re import match as m, escape as e\n' 190 | ) 191 | self.assertTrue('USAGE: virtual_file -> re at [1:6|1:7]' in client.references) 192 | self.assertTrue('IMPORT: virtual_file -> re.match at [1:16|1:20]' in client.references) 193 | self.assertTrue('IMPORT: virtual_file -> re.match at [1:25|1:25]' in client.references) 194 | self.assertTrue('IMPORT: virtual_file -> re.escape at [1:28|1:33]' in client.references) 195 | self.assertTrue('IMPORT: virtual_file -> re.escape at [1:38|1:38]' in client.references) 196 | 197 | 198 | def test_indexer_records_import_of_variable(self): 199 | client = self.indexSourceCode( 200 | 'from sys import float_info\n' 201 | ) 202 | self.assertTrue('USAGE: virtual_file -> sys at [1:6|1:8]' in client.references) 203 | self.assertTrue('IMPORT: virtual_file -> sys.float_info at [1:17|1:26]' in client.references) 204 | 205 | 206 | def test_indexer_records_import_of_aliased_variable(self): 207 | client = self.indexSourceCode( 208 | 'from sys import float_info as FI\n' 209 | ) 210 | self.assertTrue('USAGE: virtual_file -> sys at [1:6|1:8]' in client.references) 211 | self.assertTrue('IMPORT: virtual_file -> sys.float_info at [1:17|1:26]' in client.references) 212 | self.assertTrue('IMPORT: virtual_file -> sys.float_info at [1:31|1:32]' in client.references) 213 | 214 | 215 | def test_indexer_records_import_of_multiple_aliased_variables_with_single_import_statement(self): 216 | client = self.indexSourceCode( 217 | 'from sys import float_info as FI, api_version as AI\n' 218 | ) 219 | self.assertTrue('USAGE: virtual_file -> sys at [1:6|1:8]' in client.references) 220 | self.assertTrue('IMPORT: virtual_file -> sys.float_info at [1:17|1:26]' in client.references) 221 | self.assertTrue('IMPORT: virtual_file -> sys.float_info at [1:31|1:32]' in client.references) 222 | self.assertTrue('IMPORT: virtual_file -> sys.api_version at [1:35|1:45]' in client.references) 223 | self.assertTrue('IMPORT: virtual_file -> sys.api_version at [1:50|1:51]' in client.references) 224 | 225 | 226 | def test_indexer_records_import_of_class(self): 227 | client = self.indexSourceCode( 228 | 'from re import Scanner\n' 229 | ) 230 | self.assertTrue('USAGE: virtual_file -> re at [1:6|1:7]' in client.references) 231 | self.assertTrue('IMPORT: virtual_file -> re.Scanner at [1:16|1:22]' in client.references) 232 | 233 | 234 | def test_indexer_records_import_of_aliased_class(self): 235 | client = self.indexSourceCode( 236 | 'from re import Scanner as Sc\n' 237 | ) 238 | self.assertTrue('USAGE: virtual_file -> re at [1:6|1:7]' in client.references) 239 | self.assertTrue('IMPORT: virtual_file -> re.Scanner at [1:16|1:22]' in client.references) 240 | self.assertTrue('IMPORT: virtual_file -> re.Scanner at [1:27|1:28]' in client.references) 241 | 242 | 243 | def test_indexer_records_import_of_multiple_aliased_classes_with_single_import_statement(self): 244 | client = self.indexSourceCode( 245 | 'from re import Scanner as S1, Scanner as S2\n' 246 | ) 247 | self.assertTrue('USAGE: virtual_file -> re at [1:6|1:7]' in client.references) 248 | self.assertTrue('IMPORT: virtual_file -> re.Scanner at [1:16|1:22]' in client.references) 249 | self.assertTrue('IMPORT: virtual_file -> re.Scanner at [1:27|1:28]' in client.references) 250 | self.assertTrue('IMPORT: virtual_file -> re.Scanner at [1:31|1:37]' in client.references) 251 | self.assertTrue('IMPORT: virtual_file -> re.Scanner at [1:42|1:43]' in client.references) 252 | 253 | 254 | def test_indexer_records_usage_of_imported_module(self): 255 | client = self.indexSourceCode( 256 | 'import sys\n' 257 | 'dir(sys)\n' 258 | ) 259 | self.assertTrue('USAGE: virtual_file -> sys at [2:5|2:7]' in client.references) 260 | 261 | 262 | def test_indexer_records_single_class_inheritance(self): 263 | client = self.indexSourceCode( 264 | 'class Foo:\n' 265 | ' pass\n' 266 | 'class Bar(Foo):\n' 267 | ' pass\n' 268 | ) 269 | self.assertTrue('INHERITANCE: virtual_file.Bar -> virtual_file.Foo at [3:11|3:13]' in client.references) 270 | 271 | 272 | def test_indexer_records_multiple_class_inheritance(self): 273 | client = self.indexSourceCode( 274 | 'class Foo:\n' 275 | ' pass\n' 276 | 'class Bar():\n' 277 | ' pass\n' 278 | 'class Baz(Foo, Bar):\n' 279 | ' pass\n' 280 | ) 281 | self.assertTrue('INHERITANCE: virtual_file.Baz -> virtual_file.Foo at [5:11|5:13]' in client.references) 282 | self.assertTrue('INHERITANCE: virtual_file.Baz -> virtual_file.Bar at [5:16|5:18]' in client.references) 283 | 284 | 285 | def test_indexer_records_override_edge_for_method_defined_in_single_inheritance_parent(self): 286 | client = self.indexSourceCode( 287 | 'class Foo:\n' 288 | ' def my_method(self):\n' 289 | ' pass\n' 290 | 'class Bar(Foo):\n' 291 | ' def my_method(self):\n' 292 | ' pass\n' 293 | ) 294 | self.assertTrue('OVERRIDE: virtual_file.Bar.my_method -> virtual_file.Foo.my_method at [2:6|2:14]' in client.references) 295 | 296 | 297 | def test_indexer_records_override_edge_for_method_defined_in_single_inheritance_grand_parent(self): 298 | client = self.indexSourceCode( 299 | 'class Foo:\n' 300 | ' def my_method(self):\n' 301 | ' pass\n' 302 | 'class Bar(Foo):\n' 303 | ' pass\n' 304 | 'class Baz(Bar):\n' 305 | ' def my_method(self):\n' 306 | ' pass\n' 307 | ) 308 | self.assertTrue('OVERRIDE: virtual_file.Baz.my_method -> virtual_file.Foo.my_method at [2:6|2:14]' in client.references) 309 | 310 | 311 | def test_indexer_records_override_edge_for_method_defined_in_multi_inheritance_parent(self): 312 | client = self.indexSourceCode( 313 | 'class Foo:\n' 314 | ' def my_method(self):\n' 315 | ' pass\n' 316 | 'class Bar:\n' 317 | ' pass\n' 318 | 'class Baz(Foo, Bar):\n' 319 | ' def my_method(self):\n' 320 | ' pass\n' 321 | ) 322 | self.assertTrue('OVERRIDE: virtual_file.Baz.my_method -> virtual_file.Foo.my_method at [2:6|2:14]' in client.references) 323 | 324 | 325 | def test_indexer_records_override_edge_for_method_defined_in_multi_inheritance_diamond_grand_parent(self): 326 | client = self.indexSourceCode( 327 | 'class Foo:\n' 328 | ' def my_method(self):\n' 329 | ' pass\n' 330 | 'class Bar1(Foo):\n' 331 | ' pass\n' 332 | 'class Bar2(Foo):\n' 333 | ' pass\n' 334 | 'class Baz(Bar1, Bar2):\n' 335 | ' def my_method(self):\n' 336 | ' pass\n' 337 | ) 338 | self.assertTrue('OVERRIDE: virtual_file.Baz.my_method -> virtual_file.Foo.my_method at [2:6|2:14]' in client.references) 339 | 340 | 341 | def test_indexer_records_instantiation_of_custom_class(self): 342 | client = self.indexSourceCode( 343 | 'class Bar:\n' 344 | ' pass\n' 345 | '\n' 346 | 'bar = Bar()\n' 347 | ) 348 | self.assertTrue('TYPE_USAGE: virtual_file -> virtual_file.Bar at [4:7|4:9]' in client.references) 349 | 350 | 351 | def test_indexer_records_instantiation_of_environment_class(self): 352 | client = self.indexSourceCode( 353 | 'import itertools\n' 354 | 'itertools.cycle(None)\n' 355 | ) 356 | self.assertTrue('CALL: virtual_file -> itertools.cycle at [2:11|2:15]' in client.references) 357 | 358 | 359 | def test_indexer_records_usage_of_super_keyword(self): 360 | client = self.indexSourceCode( 361 | 'class Foo(object):\n' 362 | ' def foo():\n' 363 | ' pass\n' 364 | '\n' 365 | 'class Bar(Foo):\n' 366 | ' def bar(self):\n' 367 | ' super().foo()\n' 368 | ) 369 | self.assertTrue( 370 | 'TYPE_USAGE: virtual_file.Bar.bar -> builtins.super at [7:3|7:7]' in client.references or 371 | 'CALL: virtual_file.Bar.bar -> builtins.super at [7:3|7:7]' in client.references) # somehow the CI records a "call" reference. maybe that's a python 2 thing... 372 | 373 | 374 | def test_indexer_records_usage_of_builtin_class(self): 375 | client = self.indexSourceCode( 376 | 'foo = str(b"bar")\n' 377 | ) 378 | self.assertTrue('TYPE_USAGE: virtual_file -> builtins.str at [1:7|1:9]' in client.references) 379 | 380 | 381 | def test_indexer_records_call_to_builtin_function(self): 382 | client = self.indexSourceCode( 383 | 'foo = "test string".islower()\n' 384 | ) 385 | self.assertTrue('CALL: virtual_file -> builtins.str.islower at [1:21|1:27]' in client.references) 386 | 387 | 388 | def test_indexer_records_call_to_environment_function(self): 389 | client = self.indexSourceCode( 390 | 'import sys\n' 391 | 'sys.setrecursionlimit(42)\n' 392 | ) 393 | self.assertTrue('CALL: virtual_file -> sys.setrecursionlimit at [2:5|2:21]' in client.references) 394 | 395 | 396 | def test_indexer_records_function_call(self): 397 | client = self.indexSourceCode( 398 | 'def main():\n' 399 | ' pass\n' 400 | '\n' 401 | 'main()\n' 402 | ) 403 | self.assertTrue('CALL: virtual_file -> virtual_file.main at [4:1|4:4]' in client.references) 404 | 405 | 406 | def test_indexer_does_not_record_static_field_initialization_as_usage(self): 407 | client = self.indexSourceCode( 408 | 'class Foo:\n' 409 | ' x = 0\n' 410 | ) 411 | for reference in client.references: 412 | self.assertFalse(reference.startswith('USAGE: virtual_file.Foo -> virtual_file.Foo.x')) 413 | 414 | 415 | def test_indexer_records_usage_of_static_field_via_self(self): 416 | client = self.indexSourceCode( 417 | 'class Foo:\n' 418 | ' x = 0\n' 419 | ' def bar(self):\n' 420 | ' y = self.x\n' 421 | ) 422 | self.assertTrue('USAGE: virtual_file.Foo.bar -> virtual_file.Foo.x at [4:12|4:12]' in client.references) 423 | 424 | 425 | def test_indexer_records_initialization_of_non_static_field_via_self_as_usage(self): 426 | client = self.indexSourceCode( 427 | 'class Foo:\n' 428 | ' def bar(self):\n' 429 | ' self.x = None\n' 430 | ) 431 | self.assertTrue('USAGE: virtual_file.Foo.bar -> virtual_file.Foo.x at [3:8|3:8]' in client.references) 432 | 433 | 434 | # Test Qualifiers 435 | 436 | def test_indexer_records_module_as_qualifier_in_import_statement(self): 437 | client = self.indexSourceCode( 438 | 'import pkg.mod\n', 439 | None, 440 | [os.path.join(os.getcwd(), 'data', 'test')] 441 | ) 442 | self.assertTrue('pkg at [1:8|1:10]' in client.qualifiers) 443 | 444 | 445 | def test_indexer_records_module_as_qualifier_in_expression_statement(self): 446 | client = self.indexSourceCode( 447 | 'import sys\n' 448 | 'print(sys.executable)\n' 449 | ) 450 | self.assertTrue('sys at [2:7|2:9]' in client.qualifiers) 451 | 452 | 453 | def test_indexer_records_class_as_qualifier_in_expression_statement(self): 454 | client = self.indexSourceCode( 455 | 'class Foo:\n' 456 | ' bar = 0\n' 457 | 'baz = Foo.bar\n' 458 | ) 459 | self.assertTrue('virtual_file.Foo at [3:7|3:9]' in client.qualifiers) 460 | 461 | 462 | # Test Package and Module Names 463 | 464 | def test_indexer_resolves_packge_name_relative_to_sys_path(self): #FixmeInShallowMode 465 | client = self.indexSourceCode( 466 | 'import pkg\n' 467 | 'c = pkg.PackageLevelClass()\n' 468 | 'print(c.field)\n', 469 | None, 470 | [os.path.join(os.getcwd(), 'data', 'test')] 471 | ) 472 | self.assertTrue('NON-INDEXED MODULE: pkg' in client.symbols) 473 | self.assertTrue('NON-INDEXED CLASS: pkg.PackageLevelClass' in client.symbols) 474 | self.assertTrue('NON-INDEXED SYMBOL: pkg.PackageLevelClass.field' in client.symbols) 475 | 476 | 477 | def test_indexer_resolves_module_name_relative_to_sys_path(self): #FixmeInShallowMode 478 | client = self.indexSourceCode( 479 | 'import pkg.mod\n' 480 | 'c = pkg.mod.ModuleLevelClass()\n' 481 | 'print(c.field)\n', 482 | None, 483 | [os.path.join(os.getcwd(), 'data', 'test')] 484 | ) 485 | self.assertTrue('NON-INDEXED MODULE: pkg.mod' in client.symbols) 486 | self.assertTrue('NON-INDEXED CLASS: pkg.mod.ModuleLevelClass' in client.symbols) 487 | self.assertTrue('NON-INDEXED SYMBOL: pkg.mod.ModuleLevelClass.field' in client.symbols) 488 | 489 | 490 | # Test Atomic Ranges 491 | 492 | def test_indexer_records_atomic_range_for_multi_line_string(self): 493 | client = self.indexSourceCode( 494 | 'foo = """\n' 495 | '\n' 496 | '"""\n' 497 | ) 498 | self.assertTrue('ATOMIC SOURCE RANGE: [1:7|3:3]' in client.atomicSourceRanges) 499 | 500 | 501 | # Test Recording Errors 502 | 503 | def test_indexer_records_syntax_error(self): 504 | client = self.indexSourceCode( 505 | 'def foo()\n' # missing ':' character 506 | ' pass\n' 507 | ) 508 | self.assertTrue('ERROR: "Unexpected token of type "INDENT" encountered." at [2:2|2:1]' in client.errors) 509 | 510 | 511 | def test_indexer_records_error_if_imported_package_has_not_been_found(self): 512 | client = self.indexSourceCode( 513 | 'import this_is_not_a_real_package\n' 514 | ) 515 | self.assertTrue('ERROR: "Imported symbol named "this_is_not_a_real_package" has not been found." at [1:8|1:33]' in client.errors) 516 | 517 | 518 | def test_indexer_records_error_if_package_of_imported_module_has_not_been_found(self): 519 | client = self.indexSourceCode( 520 | 'import this_is_not_a_real_package.this_is_not_a_real_module\n' 521 | ) 522 | self.assertEqual(len(client.errors), 1) 523 | self.assertTrue('ERROR: "Imported symbol named "this_is_not_a_real_package" has not been found." at [1:8|1:33]' in client.errors) 524 | 525 | 526 | def test_indexer_records_error_if_imported_module_has_not_been_found(self): 527 | client = self.indexSourceCode( 528 | 'import pkg.this_is_not_a_real_module\n', 529 | None, 530 | [os.path.join(os.getcwd(), 'data', 'test')] 531 | ) 532 | self.assertTrue('ERROR: "Imported symbol named "this_is_not_a_real_module" has not been found." at [1:12|1:36]' in client.errors) 533 | 534 | 535 | def test_indexer_records_error_for_each_unsolved_import_in_single_import_statement(self): 536 | client = self.indexSourceCode( 537 | 'import this_is_not_a_real_package, this_is_not_a_real_package.this_is_not_a_real_module, pkg.this_is_not_a_real_module\n', 538 | None, 539 | [os.path.join(os.getcwd(), 'data', 'test')] 540 | ) 541 | self.assertEqual(len(client.errors), 3) 542 | self.assertTrue('ERROR: "Imported symbol named "this_is_not_a_real_package" has not been found." at [1:8|1:33]' in client.errors) 543 | self.assertTrue('ERROR: "Imported symbol named "this_is_not_a_real_package" has not been found." at [1:36|1:61]' in client.errors) 544 | self.assertTrue('ERROR: "Imported symbol named "this_is_not_a_real_module" has not been found." at [1:94|1:118]' in client.errors) 545 | 546 | 547 | def test_indexer_records_error_if_imported_aliased_package_has_not_been_found(self): 548 | client = self.indexSourceCode( 549 | 'import this_is_not_a_real_package as p\n' 550 | ) 551 | self.assertEqual(len(client.errors), 1) 552 | self.assertTrue('ERROR: "Imported symbol named "this_is_not_a_real_package" has not been found." at [1:8|1:33]' in client.errors) 553 | 554 | 555 | def test_indexer_records_error_if_package_of_imported_aliased_module_has_not_been_found(self): 556 | client = self.indexSourceCode( 557 | 'import this_is_not_a_real_package.this_is_not_a_real_module as mod\n' 558 | ) 559 | self.assertEqual(len(client.errors), 1) 560 | self.assertTrue('ERROR: "Imported symbol named "this_is_not_a_real_package" has not been found." at [1:8|1:33]' in client.errors) 561 | 562 | 563 | def test_indexer_records_error_if_imported_aliased_module_has_not_been_found(self): 564 | client = self.indexSourceCode( 565 | 'import pkg.this_is_not_a_real_module as mod\n', 566 | None, 567 | [os.path.join(os.getcwd(), 'data', 'test')] 568 | ) 569 | self.assertEqual(len(client.errors), 1) 570 | self.assertTrue('ERROR: "Imported symbol named "this_is_not_a_real_module" has not been found." at [1:12|1:36]' in client.errors) 571 | 572 | 573 | def test_indexer_records_error_for_each_unsolved_aliased_import_in_single_import_statement(self): 574 | client = self.indexSourceCode( 575 | 'import this_is_not_a_real_package as p, this_is_not_a_real_package.this_is_not_a_real_module as mod1, pkg.this_is_not_a_real_module as mod2\n', 576 | None, 577 | [os.path.join(os.getcwd(), 'data', 'test')] 578 | ) 579 | self.assertEqual(len(client.errors), 3) 580 | self.assertTrue('ERROR: "Imported symbol named "this_is_not_a_real_package" has not been found." at [1:8|1:33]' in client.errors) 581 | self.assertTrue('ERROR: "Imported symbol named "this_is_not_a_real_package" has not been found." at [1:41|1:66]' in client.errors) 582 | self.assertTrue('ERROR: "Imported symbol named "this_is_not_a_real_module" has not been found." at [1:107|1:131]' in client.errors) 583 | 584 | 585 | def test_indexer_records_error_if_package_of_imported_aliased_symbol_has_not_been_found(self): 586 | client = self.indexSourceCode( 587 | 'from this_is_not_a_real_package import this_is_not_a_real_symbol as sym\n' 588 | ) 589 | self.assertEqual(len(client.errors), 1) 590 | self.assertTrue('ERROR: "Imported symbol named "this_is_not_a_real_package" has not been found." at [1:6|1:31]' in client.errors) 591 | 592 | 593 | def test_indexer_records_error_if_package_of_module_of_imported_aliased_symbol_has_not_been_found(self): 594 | client = self.indexSourceCode( 595 | 'from this_is_not_a_real_package.this_is_not_a_real_module import this_is_not_a_real_symbol as sym\n' 596 | ) 597 | self.assertEqual(len(client.errors), 1) 598 | self.assertTrue('ERROR: "Imported symbol named "this_is_not_a_real_package" has not been found." at [1:6|1:31]' in client.errors) 599 | 600 | 601 | def test_indexer_records_error_if_module_of_imported_aliased_symbol_has_not_been_found(self): 602 | client = self.indexSourceCode( 603 | 'from pkg.this_is_not_a_real_module import this_is_not_a_real_symbol as sym\n', 604 | None, 605 | [os.path.join(os.getcwd(), 'data', 'test')] 606 | ) 607 | self.assertEqual(len(client.errors), 1) 608 | self.assertTrue('ERROR: "Imported symbol named "this_is_not_a_real_module" has not been found." at [1:10|1:34]' in client.errors) 609 | 610 | 611 | def test_indexer_records_error_if_imported_aliased_symbol_has_not_been_found(self): 612 | client = self.indexSourceCode( 613 | 'from pkg import this_is_not_a_real_symbol_1 as sym1, this_is_not_a_real_symbol_2 as sym2\n', 614 | None, 615 | [os.path.join(os.getcwd(), 'data', 'test')] 616 | ) 617 | self.assertEqual(len(client.errors), 2) 618 | self.assertTrue('ERROR: "Imported symbol named "this_is_not_a_real_symbol_1" has not been found." at [1:17|1:43]' in client.errors) 619 | self.assertTrue('ERROR: "Imported symbol named "this_is_not_a_real_symbol_2" has not been found." at [1:54|1:80]' in client.errors) 620 | 621 | 622 | # Test GitHub Issues 623 | 624 | def test_issue_6(self): # Member variable has wrong name qualifiers if initialized from function parameter 625 | client = self.indexSourceCode( 626 | 'class Foo:\n' 627 | ' def __init__(self, bar):\n' 628 | ' self.baz = bar\n' 629 | ) 630 | self.assertTrue('FIELD: virtual_file.Foo.baz at [3:8|3:10]' in client.symbols) 631 | 632 | 633 | def test_issue_8(self): # Check if compatible to used SourcetrailDB build 634 | self.assertTrue(indexer.isSourcetrailDBVersionCompatible()) 635 | 636 | 637 | def test_issue_26_1(self): # For-Loop-Iterator not recorded as local symbol 638 | client = self.indexSourceCode( 639 | 'def foo():\n' 640 | ' for n in [1, 2, 3]:\n' 641 | ' print(n)\n' 642 | ) 643 | self.assertTrue('virtual_file.foo at [2:6|2:6]' in client.localSymbols) 644 | self.assertTrue('virtual_file.foo at [3:9|3:9]' in client.localSymbols) 645 | 646 | 647 | def test_issue_26_2(self): # For-Loop-Iterator not recorded as global symbol 648 | client = self.indexSourceCode( 649 | 'for n in [1, 2, 3]:\n' 650 | ' print(n)\n' 651 | ) 652 | self.assertTrue('GLOBAL_VARIABLE: virtual_file.n at [1:5|1:5]' in client.symbols) 653 | self.assertTrue('USAGE: virtual_file -> virtual_file.n at [2:8|2:8]' in client.references) 654 | 655 | 656 | def test_issue_27(self): # Boolean value "True" is recorded as "non-indexed global variable" 657 | client = self.indexSourceCode( 658 | 'class Test():\n' 659 | ' def foo(self, bar=True):\n' 660 | ' pass\n' 661 | ) 662 | self.assertEqual(len(client.references), 0) 663 | 664 | 665 | def test_issue_28(self): # Default argument of function is "unsolved" if it has the same name as the function 666 | client = self.indexSourceCode( 667 | 'foo = 9\n' 668 | 'def foo(baz=foo):\n' 669 | ' pass\n' 670 | ) 671 | self.assertTrue('USAGE: virtual_file.foo -> virtual_file.foo at [2:13|2:15]' in client.references) 672 | 673 | 674 | def test_issue_29(self): # Local symbol not solved correctly if defined in parent scope function 675 | client = self.indexSourceCode( 676 | 'class Foo:\n' 677 | ' def __init__(self):\n' 678 | ' def bar():\n' 679 | ' self.foo = 79\n' 680 | ) 681 | self.assertTrue('virtual_file.Foo.__init__ at [2:15|2:18]' in client.localSymbols) 682 | self.assertTrue('virtual_file.Foo.__init__ at [4:4|4:7]' in client.localSymbols) 683 | 684 | 685 | def test_issue_30(self): # Unable to solve method calls for multiple inheritance if "super()" is used 686 | client = self.indexSourceCode( 687 | 'class Foo:\n' 688 | ' def foo(self):\n' 689 | ' pass\n' 690 | '\n' 691 | 'class Bar:\n' 692 | ' def bar(self):\n' 693 | ' pass\n' 694 | '\n' 695 | 'class Baz(Foo, Bar):\n' 696 | ' def baz(self):\n' 697 | ' super().foo()\n' 698 | ' super().bar()\n' 699 | ) 700 | self.assertTrue('CALL: virtual_file.Baz.baz -> virtual_file.Foo.foo at [11:11|11:13]' in client.references) 701 | self.assertTrue('CALL: virtual_file.Baz.baz -> virtual_file.Bar.bar at [12:11|12:13]' in client.references) 702 | 703 | 704 | def test_issue_34(self): # Context of method that is defined inside a for loop is not solved correctly 705 | client = self.indexSourceCode( 706 | 'def foo():\n' 707 | ' for bar in []:\n' 708 | ' def baz():\n' 709 | ' pass\n' 710 | ) 711 | self.assertTrue('FUNCTION: virtual_file.foo.baz at [3:7|3:9] with scope [3:3|5:0]' in client.symbols) 712 | 713 | 714 | def test_issue_38(self): # Local symbols in field instantiation are recorded as global variables 715 | client = self.indexSourceCode( 716 | 'class Foo:\n' 717 | ' bar = {"a": "b"}\n' 718 | ' baz = dict((k, v) for k, v in bar.items())\n' 719 | ) 720 | self.assertTrue('virtual_file.Foo at [3:24|3:24]' in client.localSymbols) 721 | self.assertTrue('virtual_file.Foo at [3:27|3:27]' in client.localSymbols) 722 | 723 | 724 | def test_issue_40(self): # global symbol defined in iterable argument is recorded as child of "unsolved symbol" 725 | client = self.indexSourceCode( 726 | 'sorted(name[:-3] for name in ["foobar"])\n' 727 | ) 728 | self.assertTrue('GLOBAL_VARIABLE: virtual_file.name at [1:22|1:25]' in client.symbols) 729 | 730 | 731 | def test_issue_41(self): # Indexer fails to record multiple call edges for a single call site 732 | client = self.indexSourceCode( 733 | 'def foo(bar):\n' 734 | ' bar.bar()\n' 735 | '\n' 736 | 'class A:\n' 737 | ' def bar(self):\n' 738 | ' print("A")\n' 739 | '\n' 740 | 'class B:\n' 741 | ' def bar(self):\n' 742 | ' print("B")\n' 743 | '\n' 744 | 'foo(A())\n' 745 | 'foo(B())\n' 746 | ) 747 | self.assertTrue('CALL: virtual_file.foo -> virtual_file.A.bar at [2:6|2:8]' in client.references) 748 | self.assertTrue('CALL: virtual_file.foo -> virtual_file.B.bar at [2:6|2:8]' in client.references) 749 | 750 | 751 | def test_issue_49(self): # Tracking __init__ constructor 752 | client = self.indexSourceCode( 753 | 'class Foo:\n' 754 | ' pass\n' 755 | 'foo = Foo()\n' 756 | ) 757 | self.assertTrue('CALL: virtual_file -> virtual_file.Foo.__init__ at [3:7|3:9]' in client.references) 758 | 759 | 760 | # Utility Functions 761 | 762 | def indexSourceCode(self, sourceCode, environmentPath = None, sysPath = None, verbose = False): 763 | workingDirectory = os.getcwd() 764 | astVisitorClient = TestAstVisitorClient() 765 | 766 | indexer.indexSourceCode( 767 | sourceCode, 768 | workingDirectory, 769 | astVisitorClient, 770 | verbose, 771 | environmentPath, 772 | sysPath 773 | ) 774 | 775 | astVisitorClient.updateReadableOutput() 776 | return astVisitorClient 777 | 778 | 779 | class TestAstVisitorClient(): 780 | 781 | def __init__(self): 782 | self.symbols = [] 783 | self.localSymbols = [] 784 | self.references = [] 785 | self.qualifiers = [] 786 | self.atomicSourceRanges = [] 787 | self.errors = [] 788 | 789 | self.serializedSymbolsToIds = {} 790 | self.symbolIdsToData = {} 791 | self.serializedLocalSymbolsToIds = {} 792 | self.localSymbolIdsToData = {} 793 | self.serializedReferencesToIds = {} 794 | self.referenceIdsToData = {} 795 | self.qualifierIdsToData = {} 796 | 797 | self.nextSymbolId = 1 798 | 799 | 800 | def updateReadableOutput(self): 801 | self.symbols = [] 802 | for key in self.symbolIdsToData: 803 | symbolString = '' 804 | 805 | if 'definition_kind' in self.symbolIdsToData[key]: 806 | symbolString += self.symbolIdsToData[key]['definition_kind'] + ' ' 807 | else: 808 | symbolString += 'NON-INDEXED ' 809 | 810 | if 'symbol_kind' in self.symbolIdsToData[key]: 811 | symbolString += self.symbolIdsToData[key]['symbol_kind'] + ': ' 812 | else: 813 | symbolString += 'SYMBOL: ' 814 | 815 | if 'name' in self.symbolIdsToData[key]: 816 | symbolString += self.symbolIdsToData[key]['name'] 817 | 818 | if 'symbol_location' in self.symbolIdsToData[key]: 819 | symbolString += ' at ' + self.symbolIdsToData[key]['symbol_location'] 820 | 821 | if 'scope_location' in self.symbolIdsToData[key]: 822 | symbolString += ' with scope ' + self.symbolIdsToData[key]['scope_location'] 823 | 824 | if 'signature_location' in self.symbolIdsToData[key]: 825 | symbolString += ' with signature ' + self.symbolIdsToData[key]['signature_location'] 826 | 827 | symbolString = symbolString.strip() 828 | 829 | if symbolString: 830 | self.symbols.append(symbolString) 831 | 832 | self.localSymbols = [] 833 | for key in self.localSymbolIdsToData: 834 | localSymbolString = '' 835 | 836 | if 'name' in self.localSymbolIdsToData[key]: 837 | localSymbolString += self.localSymbolIdsToData[key]['name'] 838 | 839 | if localSymbolString and 'local_symbol_locations' in self.localSymbolIdsToData[key]: 840 | for location in self.localSymbolIdsToData[key]['local_symbol_locations']: 841 | self.localSymbols.append(localSymbolString + ' at ' + location) 842 | 843 | self.references = [] 844 | for key in self.referenceIdsToData: 845 | if 'reference_location' not in self.referenceIdsToData[key] or len(self.referenceIdsToData[key]['reference_location']) == 0: 846 | self.referenceIdsToData[key]['reference_location'].append('') 847 | 848 | for referenceLocation in self.referenceIdsToData[key]['reference_location']: 849 | referenceString = '' 850 | 851 | if 'reference_kind' in self.referenceIdsToData[key]: 852 | referenceString += self.referenceIdsToData[key]['reference_kind'] + ': ' 853 | else: 854 | referenceString += 'UNKNOWN REFERENCE: ' 855 | 856 | if 'context_symbol_id' in self.referenceIdsToData[key] and self.referenceIdsToData[key]['context_symbol_id'] in self.symbolIdsToData: 857 | referenceString += self.symbolIdsToData[self.referenceIdsToData[key]['context_symbol_id']]['name'] 858 | else: 859 | referenceString += 'UNKNOWN SYMBOL' 860 | 861 | referenceString += ' -> ' 862 | 863 | if 'referenced_symbol_id' in self.referenceIdsToData[key] and self.referenceIdsToData[key]['referenced_symbol_id'] in self.symbolIdsToData: 864 | referenceString += self.symbolIdsToData[self.referenceIdsToData[key]['referenced_symbol_id']]['name'] 865 | else: 866 | referenceString += 'UNKNOWN SYMBOL' 867 | 868 | if referenceLocation: 869 | referenceString += ' at ' + referenceLocation 870 | 871 | referenceString = referenceString.strip() 872 | 873 | if referenceString: 874 | self.references.append(referenceString) 875 | 876 | self.qualifiers = [] 877 | for key in self.qualifierIdsToData: 878 | symbolName = 'UNKNOWN SYMBOL' 879 | if 'id' in self.qualifierIdsToData[key] and self.qualifierIdsToData[key]['id'] in self.symbolIdsToData: 880 | symbolName = self.symbolIdsToData[self.qualifierIdsToData[key]['id']]['name'] 881 | 882 | for qualifierLocation in self.qualifierIdsToData[key]['qualifier_locations']: 883 | qualifierString = symbolName 884 | 885 | if qualifierLocation: 886 | qualifierString += ' at ' + qualifierLocation 887 | 888 | if qualifierString: 889 | self.qualifiers.append(qualifierString) 890 | 891 | 892 | def getNextElementId(self): 893 | id = self.nextSymbolId 894 | self.nextSymbolId += 1 895 | return id 896 | 897 | 898 | def recordSymbol(self, nameHierarchy): 899 | serialized = nameHierarchy.serialize() 900 | 901 | if serialized in self.serializedSymbolsToIds: 902 | return self.serializedSymbolsToIds[serialized] 903 | 904 | symbolId = self.getNextElementId() 905 | self.serializedSymbolsToIds[serialized] = symbolId 906 | self.symbolIdsToData[symbolId] = { 907 | 'id': symbolId, 908 | 'name': nameHierarchy.getDisplayString() 909 | } 910 | return symbolId 911 | 912 | 913 | def recordSymbolDefinitionKind(self, symbolId, symbolDefinitionKind): 914 | if symbolId in self.symbolIdsToData: 915 | self.symbolIdsToData[symbolId]['definition_kind'] = symbolDefinitionKindToString(symbolDefinitionKind) 916 | 917 | 918 | def recordSymbolKind(self, symbolId, symbolKind): 919 | if symbolId in self.symbolIdsToData: 920 | self.symbolIdsToData[symbolId]['symbol_kind'] = symbolKindToString(symbolKind) 921 | 922 | 923 | def recordSymbolLocation(self, symbolId, sourceRange): 924 | if symbolId in self.symbolIdsToData: 925 | self.symbolIdsToData[symbolId]['symbol_location'] = sourceRange.toString() 926 | 927 | 928 | def recordSymbolScopeLocation(self, symbolId, sourceRange): 929 | if symbolId in self.symbolIdsToData: 930 | self.symbolIdsToData[symbolId]['scope_location'] = sourceRange.toString() 931 | 932 | 933 | def recordSymbolSignatureLocation(self, symbolId, sourceRange): 934 | if symbolId in self.symbolIdsToData: 935 | self.symbolIdsToData[symbolId]['signature_location'] = sourceRange.toString() 936 | 937 | 938 | def recordReference(self, contextSymbolId, referencedSymbolId, referenceKind): 939 | serialized = str(contextSymbolId) + ' -> ' + str(referencedSymbolId) + '[' + str(referenceKind) + ']' 940 | if serialized in self.serializedReferencesToIds: 941 | return self.serializedReferencesToIds[serialized] 942 | 943 | referenceId = self.getNextElementId() 944 | self.serializedReferencesToIds[serialized] = referenceId 945 | self.referenceIdsToData[referenceId] = { 946 | 'id': referenceId, 947 | 'context_symbol_id': contextSymbolId, 948 | 'referenced_symbol_id': referencedSymbolId, 949 | 'reference_kind': referenceKindToString(referenceKind), 950 | 'reference_location': [] 951 | } 952 | return referenceId 953 | 954 | 955 | def recordReferenceLocation(self, referenceId, sourceRange): 956 | if referenceId in self.referenceIdsToData: 957 | self.referenceIdsToData[referenceId]['reference_location'].append(sourceRange.toString()) 958 | 959 | 960 | def recordReferenceIsAmbiguous(self, referenceId): 961 | raise NotImplementedError 962 | 963 | 964 | def recordReferenceToUnsolvedSymhol(self, contextSymbolId, referenceKind, sourceRange): 965 | referencedSymbolId = self.recordSymbol(indexer.getNameHierarchyForUnsolvedSymbol()) 966 | referenceId = self.recordReference(contextSymbolId, referencedSymbolId, referenceKind) 967 | self.recordReferenceLocation(referenceId, sourceRange) 968 | return referenceId 969 | 970 | 971 | def recordQualifierLocation(self, referencedSymbolId, sourceRange): 972 | if referencedSymbolId not in self.qualifierIdsToData: 973 | self.qualifierIdsToData[referencedSymbolId] = { 974 | 'id': referencedSymbolId, 975 | 'qualifier_locations': [] 976 | } 977 | self.qualifierIdsToData[referencedSymbolId]['qualifier_locations'].append(sourceRange.toString()) 978 | 979 | 980 | def recordFile(self, filePath): 981 | serialized = filePath 982 | 983 | if serialized in self.serializedSymbolsToIds: 984 | return self.serializedSymbolsToIds[serialized] 985 | 986 | fileId = self.getNextElementId() 987 | self.serializedSymbolsToIds[serialized] = fileId 988 | self.symbolIdsToData[fileId] = { 989 | 'id': fileId, 990 | 'name': filePath, 991 | 'symbol_kind': 'FILE', 992 | 'definition_kind': 'INDEXED' 993 | } 994 | return fileId 995 | 996 | 997 | def recordFileLanguage(self, fileId, languageIdentifier): 998 | # FIXME: implement this one! 999 | return 1000 | 1001 | 1002 | def recordLocalSymbol(self, name): 1003 | if name in self.serializedLocalSymbolsToIds: 1004 | return self.serializedLocalSymbolsToIds[name] 1005 | 1006 | localSymbolId = self.getNextElementId() 1007 | self.serializedLocalSymbolsToIds[name] = localSymbolId 1008 | self.localSymbolIdsToData[localSymbolId] = { 1009 | 'id': localSymbolId, 1010 | 'name': name, 1011 | 'local_symbol_locations': [] 1012 | } 1013 | return localSymbolId 1014 | 1015 | 1016 | def recordLocalSymbolLocation(self, localSymbolId, sourceRange): 1017 | if localSymbolId in self.localSymbolIdsToData: 1018 | self.localSymbolIdsToData[localSymbolId]['local_symbol_locations'].append(sourceRange.toString()) 1019 | 1020 | 1021 | def recordAtomicSourceRange(self, sourceRange): 1022 | self.atomicSourceRanges.append('ATOMIC SOURCE RANGE: ' + sourceRange.toString()) 1023 | return 1024 | 1025 | 1026 | def recordError(self, message, fatal, sourceRange): 1027 | errorString = '' 1028 | if fatal: 1029 | errorString += 'FATAL ' 1030 | errorString += 'ERROR: "' + message + '" at ' + sourceRange.toString() 1031 | self.errors.append(errorString) 1032 | return 1033 | 1034 | 1035 | def symbolDefinitionKindToString(symbolDefinitionKind): 1036 | if symbolDefinitionKind == srctrl.SYMBOL_ANNOTATION: 1037 | return 'EXPLICIT' 1038 | if symbolDefinitionKind == srctrl.DEFINITION_IMPLICIT: 1039 | return 'IMPLICIT' 1040 | return '' 1041 | 1042 | def symbolKindToString(symbolKind): 1043 | if symbolKind == srctrl.SYMBOL_TYPE: 1044 | return 'TYPE' 1045 | if symbolKind == srctrl.SYMBOL_BUILTIN_TYPE: 1046 | return 'BUILTIN_TYPE' 1047 | if symbolKind == srctrl.SYMBOL_MODULE: 1048 | return 'MODULE' 1049 | if symbolKind == srctrl.SYMBOL_NAMESPACE: 1050 | return 'NAMESPACE' 1051 | if symbolKind == srctrl.SYMBOL_PACKAGE: 1052 | return 'PACKAGE' 1053 | if symbolKind == srctrl.SYMBOL_STRUCT: 1054 | return 'STRUCT' 1055 | if symbolKind == srctrl.SYMBOL_CLASS: 1056 | return 'CLASS' 1057 | if symbolKind == srctrl.SYMBOL_INTERFACE: 1058 | return 'INTERFACE' 1059 | if symbolKind == srctrl.SYMBOL_ANNOTATION: 1060 | return 'ANNOTATION' 1061 | if symbolKind == srctrl.SYMBOL_GLOBAL_VARIABLE: 1062 | return 'GLOBAL_VARIABLE' 1063 | if symbolKind == srctrl.SYMBOL_FIELD: 1064 | return 'FIELD' 1065 | if symbolKind == srctrl.SYMBOL_FUNCTION: 1066 | return 'FUNCTION' 1067 | if symbolKind == srctrl.SYMBOL_METHOD: 1068 | return 'METHOD' 1069 | if symbolKind == srctrl.SYMBOL_ENUM: 1070 | return 'ENUM' 1071 | if symbolKind == srctrl.SYMBOL_ENUM_CONSTANT: 1072 | return 'ENUM_CONSTANT' 1073 | if symbolKind == srctrl.SYMBOL_TYPEDEF: 1074 | return 'TYPEDEF' 1075 | if symbolKind == srctrl.SYMBOL_TYPE_PARAMETER: 1076 | return 'TYPE_PARAMETER' 1077 | if symbolKind == srctrl.SYMBOL_FILE: 1078 | return 'FILE' 1079 | if symbolKind == srctrl.SYMBOL_MACRO: 1080 | return 'MACRO' 1081 | if symbolKind == srctrl.SYMBOL_UNION: 1082 | return 'UNION' 1083 | return '' 1084 | 1085 | 1086 | def referenceKindToString(referenceKind): 1087 | if referenceKind == srctrl.REFERENCE_TYPE_USAGE: 1088 | return 'TYPE_USAGE' 1089 | if referenceKind == srctrl.REFERENCE_USAGE: 1090 | return 'USAGE' 1091 | if referenceKind == srctrl.REFERENCE_CALL: 1092 | return 'CALL' 1093 | if referenceKind == srctrl.REFERENCE_INHERITANCE: 1094 | return 'INHERITANCE' 1095 | if referenceKind == srctrl.REFERENCE_OVERRIDE: 1096 | return 'OVERRIDE' 1097 | if referenceKind == srctrl.REFERENCE_TYPE_ARGUMENT: 1098 | return 'TYPE_ARGUMENT' 1099 | if referenceKind == srctrl.REFERENCE_TEMPLATE_SPECIALIZATION: 1100 | return 'TEMPLATE_SPECIALIZATION' 1101 | if referenceKind == srctrl.REFERENCE_INCLUDE: 1102 | return 'INCLUDE' 1103 | if referenceKind == srctrl.REFERENCE_IMPORT: 1104 | return 'IMPORT' 1105 | if referenceKind == srctrl.REFERENCE_MACRO_USAGE: 1106 | return 'MACRO_USAGE' 1107 | if referenceKind == srctrl.REFERENCE_ANNOTATION_USAGE: 1108 | return 'ANNOTATION_USAGE' 1109 | return '' 1110 | 1111 | 1112 | if __name__ == '__main__': 1113 | unittest.main(exit=True) 1114 | -------------------------------------------------------------------------------- /test_shallow.py: -------------------------------------------------------------------------------- 1 | import shallow_indexer 2 | import multiprocessing 3 | import os 4 | import sourcetraildb as srctrl 5 | import sys 6 | import unittest 7 | 8 | 9 | class TestPythonIndexer(unittest.TestCase): 10 | 11 | # Test Recording Symbols 12 | 13 | def test_indexer_records_module_for_source_file(self): 14 | client = self.indexSourceCode( 15 | '\n' 16 | ) 17 | self.assertTrue('MODULE: virtual_file' in client.symbols) 18 | 19 | 20 | def test_indexer_records_module_scope_variable_as_global_variable(self): 21 | client = self.indexSourceCode( 22 | 'foo = 9:\n' 23 | ) 24 | self.assertTrue('GLOBAL_VARIABLE: virtual_file.foo at [1:1|1:3]' in client.symbols) 25 | 26 | 27 | def test_indexer_records_function_definition(self): 28 | client = self.indexSourceCode( 29 | 'def foo():\n' 30 | ' pass\n' 31 | ) 32 | self.assertTrue('FUNCTION: virtual_file.foo at [1:5|1:7] with scope [1:1|3:0]' in client.symbols) 33 | 34 | 35 | def test_indexer_records_class_definition(self): 36 | client = self.indexSourceCode( 37 | 'class Foo:\n' 38 | ' pass\n' 39 | ) 40 | self.assertTrue('CLASS: virtual_file.Foo at [1:7|1:9] with scope [1:1|3:0]' in client.symbols) 41 | 42 | 43 | def test_indexer_records_member_function_definition(self): 44 | client = self.indexSourceCode( 45 | 'class Foo:\n' 46 | ' def bar(self):\n' 47 | ' pass\n' 48 | ) 49 | self.assertTrue('METHOD: virtual_file.Foo.bar at [2:6|2:8] with scope [2:2|4:0]' in client.symbols) 50 | 51 | 52 | def test_indexer_records_static_field_definition(self): 53 | client = self.indexSourceCode( 54 | 'class Foo:\n' 55 | ' bar = None\n' 56 | ) 57 | self.assertTrue('FIELD: virtual_file.Foo.bar at [2:2|2:4]' in client.symbols) 58 | 59 | 60 | def test_indexer_records_non_static_field_definition(self): 61 | client = self.indexSourceCode( 62 | 'class Foo:\n' 63 | ' def bar(self):\n' 64 | ' self.x = None\n' 65 | ) 66 | self.assertTrue('FIELD: virtual_file.Foo.x at [3:8|3:8]' in client.symbols) 67 | 68 | 69 | # Test Recording Local Symbols 70 | 71 | def test_indexer_records_usage_of_variable_with_multiple_definitions_as_single_local_symbols(self): 72 | client = self.indexSourceCode( 73 | 'def foo(bar):\n' 74 | ' if bar:\n' 75 | ' baz = 9\n' 76 | ' else:\n' 77 | ' baz = 3\n' 78 | ' return baz\n' 79 | 'foo(True)\n' 80 | 'foo(False)\n' 81 | ) 82 | self.assertTrue('virtual_file.foo at [6:9|6:11]' in client.localSymbols) 83 | self.assertTrue('virtual_file.foo at [6:9|6:11]' in client.localSymbols) 84 | 85 | 86 | def test_indexer_records_function_parameter_as_local_symbol(self): 87 | client = self.indexSourceCode( 88 | 'def foo(bar):\n' 89 | ' pass\n' 90 | ) 91 | self.assertTrue('virtual_file.foo at [1:9|1:11]' in client.localSymbols) 92 | 93 | 94 | def test_indexer_records_usage_of_function_parameter_as_local_symbol(self): 95 | client = self.indexSourceCode( 96 | 'def foo(bar):\n' 97 | ' x = bar\n' 98 | ) 99 | self.assertTrue('virtual_file.foo at [2:6|2:8]' in client.localSymbols) 100 | 101 | 102 | def test_indexer_records_usage_of_function_parameter_following_an_open_brace_as_local_symbol(self): 103 | client = self.indexSourceCode( 104 | 'def foo(first):\n' 105 | ' foo(first)\n' 106 | ) 107 | self.assertTrue('virtual_file.foo at [2:6|2:10]' in client.localSymbols) 108 | 109 | 110 | def test_indexer_records_function_scope_variable_as_local_symbol(self): 111 | client = self.indexSourceCode( 112 | 'def foo():\n' 113 | ' x = 5\n' 114 | ) 115 | self.assertTrue('virtual_file.foo at [2:2|2:2]' in client.localSymbols) 116 | 117 | 118 | def test_indexer_records_usage_of_function_scope_variable_as_local_symbol(self): 119 | client = self.indexSourceCode( 120 | 'def foo():\n' 121 | ' x = 5\n' 122 | ' y = x\n' 123 | ) 124 | self.assertTrue('virtual_file.foo at [3:6|3:6]' in client.localSymbols) 125 | 126 | 127 | def test_indexer_records_method_scope_variable_as_local_symbol(self): 128 | client = self.indexSourceCode( 129 | 'class Foo:\n' 130 | ' def bar(self):\n' 131 | ' baz = 6\n' 132 | ) 133 | self.assertTrue('virtual_file.Foo.bar at [3:3|3:5]' in client.localSymbols) 134 | 135 | 136 | # Test Recording References 137 | 138 | def test_indexer_records_import_of_builtin_module(self): 139 | client = self.indexSourceCode( 140 | 'import itertools\n', 141 | ) 142 | self.assertTrue('IMPORT: virtual_file -> unsolved symbol at [1:8|1:16]' in client.references) 143 | 144 | 145 | def test_indexer_records_import_of_multiple_modules_with_single_import_statement(self): 146 | client = self.indexSourceCode( 147 | 'import itertools, re\n' 148 | ) 149 | self.assertTrue('IMPORT: virtual_file -> unsolved symbol at [1:8|1:16]' in client.references) 150 | self.assertTrue('IMPORT: virtual_file -> unsolved symbol at [1:19|1:20]' in client.references) 151 | 152 | 153 | def test_indexer_records_import_of_aliased_module_as_global_symbol(self): 154 | # this is required to find matching name if "it" is used throughout the file 155 | client = self.indexSourceCode( 156 | 'import itertools as it\n' 157 | ) 158 | self.assertTrue('IMPORT: virtual_file -> unsolved symbol at [1:8|1:16]' in client.references) 159 | self.assertTrue('GLOBAL_VARIABLE: virtual_file.it at [1:21|1:22]' in client.symbols) 160 | 161 | 162 | def test_indexer_records_import_of_multiple_alised_modules_with_single_import_statement_as_global_symbols(self): 163 | client = self.indexSourceCode( 164 | 'import itertools as it, re as regex\n' 165 | ) 166 | self.assertTrue('IMPORT: virtual_file -> unsolved symbol at [1:8|1:16]' in client.references) 167 | self.assertTrue('GLOBAL_VARIABLE: virtual_file.it at [1:21|1:22]' in client.symbols) 168 | self.assertTrue('IMPORT: virtual_file -> unsolved symbol at [1:25|1:26]' in client.references) 169 | self.assertTrue('GLOBAL_VARIABLE: virtual_file.regex at [1:31|1:35]' in client.symbols) 170 | 171 | 172 | def test_indexer_records_import_of_function(self): 173 | client = self.indexSourceCode( 174 | 'from re import match\n' 175 | ) 176 | self.assertTrue('USAGE: virtual_file -> unsolved symbol at [1:6|1:7]' in client.references) 177 | self.assertTrue('IMPORT: virtual_file -> unsolved symbol at [1:16|1:20]' in client.references) 178 | 179 | 180 | def test_indexer_records_import_of_aliased_function(self): 181 | client = self.indexSourceCode( 182 | 'from re import match as m\n' 183 | ) 184 | self.assertTrue('USAGE: virtual_file -> unsolved symbol at [1:6|1:7]' in client.references) 185 | self.assertTrue('IMPORT: virtual_file -> unsolved symbol at [1:16|1:20]' in client.references) 186 | self.assertTrue('GLOBAL_VARIABLE: virtual_file.m at [1:25|1:25]' in client.symbols) 187 | 188 | 189 | def test_indexer_records_import_of_multiple_aliased_functions_with_single_import_statement(self): 190 | client = self.indexSourceCode( 191 | 'from re import match as m, escape as e\n' 192 | ) 193 | self.assertTrue('USAGE: virtual_file -> unsolved symbol at [1:6|1:7]' in client.references) 194 | self.assertTrue('IMPORT: virtual_file -> unsolved symbol at [1:16|1:20]' in client.references) 195 | self.assertTrue('GLOBAL_VARIABLE: virtual_file.m at [1:25|1:25]' in client.symbols) 196 | self.assertTrue('IMPORT: virtual_file -> unsolved symbol at [1:28|1:33]' in client.references) 197 | self.assertTrue('GLOBAL_VARIABLE: virtual_file.e at [1:38|1:38]' in client.symbols) 198 | 199 | 200 | def test_indexer_records_usage_of_imported_module(self): 201 | client = self.indexSourceCode( 202 | 'import sys\n' 203 | 'dir(sys)\n' 204 | ) 205 | self.assertTrue('USAGE: virtual_file -> unsolved symbol at [2:5|2:7]' in client.references) 206 | 207 | 208 | def test_indexer_records_usage_for_access_of_other_class_field(self): 209 | client = self.indexSourceCode( 210 | 'class Foo:\n' 211 | ' value = 0\n' 212 | '\n' 213 | 'class Bar:\n' 214 | ' def baz(self):\n' 215 | ' foo = Foo()\n' 216 | ' foo.value = -10000\n' 217 | ) 218 | self.assertTrue('USAGE: virtual_file.Bar.baz -> unsolved symbol at [7:7|7:11]' in client.references) 219 | 220 | 221 | def test_indexer_records_single_class_inheritence(self): 222 | client = self.indexSourceCode( 223 | 'class Foo:\n' 224 | ' pass\n' 225 | 'class Bar(Foo):\n' 226 | ' pass\n' 227 | ) 228 | self.assertTrue('INHERITANCE: virtual_file.Bar -> unsolved symbol at [3:11|3:13]' in client.references) 229 | 230 | 231 | def test_indexer_records_multiple_class_inheritence(self): 232 | client = self.indexSourceCode( 233 | 'class Foo:\n' 234 | ' pass\n' 235 | 'class Bar():\n' 236 | ' pass\n' 237 | 'class Baz(Foo, Bar):\n' 238 | ' pass\n' 239 | ) 240 | self.assertTrue('INHERITANCE: virtual_file.Baz -> unsolved symbol at [5:11|5:13]' in client.references) 241 | self.assertTrue('INHERITANCE: virtual_file.Baz -> unsolved symbol at [5:16|5:18]' in client.references) 242 | 243 | 244 | def test_indexer_records_instantiation_of_custom_class(self): 245 | client = self.indexSourceCode( 246 | 'class Bar:\n' 247 | ' pass\n' 248 | '\n' 249 | 'bar = Bar()\n' 250 | ) 251 | self.assertTrue('CALL: virtual_file -> unsolved symbol at [4:7|4:9]' in client.references) 252 | 253 | 254 | def test_indexer_records_instantiation_of_environment_class(self): 255 | client = self.indexSourceCode( 256 | 'import itertools\n' 257 | 'itertools.cycle(None)\n' 258 | ) 259 | self.assertTrue('CALL: virtual_file -> unsolved symbol at [2:11|2:15]' in client.references) 260 | 261 | 262 | def test_indexer_records_usage_of_super_keyword(self): 263 | client = self.indexSourceCode( 264 | 'class Foo(object):\n' 265 | ' def foo():\n' 266 | ' pass\n' 267 | '\n' 268 | 'class Bar(Foo):\n' 269 | ' def bar(self):\n' 270 | ' super().foo()\n' 271 | ) 272 | self.assertTrue('CALL: virtual_file.Bar.bar -> unsolved symbol at [7:3|7:7]' in client.references) 273 | 274 | 275 | def test_indexer_records_usage_of_builtin_class(self): 276 | client = self.indexSourceCode( 277 | 'foo = str(b"bar")\n' 278 | ) 279 | self.assertTrue('CALL: virtual_file -> unsolved symbol at [1:7|1:9]' in client.references) 280 | 281 | 282 | def test_indexer_records_call_to_builtin_function(self): 283 | client = self.indexSourceCode( 284 | 'foo = "test string".islower()\n' 285 | ) 286 | self.assertTrue('CALL: virtual_file -> unsolved symbol at [1:21|1:27]' in client.references) 287 | 288 | 289 | def test_indexer_records_function_call(self): 290 | client = self.indexSourceCode( 291 | 'def main():\n' 292 | ' pass\n' 293 | '\n' 294 | 'main()\n' 295 | ) 296 | self.assertTrue('CALL: virtual_file -> unsolved symbol at [4:1|4:4]' in client.references) 297 | 298 | 299 | def test_indexer_does_not_record_static_field_initialization_as_usage(self): 300 | client = self.indexSourceCode( 301 | 'class Foo:\n' 302 | ' x = 0\n' 303 | ) 304 | for reference in client.references: 305 | self.assertFalse(reference.startswith('USAGE: virtual_file.Foo -> unsolved symbol')) 306 | 307 | 308 | def test_indexer_records_usage_of_static_field_via_self(self): 309 | client = self.indexSourceCode( 310 | 'class Foo:\n' 311 | ' x = 0\n' 312 | ' def bar(self):\n' 313 | ' y = self.x\n' 314 | ) 315 | self.assertTrue('USAGE: virtual_file.Foo.bar -> unsolved symbol at [4:12|4:12]' in client.references) 316 | 317 | 318 | def test_indexer_records_initialization_of_non_static_field_via_self_as_usage(self): 319 | client = self.indexSourceCode( 320 | 'class Foo:\n' 321 | ' def bar(self):\n' 322 | ' self.x = None\n', 323 | ) 324 | self.assertTrue('USAGE: virtual_file.Foo.bar -> virtual_file.Foo.x at [3:8|3:8]' in client.references) 325 | 326 | 327 | # Test Qualifiers 328 | 329 | def test_indexer_records_module_as_qualifier_in_import_statement(self): 330 | client = self.indexSourceCode( 331 | 'import pkg.mod\n', 332 | [os.path.join(os.getcwd(), 'data', 'test')] 333 | ) 334 | self.assertTrue('unsolved symbol at [1:8|1:10]' in client.qualifiers) 335 | 336 | 337 | def test_indexer_records_module_as_qualifier_in_expression_statement(self): 338 | client = self.indexSourceCode( 339 | 'import sys\n' 340 | 'print(sys.executable)\n' 341 | ) 342 | self.assertTrue('unsolved symbol at [2:7|2:9]' in client.qualifiers) 343 | 344 | 345 | def test_indexer_records_class_as_qualifier_in_expression_statement(self): 346 | client = self.indexSourceCode( 347 | 'class Foo:\n' 348 | ' bar = 0\n' 349 | 'baz = Foo.bar\n' 350 | ) 351 | self.assertTrue('unsolved symbol at [3:7|3:9]' in client.qualifiers) 352 | 353 | 354 | # Test Atomic Ranges 355 | 356 | def test_indexer_records_atomic_range_for_multi_line_string(self): 357 | client = self.indexSourceCode( 358 | 'foo = """\n' 359 | '\n' 360 | '"""\n' 361 | ) 362 | self.assertTrue('ATOMIC SOURCE RANGE: [1:7|3:3]' in client.atomicSourceRanges) 363 | 364 | 365 | # Test Recording Errors 366 | 367 | def test_indexer_records_syntax_error(self): 368 | client = self.indexSourceCode( 369 | 'def foo()\n' # missing ':' character 370 | ' pass\n' 371 | ) 372 | self.assertTrue('ERROR: "Unexpected token of type "INDENT" encountered." at [2:2|2:1]' in client.errors) 373 | 374 | 375 | # Utility Functions 376 | 377 | def indexSourceCode(self, sourceCode, sysPath = None, verbose = False): 378 | workingDirectory = os.getcwd() 379 | astVisitorClient = TestAstVisitorClient() 380 | 381 | shallow_indexer.indexSourceCode( 382 | sourceCode, 383 | workingDirectory, 384 | astVisitorClient, 385 | verbose, 386 | sysPath 387 | ) 388 | 389 | astVisitorClient.updateReadableOutput() 390 | return astVisitorClient 391 | 392 | 393 | class TestAstVisitorClient(): 394 | 395 | def __init__(self): 396 | self.symbols = [] 397 | self.localSymbols = [] 398 | self.references = [] 399 | self.qualifiers = [] 400 | self.atomicSourceRanges = [] 401 | self.errors = [] 402 | 403 | self.serializedSymbolsToIds = {} 404 | self.symbolIdsToData = {} 405 | self.serializedLocalSymbolsToIds = {} 406 | self.localSymbolIdsToData = {} 407 | self.serializedReferencesToIds = {} 408 | self.referenceIdsToData = {} 409 | self.qualifierIdsToData = {} 410 | 411 | self.nextSymbolId = 1 412 | 413 | 414 | def updateReadableOutput(self): 415 | self.symbols = [] 416 | for key in self.symbolIdsToData: 417 | symbolString = '' 418 | 419 | if 'definition_kind' in self.symbolIdsToData[key]: 420 | symbolString += self.symbolIdsToData[key]['definition_kind'] + ' ' 421 | else: 422 | symbolString += 'NON-INDEXED ' 423 | 424 | if 'symbol_kind' in self.symbolIdsToData[key]: 425 | symbolString += self.symbolIdsToData[key]['symbol_kind'] + ': ' 426 | else: 427 | symbolString += 'SYMBOL: ' 428 | 429 | if 'name' in self.symbolIdsToData[key]: 430 | symbolString += self.symbolIdsToData[key]['name'] 431 | 432 | if 'symbol_location' in self.symbolIdsToData[key]: 433 | symbolString += ' at ' + self.symbolIdsToData[key]['symbol_location'] 434 | 435 | if 'scope_location' in self.symbolIdsToData[key]: 436 | symbolString += ' with scope ' + self.symbolIdsToData[key]['scope_location'] 437 | 438 | if 'signature_location' in self.symbolIdsToData[key]: 439 | symbolString += ' with signature ' + self.symbolIdsToData[key]['signature_location'] 440 | 441 | symbolString = symbolString.strip() 442 | 443 | if symbolString: 444 | self.symbols.append(symbolString) 445 | 446 | self.localSymbols = [] 447 | for key in self.localSymbolIdsToData: 448 | localSymbolString = '' 449 | 450 | if 'name' in self.localSymbolIdsToData[key]: 451 | localSymbolString += self.localSymbolIdsToData[key]['name'] 452 | 453 | if localSymbolString and 'local_symbol_locations' in self.localSymbolIdsToData[key]: 454 | for location in self.localSymbolIdsToData[key]['local_symbol_locations']: 455 | self.localSymbols.append(localSymbolString + ' at ' + location) 456 | 457 | self.references = [] 458 | for key in self.referenceIdsToData: 459 | if 'reference_location' not in self.referenceIdsToData[key] or len(self.referenceIdsToData[key]['reference_location']) == 0: 460 | self.referenceIdsToData[key]['reference_location'].append('') 461 | 462 | for referenceLocation in self.referenceIdsToData[key]['reference_location']: 463 | referenceString = '' 464 | 465 | if 'reference_kind' in self.referenceIdsToData[key]: 466 | referenceString += self.referenceIdsToData[key]['reference_kind'] + ': ' 467 | else: 468 | referenceString += 'UNKNOWN REFERENCE: ' 469 | 470 | if 'context_symbol_id' in self.referenceIdsToData[key] and self.referenceIdsToData[key]['context_symbol_id'] in self.symbolIdsToData: 471 | referenceString += self.symbolIdsToData[self.referenceIdsToData[key]['context_symbol_id']]['name'] 472 | else: 473 | referenceString += 'UNKNOWN SYMBOL' 474 | 475 | referenceString += ' -> ' 476 | 477 | if 'referenced_symbol_id' in self.referenceIdsToData[key] and self.referenceIdsToData[key]['referenced_symbol_id'] in self.symbolIdsToData: 478 | referenceString += self.symbolIdsToData[self.referenceIdsToData[key]['referenced_symbol_id']]['name'] 479 | else: 480 | referenceString += 'UNKNOWN SYMBOL' 481 | 482 | if referenceLocation: 483 | referenceString += ' at ' + referenceLocation 484 | 485 | referenceString = referenceString.strip() 486 | 487 | if referenceString: 488 | self.references.append(referenceString) 489 | 490 | self.qualifiers = [] 491 | for key in self.qualifierIdsToData: 492 | symbolName = 'UNKNOWN SYMBOL' 493 | if 'id' in self.qualifierIdsToData[key] and self.qualifierIdsToData[key]['id'] in self.symbolIdsToData: 494 | symbolName = self.symbolIdsToData[self.qualifierIdsToData[key]['id']]['name'] 495 | 496 | for qualifierLocation in self.qualifierIdsToData[key]['qualifier_locations']: 497 | qualifierString = symbolName 498 | 499 | if qualifierLocation: 500 | qualifierString += ' at ' + qualifierLocation 501 | 502 | if qualifierString: 503 | self.qualifiers.append(qualifierString) 504 | 505 | 506 | def getNextElementId(self): 507 | id = self.nextSymbolId 508 | self.nextSymbolId += 1 509 | return id 510 | 511 | 512 | def recordSymbol(self, nameHierarchy): 513 | serialized = nameHierarchy.serialize() 514 | 515 | if serialized in self.serializedSymbolsToIds: 516 | return self.serializedSymbolsToIds[serialized] 517 | 518 | symbolId = self.getNextElementId() 519 | self.serializedSymbolsToIds[serialized] = symbolId 520 | self.symbolIdsToData[symbolId] = { 521 | 'id': symbolId, 522 | 'name': nameHierarchy.getDisplayString() 523 | } 524 | return symbolId 525 | 526 | 527 | def recordSymbolDefinitionKind(self, symbolId, symbolDefinitionKind): 528 | if symbolId in self.symbolIdsToData: 529 | self.symbolIdsToData[symbolId]['definition_kind'] = symbolDefinitionKindToString(symbolDefinitionKind) 530 | 531 | 532 | def recordSymbolKind(self, symbolId, symbolKind): 533 | if symbolId in self.symbolIdsToData: 534 | self.symbolIdsToData[symbolId]['symbol_kind'] = symbolKindToString(symbolKind) 535 | 536 | 537 | def recordSymbolLocation(self, symbolId, sourceRange): 538 | if symbolId in self.symbolIdsToData: 539 | self.symbolIdsToData[symbolId]['symbol_location'] = sourceRange.toString() 540 | 541 | 542 | def recordSymbolScopeLocation(self, symbolId, sourceRange): 543 | if symbolId in self.symbolIdsToData: 544 | self.symbolIdsToData[symbolId]['scope_location'] = sourceRange.toString() 545 | 546 | 547 | def recordSymbolSignatureLocation(self, symbolId, sourceRange): 548 | if symbolId in self.symbolIdsToData: 549 | self.symbolIdsToData[symbolId]['signature_location'] = sourceRange.toString() 550 | 551 | 552 | def recordReference(self, contextSymbolId, referencedSymbolId, referenceKind): 553 | serialized = str(contextSymbolId) + ' -> ' + str(referencedSymbolId) + '[' + str(referenceKind) + ']' 554 | if serialized in self.serializedReferencesToIds: 555 | return self.serializedReferencesToIds[serialized] 556 | 557 | referenceId = self.getNextElementId() 558 | self.serializedReferencesToIds[serialized] = referenceId 559 | self.referenceIdsToData[referenceId] = { 560 | 'id': referenceId, 561 | 'context_symbol_id': contextSymbolId, 562 | 'referenced_symbol_id': referencedSymbolId, 563 | 'reference_kind': referenceKindToString(referenceKind), 564 | 'reference_location': [] 565 | } 566 | return referenceId 567 | 568 | 569 | def recordReferenceLocation(self, referenceId, sourceRange): 570 | if referenceId in self.referenceIdsToData: 571 | self.referenceIdsToData[referenceId]['reference_location'].append(sourceRange.toString()) 572 | 573 | 574 | def recordReferenceIsAmbiguous(self, referenceId): 575 | raise NotImplementedError 576 | 577 | 578 | def recordReferenceToUnsolvedSymhol(self, contextSymbolId, referenceKind, sourceRange): 579 | referencedSymbolId = self.recordSymbol(shallow_indexer.getNameHierarchyForUnsolvedSymbol()) 580 | referenceId = self.recordReference(contextSymbolId, referencedSymbolId, referenceKind) 581 | self.recordReferenceLocation(referenceId, sourceRange) 582 | return referenceId 583 | 584 | 585 | def recordQualifierLocation(self, referencedSymbolId, sourceRange): 586 | if referencedSymbolId not in self.qualifierIdsToData: 587 | self.qualifierIdsToData[referencedSymbolId] = { 588 | 'id': referencedSymbolId, 589 | 'qualifier_locations': [] 590 | } 591 | self.qualifierIdsToData[referencedSymbolId]['qualifier_locations'].append(sourceRange.toString()) 592 | 593 | 594 | def recordFile(self, filePath): 595 | serialized = filePath 596 | 597 | if serialized in self.serializedSymbolsToIds: 598 | return self.serializedSymbolsToIds[serialized] 599 | 600 | fileId = self.getNextElementId() 601 | self.serializedSymbolsToIds[serialized] = fileId 602 | self.symbolIdsToData[fileId] = { 603 | 'id': fileId, 604 | 'name': filePath, 605 | 'symbol_kind': 'FILE', 606 | 'definition_kind': 'INDEXED' 607 | } 608 | return fileId 609 | 610 | 611 | def recordFileLanguage(self, fileId, languageIdentifier): 612 | # FIXME: implement this one! 613 | return 614 | 615 | 616 | def recordLocalSymbol(self, name): 617 | if name in self.serializedLocalSymbolsToIds: 618 | return self.serializedLocalSymbolsToIds[name] 619 | 620 | localSymbolId = self.getNextElementId() 621 | self.serializedLocalSymbolsToIds[name] = localSymbolId 622 | self.localSymbolIdsToData[localSymbolId] = { 623 | 'id': localSymbolId, 624 | 'name': name, 625 | 'local_symbol_locations': [] 626 | } 627 | return localSymbolId 628 | 629 | 630 | def recordLocalSymbolLocation(self, localSymbolId, sourceRange): 631 | if localSymbolId in self.localSymbolIdsToData: 632 | self.localSymbolIdsToData[localSymbolId]['local_symbol_locations'].append(sourceRange.toString()) 633 | 634 | 635 | def recordAtomicSourceRange(self, sourceRange): 636 | self.atomicSourceRanges.append('ATOMIC SOURCE RANGE: ' + sourceRange.toString()) 637 | return 638 | 639 | 640 | def recordError(self, message, fatal, sourceRange): 641 | errorString = '' 642 | if fatal: 643 | errorString += 'FATAL ' 644 | errorString += 'ERROR: "' + message + '" at ' + sourceRange.toString() 645 | self.errors.append(errorString) 646 | return 647 | 648 | 649 | def symbolDefinitionKindToString(symbolDefinitionKind): 650 | if symbolDefinitionKind == srctrl.SYMBOL_ANNOTATION: 651 | return 'EXPLICIT' 652 | if symbolDefinitionKind == srctrl.DEFINITION_IMPLICIT: 653 | return 'IMPLICIT' 654 | return '' 655 | 656 | def symbolKindToString(symbolKind): 657 | if symbolKind == srctrl.SYMBOL_TYPE: 658 | return 'TYPE' 659 | if symbolKind == srctrl.SYMBOL_BUILTIN_TYPE: 660 | return 'BUILTIN_TYPE' 661 | if symbolKind == srctrl.SYMBOL_MODULE: 662 | return 'MODULE' 663 | if symbolKind == srctrl.SYMBOL_NAMESPACE: 664 | return 'NAMESPACE' 665 | if symbolKind == srctrl.SYMBOL_PACKAGE: 666 | return 'PACKAGE' 667 | if symbolKind == srctrl.SYMBOL_STRUCT: 668 | return 'STRUCT' 669 | if symbolKind == srctrl.SYMBOL_CLASS: 670 | return 'CLASS' 671 | if symbolKind == srctrl.SYMBOL_INTERFACE: 672 | return 'INTERFACE' 673 | if symbolKind == srctrl.SYMBOL_ANNOTATION: 674 | return 'ANNOTATION' 675 | if symbolKind == srctrl.SYMBOL_GLOBAL_VARIABLE: 676 | return 'GLOBAL_VARIABLE' 677 | if symbolKind == srctrl.SYMBOL_FIELD: 678 | return 'FIELD' 679 | if symbolKind == srctrl.SYMBOL_FUNCTION: 680 | return 'FUNCTION' 681 | if symbolKind == srctrl.SYMBOL_METHOD: 682 | return 'METHOD' 683 | if symbolKind == srctrl.SYMBOL_ENUM: 684 | return 'ENUM' 685 | if symbolKind == srctrl.SYMBOL_ENUM_CONSTANT: 686 | return 'ENUM_CONSTANT' 687 | if symbolKind == srctrl.SYMBOL_TYPEDEF: 688 | return 'TYPEDEF' 689 | if symbolKind == srctrl.SYMBOL_TYPE_PARAMETER: 690 | return 'TYPE_PARAMETER' 691 | if symbolKind == srctrl.SYMBOL_FILE: 692 | return 'FILE' 693 | if symbolKind == srctrl.SYMBOL_MACRO: 694 | return 'MACRO' 695 | if symbolKind == srctrl.SYMBOL_UNION: 696 | return 'UNION' 697 | return '' 698 | 699 | 700 | def referenceKindToString(referenceKind): 701 | if referenceKind == srctrl.REFERENCE_TYPE_USAGE: 702 | return 'TYPE_USAGE' 703 | if referenceKind == srctrl.REFERENCE_USAGE: 704 | return 'USAGE' 705 | if referenceKind == srctrl.REFERENCE_CALL: 706 | return 'CALL' 707 | if referenceKind == srctrl.REFERENCE_INHERITANCE: 708 | return 'INHERITANCE' 709 | if referenceKind == srctrl.REFERENCE_OVERRIDE: 710 | return 'OVERRIDE' 711 | if referenceKind == srctrl.REFERENCE_TYPE_ARGUMENT: 712 | return 'TYPE_ARGUMENT' 713 | if referenceKind == srctrl.REFERENCE_TEMPLATE_SPECIALIZATION: 714 | return 'TEMPLATE_SPECIALIZATION' 715 | if referenceKind == srctrl.REFERENCE_INCLUDE: 716 | return 'INCLUDE' 717 | if referenceKind == srctrl.REFERENCE_IMPORT: 718 | return 'IMPORT' 719 | if referenceKind == srctrl.REFERENCE_MACRO_USAGE: 720 | return 'MACRO_USAGE' 721 | if referenceKind == srctrl.REFERENCE_ANNOTATION_USAGE: 722 | return 'ANNOTATION_USAGE' 723 | return '' 724 | 725 | 726 | if __name__ == '__main__': 727 | unittest.main(exit=True) 728 | --------------------------------------------------------------------------------