Showing preview only (3,472K chars total). Download the full file or copy to clipboard to get everything.
Repository: google/grumpy
Branch: master
Commit: 3ec87959189c
Files: 295
Total size: 3.3 MB
Directory structure:
gitextract_ey0d_gsm/
├── .gitignore
├── .pylintrc
├── .travis.yml
├── AUTHORS.md
├── CONTRIBUTING.md
├── LICENSE
├── Makefile
├── README.md
├── __init__.py
├── benchmarks/
│ ├── bm_call_method.py
│ ├── bm_call_simple.py
│ ├── call.py
│ ├── comprehension.py
│ ├── concurrent.py
│ ├── dict.py
│ ├── generator.py
│ ├── list.py
│ ├── loop.py
│ └── tuple.py
├── compiler/
│ ├── __init__.py
│ ├── block.py
│ ├── block_test.py
│ ├── expr.py
│ ├── expr_visitor.py
│ ├── expr_visitor_test.py
│ ├── imputil.py
│ ├── imputil_test.py
│ ├── shard_test.py
│ ├── stmt.py
│ ├── stmt_test.py
│ ├── util.py
│ └── util_test.py
├── lib/
│ ├── README.md
│ ├── __builtin__.py
│ ├── _random.py
│ ├── _syscall.py
│ ├── errno.py
│ ├── exceptions.py
│ ├── itertools.py
│ ├── itertools_test.py
│ ├── math.py
│ ├── math_test.py
│ ├── os/
│ │ ├── __init__.py
│ │ ├── path.py
│ │ └── path_test.py
│ ├── os_test.py
│ ├── random_test.py
│ ├── select_.py
│ ├── stat.py
│ ├── sys.py
│ ├── sys_test.py
│ ├── tempfile.py
│ ├── tempfile_test.py
│ ├── thread.py
│ ├── time.py
│ ├── time_test.py
│ ├── types_test.py
│ ├── weetest.py
│ └── weetest_test.py
├── runtime/
│ ├── baseexception.go
│ ├── baseexception_test.go
│ ├── basestring.go
│ ├── basestring_test.go
│ ├── bool.go
│ ├── bool_test.go
│ ├── builtin_types.go
│ ├── builtin_types_test.go
│ ├── bytearray.go
│ ├── bytearray_test.go
│ ├── code.go
│ ├── code_test.go
│ ├── complex.go
│ ├── complex_test.go
│ ├── core.go
│ ├── core_test.go
│ ├── descriptor.go
│ ├── descriptor_test.go
│ ├── dict.go
│ ├── dict_test.go
│ ├── doc.go
│ ├── exceptions.go
│ ├── file.go
│ ├── file_test.go
│ ├── float.go
│ ├── float_test.go
│ ├── frame.go
│ ├── frame_test.go
│ ├── function.go
│ ├── function_test.go
│ ├── generator.go
│ ├── generator_test.go
│ ├── int.go
│ ├── int_test.go
│ ├── list.go
│ ├── list_test.go
│ ├── long.go
│ ├── long_test.go
│ ├── method.go
│ ├── method_test.go
│ ├── module.go
│ ├── module_test.go
│ ├── native.go
│ ├── native_test.go
│ ├── numeric.go
│ ├── object.go
│ ├── object_test.go
│ ├── param.go
│ ├── param_test.go
│ ├── range.go
│ ├── range_test.go
│ ├── seq.go
│ ├── seq_test.go
│ ├── set.go
│ ├── set_test.go
│ ├── slice.go
│ ├── slice_test.go
│ ├── slots.go
│ ├── slots_test.go
│ ├── str.go
│ ├── str_test.go
│ ├── super.go
│ ├── super_test.go
│ ├── threading.go
│ ├── threading_test.go
│ ├── traceback.go
│ ├── tuple.go
│ ├── tuple_test.go
│ ├── type.go
│ ├── type_test.go
│ ├── unicode.go
│ ├── unicode_test.go
│ ├── weakref.go
│ └── weakref_test.go
├── testing/
│ ├── assert_test.py
│ ├── assign_test.py
│ ├── builtin_test.py
│ ├── class_test.py
│ ├── compare_test.py
│ ├── complex_test.py
│ ├── comprehension_test.py
│ ├── dict_test.py
│ ├── file_test.py
│ ├── float_test.py
│ ├── for_test.py
│ ├── function_test.py
│ ├── generator_test.py
│ ├── getopt_test.py
│ ├── global_test.py
│ ├── if_test.py
│ ├── import_test.py
│ ├── list_test.py
│ ├── native_test.py
│ ├── op_test.py
│ ├── pow_test.py
│ ├── scope_test.py
│ ├── str_test.py
│ ├── struct_test.py
│ ├── try_test.py
│ ├── tuple_test.py
│ ├── while_test.py
│ └── with_test.py
├── third_party/
│ ├── ouroboros/
│ │ ├── AUTHORS
│ │ ├── LICENSE
│ │ ├── READEME.md
│ │ ├── operator.py
│ │ └── test/
│ │ └── test_operator.py
│ ├── pypy/
│ │ ├── LICENSE
│ │ ├── README.md
│ │ ├── _collections.py
│ │ ├── _csv.py
│ │ ├── _functools.py
│ │ ├── _md5.py
│ │ ├── _sha.py
│ │ ├── _sha256.py
│ │ ├── _sha512.py
│ │ ├── _sre.py
│ │ ├── _struct.py
│ │ ├── binascii.py
│ │ └── datetime.py
│ ├── pythonparser/
│ │ ├── LICENSE.txt
│ │ ├── README.md
│ │ ├── __init__.py
│ │ ├── algorithm.py
│ │ ├── ast.py
│ │ ├── diagnostic.py
│ │ ├── lexer.py
│ │ ├── parser.py
│ │ └── source.py
│ └── stdlib/
│ ├── LICENSE
│ ├── Queue.py
│ ├── README.md
│ ├── StringIO.py
│ ├── UserDict.py
│ ├── UserList.py
│ ├── UserString.py
│ ├── _abcoll.py
│ ├── _weakrefset.py
│ ├── abc.py
│ ├── argparse.py
│ ├── base64.py
│ ├── bisect.py
│ ├── collections.py
│ ├── colorsys.py
│ ├── contextlib.py
│ ├── copy.py
│ ├── copy_reg.py
│ ├── csv.py
│ ├── difflib.py
│ ├── dircache.py
│ ├── dummy_thread.py
│ ├── fnmatch.py
│ ├── fpformat.py
│ ├── functools.py
│ ├── genericpath.py
│ ├── getopt.py
│ ├── glob.py
│ ├── heapq.py
│ ├── json/
│ │ ├── __init__.py
│ │ ├── decoder.py
│ │ └── encoder.py
│ ├── json_scanner.py
│ ├── keyword.py
│ ├── linecache.py
│ ├── md5.py
│ ├── mimetools.py
│ ├── mutex.py
│ ├── optparse.py
│ ├── pprint.py
│ ├── quopri.py
│ ├── random.py
│ ├── re.py
│ ├── re_tests.py
│ ├── repr.py
│ ├── rfc822.py
│ ├── sched.py
│ ├── sha.py
│ ├── sre_compile.py
│ ├── sre_constants.py
│ ├── sre_parse.py
│ ├── string.py
│ ├── test/
│ │ ├── __init__.py
│ │ ├── list_tests.py
│ │ ├── lock_tests.py
│ │ ├── mapping_tests.py
│ │ ├── seq_tests.py
│ │ ├── string_tests.py
│ │ ├── test_argparse.py
│ │ ├── test_bisect.py
│ │ ├── test_colorsys.py
│ │ ├── test_datetime.py
│ │ ├── test_dict.py
│ │ ├── test_dircache.py
│ │ ├── test_dummy_thread.py
│ │ ├── test_fpformat.py
│ │ ├── test_genericpath.py
│ │ ├── test_list.py
│ │ ├── test_md5.py
│ │ ├── test_mimetools.py
│ │ ├── test_mutex.py
│ │ ├── test_queue.py
│ │ ├── test_quopri.py
│ │ ├── test_rfc822.py
│ │ ├── test_sched.py
│ │ ├── test_select.py
│ │ ├── test_slice.py
│ │ ├── test_stat.py
│ │ ├── test_string.py
│ │ ├── test_support.py
│ │ ├── test_threading.py
│ │ ├── test_tuple.py
│ │ └── test_uu.py
│ ├── textwrap.py
│ ├── threading.py
│ ├── traceback.py
│ ├── types.py
│ ├── unittest/
│ │ └── __init__.py
│ ├── unittest_case.py
│ ├── unittest_loader.py
│ ├── unittest_result.py
│ ├── unittest_runner.py
│ ├── unittest_signals.py
│ ├── unittest_suite.py
│ ├── unittest_util.py
│ ├── urlparse.py
│ ├── uu.py
│ ├── warnings.py
│ └── weakref.py
└── tools/
├── benchcmp
├── coverparse
├── diffrange
├── genmake
├── grumpc
├── grumprun
├── pkgc.go
└── pydeps
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
build
errors.err
*.swp
*.pyc
================================================
FILE: .pylintrc
================================================
[BASIC]
argument-rgx=^[a-z][a-z0-9_]*$
attr-rgx=^_{0,2}[a-z][a-z0-9_]*$
const-rgx=^(_?[A-Z][A-Z0-9_]*|__[a-z0-9_]+__|_?[a-z][a-z0-9_]*)$
docstring-min-length=10
function-rgx=^(?:(?P<camel_case>_?[A-Z][a-zA-Z0-9]*)|(?P<snake_case>_?[a-z][a-z0-9_]*))$
good-names=main,_
method-rgx=^(?:(?P<exempt>__[a-z0-9_]+__|next|test[A-Z_][A-Za-z0-9_]*)|(?P<camel_case>_{0,2}[A-Z][a-zA-Z0-9]*)|(?P<snake_case>_{0,2}[a-z][a-z0-9_]*))$
no-docstring-rgx=(__.*__|main|test[A-Z_][A-Za-z0-9_]*|[A-Z][A-Za-z0-9]*Test)
variable-rgx=^[a-z][a-z0-9_]*$
[FORMAT]
indent-string=' '
max-line-length=80
[MESSAGES CONTROL]
# TODO: Remove cyclic-import once expr_visitor.py -> stmt.py is resolved.
disable=design,similarities,no-self-use,attribute-defined-outside-init,locally-disabled,star-args,pointless-except,bad-option-value,global-statement,fixme,suppressed-message,useless-suppression,locally-enabled,file-ignored,cyclic-import
[REPORTS]
msg-template={path}:{line}: {msg} ({symbol})
reports=no
[TYPECHECK]
# AST classes have dynamic members. Writer does not but for some reason pylint
# barfs on some of its members.
ignored-classes=pythonparser.ast.Module,grumpy.compiler.util.Writer
================================================
FILE: .travis.yml
================================================
language: go
os:
- linux
- osx
before_script:
- rvm get head || true # https://github.com/travis-ci/travis-ci/issues/6307
- set -e
# Run gofmt and lint serially to avoid confusing output. Run tests in parallel
# for speed.
script: make gofmt lint && make -j2 test
after_script: set +e
================================================
FILE: AUTHORS.md
================================================
Contributors in the order of first contribution
* [Dylan Trotter](https://github.com/trotterdylan)
* [Aaron Tubbs](https://github.com/atubbs)
* [Devin Jeanpierre](https://github.com/ssbr)
* [Torin Rudeen](https://github.com/torinmr)
* [Brian Atkinson](https://github.com/nairb774)
* [Matt Harden](https://github.com/nerdatmath)
* [Ryan Kennedy](https://github.com/ryankennedy)
* [Brett Cannon](https://github.com/brettcannon)
* [Alex Koren](https://github.com/AlexEKoren)
* [Steven Maude](https://github.com/StevenMaude)
* [feilengcui008](https://github.com/feilengcui008)
* [Meador Inge](https://github.com/meadori)
* [Kyoung-chan Lee](https://github.com/leekchan)
* [Cholerae Hu](https://github.com/choleraehyq)
* [Jurriaan Bremer](https://github.com/jbremer)
* [Florian Ludwig](https://github.com/FlorianLudwig)
* [ns-cweber](https://github.com/ns-cweber)
* [Paul Smith](https://github.com/paulsmith)
* [Izaak Weiss](https://github.com/lalaithion)
* [YOU](https://github.com/S-YOU)
* [iury](https://github.com/IuryAlves)
* [wuttem](https://github.com/wuttem)
* [cclauss](https://github.com/cclauss)
* [Mirko Dziadzka](https://github.com/MirkoDziadzka)
* [Dong-hee Na](https://github.com/corona10)
================================================
FILE: CONTRIBUTING.md
================================================
Want to contribute? Great! First, read this page.
### Before you contribute
Before we can use your code, you must sign the
[Google Individual Contributor License Agreement]
(https://cla.developers.google.com/about/google-individual)
(CLA), which you can do online. The CLA is necessary mainly because you own the
copyright to your changes, even after your contribution becomes part of our
codebase, so we need your permission to use and distribute your code. We also
need to be sure of various other things—for instance that you'll tell us if you
know that your code infringes on other people's patents. You don't have to sign
the CLA until after you've submitted your code for review and a member has
approved it, but you must do it before we can put your code into our codebase.
Before you start working on a larger contribution, you should get in touch with
us first through the issue tracker with your idea so that we can help out and
possibly guide you. Coordinating up front makes it much easier to avoid
frustration later on.
Contributions made by corporations are covered by a different agreement than
the one above, the
[Software Grant and Corporate Contributor License Agreement]
(https://cla.developers.google.com/about/google-corporate).
### Code reviews
All submissions, including submissions by project members, require review. We
use GitHub pull requests for this purpose.
### Code Style
We use Google style guides for all our code. Below are the guidelines for each
language we use.
#### Go
All Go source code must be formatted using gofmt and be lint-clean according to
golint. This will be checked by Travis but can be checked manually from a local
repo via `make gofmt golint`.
Code is expected to be gofmt- and lint clean before it is submitted for review.
Code reviews can then focus on structural details and higher level style
considerations. Many common mistakes are already documented in the
[Go Code Review Comments](https://github.com/golang/go/wiki/CodeReviewComments)
doc so it's worth being familiar with these patterns.
#### Python
All Python source code must be lint-clean according to pylint. This will be
checked by Travis but can be checked manually from a local repo via
`make pylint`.
Once code is pylint-clean, it can be submitted for review. In addition to lint
cleanliness, Python code must adhere to the
[Google Python Style Guide](https://google.github.io/styleguide/pyguide.html)
which has a number of additional conventions. Please be familiar with the style
guide and ensure code satisfies its rules before submitting for review.
##### Borrowed Standard Library Code
Standard library code that is borrowed from other open source projects such as
CPython and PyPy need not be lint clean or satisfy the style guide. The goal
should be to keep the copied sources as close to the originals as possible
while still being functional. For more details about borrowing this kind of
code from other places see the
[guidelines for integration](https://github.com/google/grumpy/wiki/Standard-libraries:-guidelines-for-integration).
================================================
FILE: LICENSE
================================================
Copyright 2016 Google Inc. All Rights Reserved.
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2016 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: Makefile
================================================
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ------------------------------------------------------------------------------
# General setup
# ------------------------------------------------------------------------------
GO_ENV := $(shell go env GOOS GOARCH)
GOOS ?= $(word 1,$(GO_ENV))
GOARCH ?= $(word 2,$(GO_ENV))
ROOT_DIR := $(realpath .)
PKG_DIR := build/pkg/$(GOOS)_$(GOARCH)
# Try python2 and then python if PYTHON has not been set
ifeq ($(PYTHON),)
ifneq ($(shell which python2),)
PYTHON = python2
else
PYTHON = python
endif
endif
PYTHON_BIN := $(shell which $(PYTHON))
PYTHON_VER := $(word 2,$(shell $(PYTHON) -V 2>&1))
GO_REQ_MAJ := 1
GO_REQ_MIN := 9
GO_MAJ_MIN := $(subst go,, $(word 3,$(shell go version 2>&1)) )
GO_MAJ := $(word 1,$(subst ., ,$(GO_MAJ_MIN) ))
GO_MIN := $(word 2,$(subst ., ,$(GO_MAJ_MIN) ))
ifeq ($(filter 2.7.%,$(PYTHON_VER)),)
$(error unsupported Python version $(PYTHON_VER), Grumpy only supports 2.7.x. To use a different python binary such as python2, run: 'make PYTHON=python2 ...')
endif
ifneq ($(shell test $(GO_MAJ) -ge $(GO_REQ_MAJ) -a $(GO_MIN) -ge $(GO_REQ_MIN) && echo ok),ok)
$(error unsupported Go version $(GO_VER), Grumpy requires at least $(GO_REQ_MAJ).$(GO_REQ_MIN). Please update Go)
endif
PY_DIR := build/lib/python2.7/site-packages
PY_INSTALL_DIR := $(shell $(PYTHON) -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())")
export GOPATH := $(ROOT_DIR)/build
export PYTHONPATH := $(ROOT_DIR)/$(PY_DIR)
export PATH := $(ROOT_DIR)/build/bin:$(PATH)
GOPATH_PY_ROOT := $(GOPATH)/src/__python__
PYTHONPARSER_SRCS := $(patsubst third_party/%,$(PY_DIR)/grumpy/%,$(wildcard third_party/pythonparser/*.py))
COMPILER_BIN := build/bin/grumpc
COMPILER_SRCS := $(addprefix $(PY_DIR)/grumpy/compiler/,$(notdir $(shell find compiler -name '*.py' -not -name '*_test.py'))) $(PY_DIR)/grumpy/__init__.py
COMPILER_TESTS := $(patsubst %.py,grumpy/%,$(filter-out compiler/expr_visitor_test.py compiler/stmt_test.py,$(wildcard compiler/*_test.py)))
COMPILER_TEST_SRCS := $(patsubst %,$(PY_DIR)/%.py,$(COMPILER_TESTS))
COMPILER_SHARDED_TEST_SRCS := $(patsubst %,$(PY_DIR)/grumpy/compiler/%,expr_visitor_test.py stmt_test.py)
COMPILER_PASS_FILES := $(patsubst %,$(PY_DIR)/%.pass,$(COMPILER_TESTS))
COMPILER_EXPR_VISITOR_PASS_FILES := $(patsubst %,$(PY_DIR)/grumpy/compiler/expr_visitor_test.%of32.pass,$(shell seq 32))
COMPILER_STMT_PASS_FILES := $(patsubst %,$(PY_DIR)/grumpy/compiler/stmt_test.%of16.pass,$(shell seq 16))
COMPILER_D_FILES := $(patsubst %,$(PY_DIR)/%.d,$(COMPILER_TESTS))
COMPILER := $(COMPILER_BIN) $(COMPILER_SRCS) $(PYTHONPARSER_SRCS)
PKGC_BIN := build/bin/pkgc
RUNNER_BIN := build/bin/grumprun
RUNTIME_SRCS := $(addprefix build/src/grumpy/,$(notdir $(wildcard runtime/*.go)))
RUNTIME := $(PKG_DIR)/grumpy.a
RUNTIME_PASS_FILE := build/runtime.pass
RUNTIME_COVER_FILE := $(PKG_DIR)/grumpy.cover
RUNNER = $(RUNNER_BIN) $(COMPILER) $(RUNTIME) $(STDLIB)
LIB_SRCS := $(patsubst lib/%,$(GOPATH_PY_ROOT)/%,$(shell find lib -name '*.py'))
THIRD_PARTY_STDLIB_SRCS := $(patsubst third_party/stdlib/%,$(GOPATH_PY_ROOT)/%,$(shell find third_party/stdlib -name '*.py'))
THIRD_PARTY_PYPY_SRCS := $(patsubst third_party/pypy/%,$(GOPATH_PY_ROOT)/%,$(shell find third_party/pypy -name '*.py'))
THIRD_PARTY_OUROBOROS_SRCS := $(patsubst third_party/ouroboros/%,$(GOPATH_PY_ROOT)/%,$(shell find third_party/ouroboros -name '*.py'))
STDLIB_SRCS := $(LIB_SRCS) $(THIRD_PARTY_STDLIB_SRCS) $(THIRD_PARTY_PYPY_SRCS) $(THIRD_PARTY_OUROBOROS_SRCS)
STDLIB_PACKAGES := $(patsubst $(GOPATH_PY_ROOT)/%.py,%,$(patsubst $(GOPATH_PY_ROOT)/%/__init__.py,%,$(STDLIB_SRCS)))
STDLIB := $(patsubst %,$(PKG_DIR)/__python__/%.a,$(STDLIB_PACKAGES))
STDLIB_TESTS := \
itertools_test \
math_test \
os/path_test \
os_test \
random_test \
re_tests \
sys_test \
tempfile_test \
test/test_bisect \
test/test_colorsys \
test/test_datetime \
test/test_dict \
test/test_dircache \
test/test_dummy_thread \
test/test_fpformat \
test/test_genericpath \
test/test_list \
test/test_md5 \
test/test_mimetools \
test/test_mutex \
test/test_operator \
test/test_quopri \
test/test_queue \
test/test_rfc822 \
test/test_sched \
test/test_select \
test/test_slice \
test/test_stat \
test/test_string \
test/test_threading \
test/test_tuple \
test/test_uu \
time_test \
types_test \
weetest_test
STDLIB_PASS_FILES := $(patsubst %,build/testing/%.pass,$(notdir $(STDLIB_TESTS)))
ACCEPT_TESTS := $(patsubst %.py,%,$(wildcard testing/*.py))
ACCEPT_PASS_FILES := $(patsubst %,build/%.pass,$(ACCEPT_TESTS))
ACCEPT_PY_PASS_FILES := $(patsubst %,build/%_py.pass,$(filter-out %/native_test,$(ACCEPT_TESTS)))
BENCHMARKS := $(patsubst %.py,%,$(wildcard benchmarks/*.py))
BENCHMARK_BINS := $(patsubst %,build/%_benchmark,$(BENCHMARKS))
TOOL_BINS = $(patsubst %,build/bin/%,benchcmp coverparse diffrange genmake pydeps)
GOLINT_BIN = build/bin/golint
PYLINT_BIN = build/bin/pylint
all: $(COMPILER) $(RUNNER) $(RUNTIME) $(TOOL_BINS)
benchmarks: $(BENCHMARK_BINS)
clean:
@rm -rf build
# Convenient wrapper around grumprun that avoids having to set up PATH, etc.
run: $(RUNNER)
@$(RUNNER_BIN)
test: $(ACCEPT_PASS_FILES) $(ACCEPT_PY_PASS_FILES) $(COMPILER_PASS_FILES) $(COMPILER_EXPR_VISITOR_PASS_FILES) $(COMPILER_STMT_PASS_FILES) $(RUNTIME_PASS_FILE) $(STDLIB_PASS_FILES)
precommit: cover gofmt lint test
.PHONY: all benchmarks clean cover gofmt golint install lint precommit pylint run test
# ------------------------------------------------------------------------------
# grumpc compiler
# ------------------------------------------------------------------------------
$(COMPILER_BIN) $(RUNNER_BIN) $(TOOL_BINS): build/bin/%: tools/%
@mkdir -p build/bin
@cp -f $< $@
@sed -i.bak -e '1s@/usr/bin/env python@$(PYTHON_BIN)@' $@
@rm -f $@.bak
$(COMPILER_SRCS) $(COMPILER_TEST_SRCS) $(COMPILER_SHARDED_TEST_SRCS): $(PY_DIR)/grumpy/%.py: %.py
@mkdir -p $(PY_DIR)/grumpy/compiler
@cp -f $< $@
$(COMPILER_PASS_FILES): %.pass: %.py $(COMPILER) $(COMPILER_TEST_SRCS)
@$(PYTHON) $< -q
@touch $@
@echo compiler/`basename $*` PASS
# NOTE: In the regex below we use (\.|$) instead of \> because the latter is
# not available in the awk available on OS X.
$(COMPILER_D_FILES): $(PY_DIR)/%.d: $(PY_DIR)/%.py $(COMPILER_SRCS) $(PYTHONPARSER_SRCS)
@$(PYTHON) -m modulefinder $< | awk '{if (match($$2, /^grumpy(\.|$$)/)) { print "$(PY_DIR)/$*.pass: " substr($$3, length("$(ROOT_DIR)/") + 1) }}' > $@
-include $(COMPILER_D_FILES)
# Does not depend on stdlibs since it makes minimal use of them.
$(COMPILER_EXPR_VISITOR_PASS_FILES): $(PY_DIR)/grumpy/compiler/expr_visitor_test.%.pass: $(PY_DIR)/grumpy/compiler/expr_visitor_test.py $(RUNNER_BIN) $(COMPILER) $(RUNTIME) $(PKG_DIR)/__python__/traceback.a
@$(PYTHON) $< --shard=$*
@touch $@
@echo 'compiler/expr_visitor_test $* PASS'
COMPILER_STMT_PASS_FILE_DEPS := \
$(PKG_DIR)/__python__/__go__/grumpy.a \
$(PKG_DIR)/__python__/__go__/os.a \
$(PKG_DIR)/__python__/__go__/runtime.a \
$(PKG_DIR)/__python__/__go__/time.a \
$(PKG_DIR)/__python__/__go__/unicode.a \
$(PKG_DIR)/__python__/sys.a \
$(PKG_DIR)/__python__/traceback.a
# Does not depend on stdlibs since it makes minimal use of them.
$(COMPILER_STMT_PASS_FILES): $(PY_DIR)/grumpy/compiler/stmt_test.%.pass: $(PY_DIR)/grumpy/compiler/stmt_test.py $(RUNNER_BIN) $(COMPILER) $(RUNTIME) $(COMPILER_STMT_PASS_FILE_DEPS)
@$(PYTHON) $< --shard=$*
@touch $@
@echo 'compiler/stmt_test $* PASS'
$(PKGC_BIN): tools/pkgc.go
@mkdir -p $(@D)
@go build -o $@ $<
# ------------------------------------------------------------------------------
# Grumpy runtime
# ------------------------------------------------------------------------------
$(RUNTIME_SRCS): build/src/grumpy/%.go: runtime/%.go
@mkdir -p build/src/grumpy
@cp -f $< $@
$(RUNTIME): $(filter-out %_test.go,$(RUNTIME_SRCS))
@mkdir -p $(PKG_DIR)
@go tool compile -o $@ -p grumpy -complete -I $(PKG_DIR) -pack $^
$(RUNTIME_PASS_FILE): $(RUNTIME) $(filter %_test.go,$(RUNTIME_SRCS))
@go test grumpy
@touch $@
@echo 'runtime/grumpy PASS'
$(RUNTIME_COVER_FILE): $(RUNTIME) $(filter %_test.go,$(RUNTIME_SRCS))
@go test -coverprofile=$@ grumpy
cover: $(RUNTIME_COVER_FILE) $(TOOL_BINS)
@bash -c 'comm -12 <(coverparse $< | sed "s/^grumpy/runtime/" | sort) <(git diff --dst-prefix= $(DIFF_COMMIT) | diffrange | sort)' | sort -t':' -k1,1 -k2n,2 | sed 's/$$/: missing coverage/' | tee errors.err
@test ! -s errors.err
build/gofmt.diff: $(wildcard runtime/*.go)
@gofmt -d $^ > $@
gofmt: build/gofmt.diff
@if [ -s $< ]; then echo 'gofmt found errors, run: gofmt -w $(ROOT_DIR)/runtime/*.go'; false; fi
$(GOLINT_BIN):
@go get -u github.com/golang/lint/golint
golint: $(GOLINT_BIN)
@$(GOLINT_BIN) -set_exit_status runtime
# Don't use system pip for this since behavior varies a lot between versions.
# Instead build pylint from source. Dependencies will be fetched by distutils.
$(PYLINT_BIN):
@mkdir -p build/third_party
@cd build/third_party && curl -sL https://pypi.io/packages/source/p/pylint/pylint-1.6.4.tar.gz | tar -zx
@cd build/third_party/pylint-1.6.4 && $(PYTHON) setup.py install --prefix $(ROOT_DIR)/build
pylint: $(PYLINT_BIN) $(COMPILER_SRCS) $(PYTHONPARSER_SRCS) $(COMPILER_BIN) $(RUNNER_BIN) $(TOOL_BINS)
@$(PYTHON) $(PYLINT_BIN) $(COMPILER_SRCS) $(COMPILER_BIN) $(RUNNER_BIN) $(TOOL_BINS)
lint: golint pylint
# ------------------------------------------------------------------------------
# Native modules
# ------------------------------------------------------------------------------
$(PKG_DIR)/__python__/__go__/%.a: build/src/__python__/__go__/%/module.go $(RUNTIME)
@mkdir -p $(@D)
@go install __python__/__go__/$*
build/src/__python__/__go__/%/module.go: $(PKGC_BIN) $(RUNTIME)
@mkdir -p $(@D)
@$(PKGC_BIN) $* > $@
$(PKG_DIR)/__python__/__go__/grumpy.a: $(RUNTIME)
.PRECIOUS: build/src/__python__/__go__/%/module.go $(PKG_DIR)/__python__/__go__/%.a
# ------------------------------------------------------------------------------
# Standard library
# ------------------------------------------------------------------------------
$(LIB_SRCS): $(GOPATH_PY_ROOT)/%: lib/%
@mkdir -p $(@D)
@cp -f $< $@
$(THIRD_PARTY_STDLIB_SRCS): $(GOPATH_PY_ROOT)/%: third_party/stdlib/%
@mkdir -p $(@D)
@cp -f $< $@
$(THIRD_PARTY_PYPY_SRCS): $(GOPATH_PY_ROOT)/%: third_party/pypy/%
@mkdir -p $(@D)
@cp -f $< $@
$(THIRD_PARTY_OUROBOROS_SRCS): $(GOPATH_PY_ROOT)/%: third_party/ouroboros/%
@mkdir -p $(@D)
@cp -f $< $@
build/stdlib.mk: build/bin/genmake | $(STDLIB_SRCS)
@genmake build > $@
-include build/stdlib.mk
$(patsubst %,build/src/__python__/%/module.go,$(STDLIB_PACKAGES)): $(COMPILER)
$(patsubst %,build/src/__python__/%/module.d,$(STDLIB_PACKAGES)): build/bin/pydeps $(PYTHONPARSER_SRCS) $(COMPILER)
$(patsubst %,$(PKG_DIR)/__python__/%.a,$(STDLIB_PACKAGES)): $(RUNTIME)
define GRUMPY_STDLIB_TEST
build/testing/$(notdir $(1)).pass: $(RUNTIME) $(PKG_DIR)/__python__/$(1).a $(RUNNER_BIN) $(PKG_DIR)/__python__/traceback.a
@mkdir -p $$(@D)
@$(RUNNER_BIN) -m $(subst /,.,$(1))
@touch $$@
@echo 'lib/$(1) PASS'
endef
$(eval $(foreach x,$(STDLIB_TESTS),$(call GRUMPY_STDLIB_TEST,$(x))))
# ------------------------------------------------------------------------------
# Acceptance tests & benchmarks
# ------------------------------------------------------------------------------
$(PY_DIR)/weetest.py: lib/weetest.py
@cp -f $< $@
$(PYTHONPARSER_SRCS): $(PY_DIR)/grumpy/%: third_party/%
@mkdir -p $(@D)
@cp -f $< $@
$(ACCEPT_PASS_FILES): build/%_test.pass: %_test.py $(RUNTIME) $(STDLIB) $(RUNNER_BIN)
@mkdir -p $(@D)
@$(RUNNER_BIN) < $<
@touch $@
@echo '$*_test PASS'
NATIVE_TEST_DEPS := \
$(PKG_DIR)/__python__/__go__/encoding/csv.a \
$(PKG_DIR)/__python__/__go__/image.a \
$(PKG_DIR)/__python__/__go__/math.a \
$(PKG_DIR)/__python__/__go__/strings.a
build/testing/native_test.pass: $(NATIVE_TEST_DEPS)
$(ACCEPT_PY_PASS_FILES): build/%_py.pass: %.py $(PY_DIR)/weetest.py
@mkdir -p $(@D)
@$(PYTHON) $<
@touch $@
@echo '$*_py PASS'
$(patsubst %,build/%.go,$(BENCHMARKS)): build/%.go: %.py $(COMPILER)
@mkdir -p $(@D)
@$(COMPILER_BIN) $< > $@
$(BENCHMARK_BINS): build/benchmarks/%_benchmark: build/benchmarks/%.go $(RUNTIME) $(STDLIB)
@mkdir -p $(@D)
@go build -o $@ $<
# ------------------------------------------------------------------------------
# Installation
# ------------------------------------------------------------------------------
install: $(RUNNER_BIN) $(COMPILER) $(RUNTIME) $(STDLIB)
# Binary executables
install -d "$(DESTDIR)/usr/bin"
install -m755 build/bin/grumpc "$(DESTDIR)/usr/bin/grumpc"
install -m755 build/bin/grumprun "$(DESTDIR)/usr/bin/grumprun"
# Python module
install -d "$(DESTDIR)"{/usr/lib/go,"$(PY_INSTALL_DIR)"}
cp -rv "$(PY_DIR)/grumpy" "$(DESTDIR)$(PY_INSTALL_DIR)"
# Go package and sources
install -d "$(DESTDIR)/usr/lib/go/"
cp -rv build/pkg build/src "$(DESTDIR)/usr/lib/go/"
================================================
FILE: README.md
================================================
# Grumpy: Go running Python
[](https://travis-ci.org/google/grumpy)
[](https://gitter.im/grumpy-devel/Lobby?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
## Overview
Grumpy is a Python to Go source code transcompiler and runtime that is intended
to be a near drop-in replacement for CPython 2.7. The key difference is that it
compiles Python source code to Go source code which is then compiled to native
code, rather than to bytecode. This means that Grumpy has no VM. The compiled Go
source code is a series of calls to the Grumpy runtime, a Go library serving a
similar purpose to the Python C API (although the API is incompatible with
CPython's).
## Limitations
### Things that will probably never be supported by Grumpy
1. `exec`, `eval` and `compile`: These dynamic features of CPython are not
supported by Grumpy because Grumpy modules consist of statically-compiled Go
code. Supporting dynamic execution would require bundling Grumpy programs
with the compilation toolchain, which would be unwieldy and impractically
slow.
2. C extension modules: Grumpy has a different API and object layout than
CPython and so supporting C extensions would be difficult. In principle it's
possible to support them via an API bridge layer like the one that
[JyNI](http://jyni.org) provides for Jython, but it would be hard to maintain and
would add significant overhead when calling into and out of extension
modules.
### Things that Grumpy will support but doesn't yet
There are three basic categories of incomplete functionality:
1. [Language features](https://github.com/google/grumpy/wiki/Missing-features#language-features):
Most language features are implemented with the notable exception of
[old-style classes](http://stackoverflow.com/questions/54867/what-is-the-difference-between-old-style-and-new-style-classes-in-python).
There are also a handful of operators that aren't yet supported.
2. [Builtin functions and types](https://github.com/google/grumpy/wiki/Missing-features#builtins):
There are a number of missing functions and types in `__builtins__` that have
not yet been implemented. There are also a lot of methods on builtin types
that are missing.
3. [Standard library](https://github.com/google/grumpy/wiki/Missing-features#standard-libraries):
The Python standard library is very large and much of it is pure Python, so
as the language features and builtins get filled out, many modules will
just work. But there are also a number of libraries in CPython that are C
extension modules which will need to be rewritten.
4. C locale support: Go doesn't support locales in the same way that C does. As such,
some functionality that is locale-dependent may not currently work the same as in
CPython.
## Running Grumpy Programs
### Method 1: make run:
The simplest way to execute a Grumpy program is to use `make run`, which wraps a
shell script called grumprun that takes Python code on stdin and builds and runs
the code under Grumpy. All of the commands below are assumed to be run from the
root directory of the Grumpy source code distribution:
```
echo "print 'hello, world'" | make run
```
### Method 2: grumpc and grumprun:
For more complicated programs, you'll want to compile your Python source code to
Go using grumpc (the Grumpy compiler) and then build the Go code using `go
build`. Since Grumpy programs are statically linked, all the modules in a
program must be findable by the Grumpy toolchain on the GOPATH. Grumpy looks for
Go packages corresponding to Python modules in the \_\_python\_\_ subdirectory
of the GOPATH. By convention, this subdirectory is also used for staging Python
source code, making it similar to the PYTHONPATH.
The first step is to set up the shell so that the Grumpy toolchain and libraries
can be found. From the root directory of the Grumpy source distribution run:
```
make
export PATH=$PWD/build/bin:$PATH
export GOPATH=$PWD/build
export PYTHONPATH=$PWD/build/lib/python2.7/site-packages
```
You will know things are working if you see the expected output from this
command:
```
echo 'import sys; print sys.version' | grumprun
```
Next, we will write our simple Python module into the \_\_python\_\_ directory:
```
echo 'def hello(): print "hello, world"' > $GOPATH/src/__python__/hello.py
```
To build a Go package from our Python script, run the following:
```
mkdir -p $GOPATH/src/__python__/hello
grumpc -modname=hello $GOPATH/src/__python__/hello.py > \
$GOPATH/src/__python__/hello/module.go
```
You should now be able to build a Go program that imports the package
"\_\_python\_\_/hello". We can also import this module into Python programs
that are built using grumprun:
```
echo 'from hello import hello; hello()' | grumprun
```
grumprun is doing a few things under the hood here:
1. Compiles the given Python code to a dummy Go package, the same way we
produced \_\_python\_\_/hello/module.go above
2. Produces a main Go package that imports the Go package from step 1. and
executes it as our \_\_main\_\_ Python package
3. Executes `go run` on the main package generated in step 2.
## Developing Grumpy
There are three main components and depending on what kind of feature you're
writing, you may need to change one or more of these.
### grumpc
Grumpy converts Python programs into Go programs and `grumpc` is the tool
responsible for parsing Python code and generating Go code from it. `grumpc` is
written in Python and uses the [`pythonparser`](https://github.com/m-labs/pythonparser)
module to accomplish parsing.
The grumpc script itself lives at `tools/grumpc`. It is supported by a number of
Python modules in the `compiler` subdir.
### Grumpy Runtime
The Go code generated by `grumpc` performs operations on data structures that
represent Python objects in running Grumpy programs. These data structures and
operations are defined in the `grumpy` Go library (source is in the runtime
subdir of the source distribution). This runtime is analogous to the Python C
API and many of the structures and operations defined by `grumpy` have
counterparts in CPython.
### Grumpy Standard Library
Much of the Python standard library is written in Python and thus "just works"
in Grumpy. These parts of the standard library are copied from CPython 2.7
(possibly with light modifications). For licensing reasons, these files are kept
in the `third_party` subdir.
The parts of the standard library that cannot be written in pure Python, e.g.
file and directory operations, are kept in the `lib` subdir. In CPython these
kinds of modules are written as C extensions. In Grumpy they are written in
Python but they use native Go extensions to access facilities not otherwise
available in Python.
### Source Code Overview
- `compiler`: Python package implementating Python -> Go transcompilation logic.
- `lib`: Grumpy-specific Python standard library implementation.
- `runtime`: Go source code for the Grumpy runtime library.
- `third_party/ouroboros`: Pure Python standard libraries copied from the
[Ouroboros project](https://github.com/pybee/ouroboros).
- `third_party/pypy`: Pure Python standard libraries copied from PyPy.
- `third_party/stdlib`: Pure Python standard libraries copied from CPython.
- `tools`: Transcompilation and utility binaries.
## Contact
Questions? Comments? Drop us a line at [grumpy-users@googlegroups.com](https://groups.google.com/forum/#!forum/grumpy-users)
or join our [Gitter channel](https://gitter.im/grumpy-devel/Lobby)
================================================
FILE: __init__.py
================================================
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
================================================
FILE: benchmarks/bm_call_method.py
================================================
"""Microbenchmark for method call overhead.
This measures simple method calls that are predictable, do not use varargs or
kwargs, and do not use tuple unpacking.
Taken from:
https://github.com/python/performance/blob/9b8d859/performance/benchmarks/bm_call_method.py
"""
import weetest
class Foo(object):
def foo(self, a, b, c, d):
# 20 calls
self.bar(a, b, c)
self.bar(a, b, c)
self.bar(a, b, c)
self.bar(a, b, c)
self.bar(a, b, c)
self.bar(a, b, c)
self.bar(a, b, c)
self.bar(a, b, c)
self.bar(a, b, c)
self.bar(a, b, c)
self.bar(a, b, c)
self.bar(a, b, c)
self.bar(a, b, c)
self.bar(a, b, c)
self.bar(a, b, c)
self.bar(a, b, c)
self.bar(a, b, c)
self.bar(a, b, c)
self.bar(a, b, c)
self.bar(a, b, c)
def bar(self, a, b, c):
# 20 calls
self.baz(a, b)
self.baz(a, b)
self.baz(a, b)
self.baz(a, b)
self.baz(a, b)
self.baz(a, b)
self.baz(a, b)
self.baz(a, b)
self.baz(a, b)
self.baz(a, b)
self.baz(a, b)
self.baz(a, b)
self.baz(a, b)
self.baz(a, b)
self.baz(a, b)
self.baz(a, b)
self.baz(a, b)
self.baz(a, b)
self.baz(a, b)
self.baz(a, b)
def baz(self, a, b):
# 20 calls
self.quux(a)
self.quux(a)
self.quux(a)
self.quux(a)
self.quux(a)
self.quux(a)
self.quux(a)
self.quux(a)
self.quux(a)
self.quux(a)
self.quux(a)
self.quux(a)
self.quux(a)
self.quux(a)
self.quux(a)
self.quux(a)
self.quux(a)
self.quux(a)
self.quux(a)
self.quux(a)
def quux(self, a):
# 20 calls
self.qux()
self.qux()
self.qux()
self.qux()
self.qux()
self.qux()
self.qux()
self.qux()
self.qux()
self.qux()
self.qux()
self.qux()
self.qux()
self.qux()
self.qux()
self.qux()
self.qux()
self.qux()
self.qux()
self.qux()
def qux(self):
pass
def BenchmarkCallMethod(b):
f = Foo()
for _ in xrange(b.N):
# 20 calls
f.foo(1, 2, 3, 4)
f.foo(1, 2, 3, 4)
f.foo(1, 2, 3, 4)
f.foo(1, 2, 3, 4)
f.foo(1, 2, 3, 4)
f.foo(1, 2, 3, 4)
f.foo(1, 2, 3, 4)
f.foo(1, 2, 3, 4)
f.foo(1, 2, 3, 4)
f.foo(1, 2, 3, 4)
f.foo(1, 2, 3, 4)
f.foo(1, 2, 3, 4)
f.foo(1, 2, 3, 4)
f.foo(1, 2, 3, 4)
f.foo(1, 2, 3, 4)
f.foo(1, 2, 3, 4)
f.foo(1, 2, 3, 4)
f.foo(1, 2, 3, 4)
f.foo(1, 2, 3, 4)
f.foo(1, 2, 3, 4)
if __name__ == '__main__':
weetest.RunBenchmarks()
================================================
FILE: benchmarks/bm_call_simple.py
================================================
"""Microbenchmark for function call overhead.
This measures simple function calls that are not methods, do not use varargs or
kwargs, and do not use tuple unpacking.
Taken from:
https://github.com/python/performance/blob/9b8d859/performance/benchmarks/bm_call_simple.py
"""
import weetest
def foo(a, b, c, d):
# 20 calls
bar(a, b, c)
bar(a, b, c)
bar(a, b, c)
bar(a, b, c)
bar(a, b, c)
bar(a, b, c)
bar(a, b, c)
bar(a, b, c)
bar(a, b, c)
bar(a, b, c)
bar(a, b, c)
bar(a, b, c)
bar(a, b, c)
bar(a, b, c)
bar(a, b, c)
bar(a, b, c)
bar(a, b, c)
bar(a, b, c)
bar(a, b, c)
bar(a, b, c)
def bar(a, b, c):
# 20 calls
baz(a, b)
baz(a, b)
baz(a, b)
baz(a, b)
baz(a, b)
baz(a, b)
baz(a, b)
baz(a, b)
baz(a, b)
baz(a, b)
baz(a, b)
baz(a, b)
baz(a, b)
baz(a, b)
baz(a, b)
baz(a, b)
baz(a, b)
baz(a, b)
baz(a, b)
baz(a, b)
def baz(a, b):
# 20 calls
quux(a)
quux(a)
quux(a)
quux(a)
quux(a)
quux(a)
quux(a)
quux(a)
quux(a)
quux(a)
quux(a)
quux(a)
quux(a)
quux(a)
quux(a)
quux(a)
quux(a)
quux(a)
quux(a)
quux(a)
def quux(a):
# 20 calls
qux()
qux()
qux()
qux()
qux()
qux()
qux()
qux()
qux()
qux()
qux()
qux()
qux()
qux()
qux()
qux()
qux()
qux()
qux()
qux()
def qux():
pass
def BenchmarkCallSimple(b):
for _ in xrange(b.N):
# 20 calls
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
if __name__ == '__main__':
weetest.RunBenchmarks()
================================================
FILE: benchmarks/call.py
================================================
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Benchmarks for function calls."""
# pylint: disable=unused-argument
import weetest
def BenchmarkCallNoArgs(b):
def Foo():
pass
for _ in xrange(b.N):
Foo()
def BenchmarkCallPositionalArgs(b):
def Foo(a, b, c):
pass
for _ in xrange(b.N):
Foo(1, 2, 3)
def BenchmarkCallKeywords(b):
def Foo(a, b, c):
pass
for _ in xrange(b.N):
Foo(a=1, b=2, c=3)
def BenchmarkCallDefaults(b):
def Foo(a=1, b=2, c=3):
pass
for _ in xrange(b.N):
Foo()
def BenchmarkCallVarArgs(b):
def Foo(*args):
pass
for _ in xrange(b.N):
Foo(1, 2, 3)
def BenchmarkCallKwargs(b):
def Foo(**kwargs):
pass
for _ in xrange(b.N):
Foo(a=1, b=2, c=3)
if __name__ == '__main__':
weetest.RunBenchmarks()
================================================
FILE: benchmarks/comprehension.py
================================================
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Benchmarks for comprehensions."""
# pylint: disable=unused-argument
import weetest
def BenchmarkGeneratorExpCreate(b):
l = []
for _ in xrange(b.N):
(x for x in l) # pylint: disable=pointless-statement
def BenchmarkGeneratorExpIterate(b):
for _ in (x for x in xrange(b.N)):
pass
def BenchmarkListCompCreate(b):
for _ in xrange(b.N):
[x for x in xrange(1000)] # pylint: disable=expression-not-assigned
def BenchmarkDictCompCreate(b):
for _ in xrange(b.N):
{x: x for x in xrange(1000)} # pylint: disable=expression-not-assigned
if __name__ == '__main__':
weetest.RunBenchmarks()
================================================
FILE: benchmarks/concurrent.py
================================================
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Benchmarks for simple parallel calculations."""
import threading
import weetest
def Arithmetic(n):
return n * 3 + 2
def Fib(n):
if n < 2:
return 1
return Fib(n - 1) + Fib(n - 2)
_WORKLOADS = [
(Arithmetic, 1001),
(Fib, 10),
]
def _MakeParallelBenchmark(p, work_func, *args):
"""Create and return a benchmark that runs work_func p times in parallel."""
def Benchmark(b): # pylint: disable=missing-docstring
e = threading.Event()
def Target():
e.wait()
for _ in xrange(b.N / p):
work_func(*args)
threads = []
for _ in xrange(p):
t = threading.Thread(target=Target)
t.start()
threads.append(t)
b.ResetTimer()
e.set()
for t in threads:
t.join()
return Benchmark
def _RegisterBenchmarks():
for p in xrange(1, 13):
for work_func, arg in _WORKLOADS:
name = 'Benchmark' + work_func.__name__
if p > 1:
name += 'Parallel%s' % p
globals()[name] = _MakeParallelBenchmark(p, work_func, arg)
_RegisterBenchmarks()
if __name__ == '__main__':
weetest.RunBenchmarks()
================================================
FILE: benchmarks/dict.py
================================================
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Benchmarks for dictionary operations."""
# pylint: disable=pointless-statement
import weetest
def BenchmarkDictCreate(b):
for _ in xrange(b.N):
d = {'one': 1, 'two': 2, 'three': 3}
def BenchmarkDictCreateFunc(b):
for _ in xrange(b.N):
d = dict(one=1, two=2, three=3)
def BenchmarkDictGetItem(b):
d = {42: 123}
for _ in xrange(b.N):
d[42]
def BenchmarkDictStringOnlyGetItem(b):
d = {'foo': 123}
for _ in xrange(b.N):
d['foo']
def BenchmarkDictSetItem(b):
d = {}
for _ in xrange(b.N):
d[42] = 123
def BenchmarkDictStringOnlySetItem(b):
d = {}
for _ in xrange(b.N):
d['foo'] = 123
def BenchmarkHashStrCached(b):
"""Hashes the same value repeatedly to exercise any hash caching logic."""
h = hash # Prevent builtins lookup each iteration.
for _ in xrange(b.N):
h('foobarfoobarfoobar')
if __name__ == '__main__':
weetest.RunBenchmarks()
================================================
FILE: benchmarks/generator.py
================================================
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Benchmarks for generator functions."""
import weetest
def BenchmarkGeneratorIterate(b):
def Gen(n):
for i in xrange(n):
yield i
for _ in Gen(b.N):
pass
def BenchmarkGeneratorCreate(b):
def Gen():
yield 1
for _ in xrange(b.N):
Gen()
if __name__ == '__main__':
weetest.RunBenchmarks()
================================================
FILE: benchmarks/list.py
================================================
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Benchmarks for list operations."""
# pylint: disable=pointless-statement
import weetest
def BenchmarkListGetItem(b):
l = [1, 3, 9]
for _ in xrange(b.N):
l[2]
def BenchmarkListContains3(b):
l = [1, 3, 9]
for _ in xrange(b.N):
9 in l
def BenchmarkListContains10(b):
l = range(10)
for _ in xrange(b.N):
9 in l
if __name__ == '__main__':
weetest.RunBenchmarks()
================================================
FILE: benchmarks/loop.py
================================================
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Benchmarks for simple low overhead loops."""
import weetest
def BenchmarkForXRange(b):
for _ in xrange(b.N):
pass
def BenchmarkWhileCounter(b):
i = 0
while i < b.N:
i += 1
def BenchmarkWhileXRange(b):
i = iter(xrange(b.N))
try:
while True:
i.next()
except StopIteration:
pass
if __name__ == '__main__':
weetest.RunBenchmarks()
================================================
FILE: benchmarks/tuple.py
================================================
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Benchmarks for list operations."""
# pylint: disable=pointless-statement
import weetest
def BenchmarkTupleGetItem(b):
l = (1, 3, 9)
for _ in xrange(b.N):
l[2]
def BenchmarkTupleContains3(b):
t = (1, 3, 9)
for _ in xrange(b.N):
9 in t
def BenchmarkTupleContains10(b):
t = tuple(range(10))
for _ in xrange(b.N):
9 in t
if __name__ == '__main__':
weetest.RunBenchmarks()
================================================
FILE: compiler/__init__.py
================================================
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
================================================
FILE: compiler/block.py
================================================
# coding=utf-8
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Classes for analyzing and storing the state of Python code blocks."""
from __future__ import unicode_literals
import abc
import collections
import re
from grumpy.compiler import expr
from grumpy.compiler import util
from grumpy.pythonparser import algorithm
from grumpy.pythonparser import ast
from grumpy.pythonparser import source
_non_word_re = re.compile('[^A-Za-z0-9_]')
class Package(object):
"""A Go package import."""
def __init__(self, name, alias=None):
self.name = name
# Use Γ as a separator since it provides readability with a low
# probability of name collisions.
self.alias = alias or 'π_' + name.replace('/', 'Γ').replace('.', 'Γ')
class Loop(object):
"""Represents a for or while loop within a particular block."""
def __init__(self, breakvar):
self.breakvar = breakvar
class Block(object):
"""Represents a Python block such as a function or class definition."""
__metaclass__ = abc.ABCMeta
def __init__(self, parent, name):
self.root = parent.root if parent else self
self.parent = parent
self.name = name
self.free_temps = set()
self.used_temps = set()
self.temp_index = 0
self.label_count = 0
self.checkpoints = set()
self.loop_stack = []
self.is_generator = False
@abc.abstractmethod
def bind_var(self, writer, name, value):
"""Writes Go statements for assigning value to named var in this block.
This is overridden in the different concrete block types since in Python,
binding a variable in, e.g. a function is quite different than binding at
global block.
Args:
writer: The Writer object where statements will be written.
name: The name of the Python variable.
value: A Go expression to assign to the variable.
"""
pass
@abc.abstractmethod
def del_var(self, writer, name):
pass
@abc.abstractmethod
def resolve_name(self, writer, name):
"""Returns a GeneratedExpr object for accessing the named var in this block.
This is overridden in the different concrete block types since name
resolution in Python behaves differently depending on where in what kind of
block its happening within, e.g. local vars are different than globals.
Args:
writer: Writer object where intermediate calculations will be printed.
name: The name of the Python variable.
"""
pass
def genlabel(self, is_checkpoint=False):
self.label_count += 1
if is_checkpoint:
self.checkpoints.add(self.label_count)
return self.label_count
def alloc_temp(self, type_='*πg.Object'):
"""Create a new temporary Go variable having type type_ for this block."""
for v in sorted(self.free_temps, key=lambda k: k.name):
if v.type_ == type_:
self.free_temps.remove(v)
self.used_temps.add(v)
return v
self.temp_index += 1
name = 'πTemp{:03d}'.format(self.temp_index)
v = expr.GeneratedTempVar(self, name, type_)
self.used_temps.add(v)
return v
def free_temp(self, v):
"""Release the GeneratedTempVar v so it can be reused."""
self.used_temps.remove(v)
self.free_temps.add(v)
def push_loop(self, breakvar):
loop = Loop(breakvar)
self.loop_stack.append(loop)
return loop
def pop_loop(self):
self.loop_stack.pop()
def top_loop(self):
return self.loop_stack[-1]
def _resolve_global(self, writer, name):
result = self.alloc_temp()
writer.write_checked_call2(
result, 'πg.ResolveGlobal(πF, {})', self.root.intern(name))
return result
class ModuleBlock(Block):
"""Python block for a module."""
def __init__(self, importer, full_package_name,
filename, src, future_features):
Block.__init__(self, None, '<module>')
self.importer = importer
self.full_package_name = full_package_name
self.filename = filename
self.buffer = source.Buffer(src)
self.strings = set()
self.future_features = future_features
def bind_var(self, writer, name, value):
writer.write_checked_call1(
'πF.Globals().SetItem(πF, {}.ToObject(), {})',
self.intern(name), value)
def del_var(self, writer, name):
writer.write_checked_call1('πg.DelVar(πF, πF.Globals(), {})',
self.intern(name))
def resolve_name(self, writer, name):
return self._resolve_global(writer, name)
def intern(self, s):
if len(s) > 64 or _non_word_re.search(s):
return 'πg.NewStr({})'.format(util.go_str(s))
self.strings.add(s)
return 'ß' + s
class ClassBlock(Block):
"""Python block for a class definition."""
def __init__(self, parent, name, global_vars):
Block.__init__(self, parent, name)
self.global_vars = global_vars
def bind_var(self, writer, name, value):
if name in self.global_vars:
return self.root.bind_var(writer, name, value)
writer.write_checked_call1('πClass.SetItem(πF, {}.ToObject(), {})',
self.root.intern(name), value)
def del_var(self, writer, name):
if name in self.global_vars:
return self.root.del_var(writer, name)
writer.write_checked_call1('πg.DelVar(πF, πClass, {})',
self.root.intern(name))
def resolve_name(self, writer, name):
local = 'nil'
if name not in self.global_vars:
# Only look for a local in an outer block when name hasn't been declared
# global in this block. If it has been declared global then we fallback
# straight to the global dict.
block = self.parent
while not isinstance(block, ModuleBlock):
if isinstance(block, FunctionBlock) and name in block.vars:
var = block.vars[name]
if var.type != Var.TYPE_GLOBAL:
local = util.adjust_local_name(name)
# When it is declared global, prefer it to anything in outer blocks.
break
block = block.parent
result = self.alloc_temp()
writer.write_checked_call2(
result, 'πg.ResolveClass(πF, πClass, {}, {})',
local, self.root.intern(name))
return result
class FunctionBlock(Block):
"""Python block for a function definition."""
def __init__(self, parent, name, block_vars, is_generator):
Block.__init__(self, parent, name)
self.vars = block_vars
self.parent = parent
self.is_generator = is_generator
def bind_var(self, writer, name, value):
if self.vars[name].type == Var.TYPE_GLOBAL:
return self.root.bind_var(writer, name, value)
writer.write('{} = {}'.format(util.adjust_local_name(name), value))
def del_var(self, writer, name):
var = self.vars.get(name)
if not var:
raise util.ParseError(
None, 'cannot delete nonexistent local: {}'.format(name))
if var.type == Var.TYPE_GLOBAL:
return self.root.del_var(writer, name)
adjusted_name = util.adjust_local_name(name)
# Resolve local first to ensure the variable is already bound.
writer.write_checked_call1('πg.CheckLocal(πF, {}, {})',
adjusted_name, util.go_str(name))
writer.write('{} = πg.UnboundLocal'.format(adjusted_name))
def resolve_name(self, writer, name):
block = self
while not isinstance(block, ModuleBlock):
if isinstance(block, FunctionBlock):
var = block.vars.get(name)
if var:
if var.type == Var.TYPE_GLOBAL:
return self._resolve_global(writer, name)
writer.write_checked_call1('πg.CheckLocal(πF, {}, {})',
util.adjust_local_name(name),
util.go_str(name))
return expr.GeneratedLocalVar(name)
block = block.parent
return self._resolve_global(writer, name)
class Var(object):
"""A Python variable used within a particular block."""
TYPE_LOCAL = 0
TYPE_PARAM = 1
TYPE_GLOBAL = 2
def __init__(self, name, var_type, arg_index=None):
self.name = name
self.type = var_type
if var_type == Var.TYPE_LOCAL:
assert arg_index is None
self.init_expr = 'πg.UnboundLocal'
elif var_type == Var.TYPE_PARAM:
assert arg_index is not None
self.init_expr = 'πArgs[{}]'.format(arg_index)
else:
assert arg_index is None
self.init_expr = None
class BlockVisitor(algorithm.Visitor):
"""Visits nodes in a function or class to determine block variables."""
# pylint: disable=invalid-name,missing-docstring
def __init__(self):
self.vars = collections.OrderedDict()
def visit_Assign(self, node):
for target in node.targets:
self._assign_target(target)
self.visit(node.value)
def visit_AugAssign(self, node):
self._assign_target(node.target)
self.visit(node.value)
def visit_ClassDef(self, node):
self._register_local(node.name)
def visit_ExceptHandler(self, node):
if node.name:
self._register_local(node.name.id)
self.generic_visit(node)
def visit_For(self, node):
self._assign_target(node.target)
self.generic_visit(node)
def visit_FunctionDef(self, node):
# The function being defined is local to this block, i.e. is nested within
# another function. Note that further nested symbols are not traversed
# because we don't explicitly visit the function body.
self._register_local(node.name)
def visit_Global(self, node):
for name in node.names:
self._register_global(node, name)
def visit_Import(self, node):
for alias in node.names:
self._register_local(alias.asname or alias.name.split('.')[0])
def visit_ImportFrom(self, node):
for alias in node.names:
self._register_local(alias.asname or alias.name)
def visit_With(self, node):
for item in node.items:
if item.optional_vars:
self._assign_target(item.optional_vars)
self.generic_visit(node)
def _assign_target(self, target):
if isinstance(target, ast.Name):
self._register_local(target.id)
elif isinstance(target, (ast.Tuple, ast.List)):
for elt in target.elts:
self._assign_target(elt)
def _register_global(self, node, name):
var = self.vars.get(name)
if var:
if var.type == Var.TYPE_PARAM:
msg = "name '{}' is parameter and global"
raise util.ParseError(node, msg.format(name))
if var.type == Var.TYPE_LOCAL:
msg = "name '{}' is used prior to global declaration"
raise util.ParseError(node, msg.format(name))
else:
self.vars[name] = Var(name, Var.TYPE_GLOBAL)
def _register_local(self, name):
if not self.vars.get(name):
self.vars[name] = Var(name, Var.TYPE_LOCAL)
class FunctionBlockVisitor(BlockVisitor):
"""Visits function nodes to determine variables and generator state."""
# pylint: disable=invalid-name,missing-docstring
def __init__(self, node):
BlockVisitor.__init__(self)
self.is_generator = False
node_args = node.args
args = [a.arg for a in node_args.args]
if node_args.vararg:
args.append(node_args.vararg.arg)
if node_args.kwarg:
args.append(node_args.kwarg.arg)
for i, name in enumerate(args):
if name in self.vars:
msg = "duplicate argument '{}' in function definition".format(name)
raise util.ParseError(node, msg)
self.vars[name] = Var(name, Var.TYPE_PARAM, arg_index=i)
def visit_Yield(self, unused_node): # pylint: disable=unused-argument
self.is_generator = True
================================================
FILE: compiler/block_test.py
================================================
# coding=utf-8
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests Package, Block, BlockVisitor and related classes."""
from __future__ import unicode_literals
import textwrap
import unittest
from grumpy.compiler import block
from grumpy.compiler import imputil
from grumpy.compiler import util
from grumpy import pythonparser
class PackageTest(unittest.TestCase):
def testCreate(self):
package = block.Package('foo/bar/baz')
self.assertEqual(package.name, 'foo/bar/baz')
self.assertEqual(package.alias, 'π_fooΓbarΓbaz')
def testCreateGrump(self):
package = block.Package('foo/bar/baz', 'myalias')
self.assertEqual(package.name, 'foo/bar/baz')
self.assertEqual(package.alias, 'myalias')
class BlockTest(unittest.TestCase):
def testLoop(self):
b = _MakeModuleBlock()
loop = b.push_loop(None)
self.assertEqual(loop, b.top_loop())
inner_loop = b.push_loop(None)
self.assertEqual(inner_loop, b.top_loop())
b.pop_loop()
self.assertEqual(loop, b.top_loop())
def testResolveName(self):
module_block = _MakeModuleBlock()
block_vars = {'foo': block.Var('foo', block.Var.TYPE_LOCAL)}
func1_block = block.FunctionBlock(module_block, 'func1', block_vars, False)
block_vars = {'bar': block.Var('bar', block.Var.TYPE_LOCAL)}
func2_block = block.FunctionBlock(func1_block, 'func2', block_vars, False)
block_vars = {'case': block.Var('case', block.Var.TYPE_LOCAL)}
keyword_block = block.FunctionBlock(
module_block, 'keyword_func', block_vars, False)
class1_block = block.ClassBlock(module_block, 'Class1', set())
class2_block = block.ClassBlock(func1_block, 'Class2', set())
self.assertRegexpMatches(self._ResolveName(module_block, 'foo'),
r'ResolveGlobal\b.*foo')
self.assertRegexpMatches(self._ResolveName(module_block, 'bar'),
r'ResolveGlobal\b.*bar')
self.assertRegexpMatches(self._ResolveName(module_block, 'baz'),
r'ResolveGlobal\b.*baz')
self.assertRegexpMatches(self._ResolveName(func1_block, 'foo'),
r'CheckLocal\b.*foo')
self.assertRegexpMatches(self._ResolveName(func1_block, 'bar'),
r'ResolveGlobal\b.*bar')
self.assertRegexpMatches(self._ResolveName(func1_block, 'baz'),
r'ResolveGlobal\b.*baz')
self.assertRegexpMatches(self._ResolveName(func2_block, 'foo'),
r'CheckLocal\b.*foo')
self.assertRegexpMatches(self._ResolveName(func2_block, 'bar'),
r'CheckLocal\b.*bar')
self.assertRegexpMatches(self._ResolveName(func2_block, 'baz'),
r'ResolveGlobal\b.*baz')
self.assertRegexpMatches(self._ResolveName(class1_block, 'foo'),
r'ResolveClass\(.*, nil, .*foo')
self.assertRegexpMatches(self._ResolveName(class2_block, 'foo'),
r'ResolveClass\(.*, µfoo, .*foo')
self.assertRegexpMatches(self._ResolveName(keyword_block, 'case'),
r'CheckLocal\b.*µcase, "case"')
def _ResolveName(self, b, name):
writer = util.Writer()
b.resolve_name(writer, name)
return writer.getvalue()
class BlockVisitorTest(unittest.TestCase):
def testAssignSingle(self):
visitor = block.BlockVisitor()
visitor.visit(_ParseStmt('foo = 3'))
self.assertEqual(visitor.vars.keys(), ['foo'])
self.assertRegexpMatches(visitor.vars['foo'].init_expr, r'UnboundLocal')
def testAssignMultiple(self):
visitor = block.BlockVisitor()
visitor.visit(_ParseStmt('foo = bar = 123'))
self.assertEqual(sorted(visitor.vars.keys()), ['bar', 'foo'])
self.assertRegexpMatches(visitor.vars['foo'].init_expr, r'UnboundLocal')
self.assertRegexpMatches(visitor.vars['bar'].init_expr, r'UnboundLocal')
def testAssignTuple(self):
visitor = block.BlockVisitor()
visitor.visit(_ParseStmt('foo, bar = "a", "b"'))
self.assertEqual(sorted(visitor.vars.keys()), ['bar', 'foo'])
self.assertRegexpMatches(visitor.vars['foo'].init_expr, r'UnboundLocal')
self.assertRegexpMatches(visitor.vars['bar'].init_expr, r'UnboundLocal')
def testAssignNested(self):
visitor = block.BlockVisitor()
visitor.visit(_ParseStmt('foo, (bar, baz) = "a", ("b", "c")'))
self.assertEqual(sorted(visitor.vars.keys()), ['bar', 'baz', 'foo'])
self.assertRegexpMatches(visitor.vars['foo'].init_expr, r'UnboundLocal')
self.assertRegexpMatches(visitor.vars['bar'].init_expr, r'UnboundLocal')
self.assertRegexpMatches(visitor.vars['baz'].init_expr, r'UnboundLocal')
def testAugAssignSingle(self):
visitor = block.BlockVisitor()
visitor.visit(_ParseStmt('foo += 3'))
self.assertEqual(visitor.vars.keys(), ['foo'])
self.assertRegexpMatches(visitor.vars['foo'].init_expr, r'UnboundLocal')
def testVisitClassDef(self):
visitor = block.BlockVisitor()
visitor.visit(_ParseStmt('class Foo(object): pass'))
self.assertEqual(visitor.vars.keys(), ['Foo'])
self.assertRegexpMatches(visitor.vars['Foo'].init_expr, r'UnboundLocal')
def testExceptHandler(self):
visitor = block.BlockVisitor()
visitor.visit(_ParseStmt(textwrap.dedent("""\
try:
pass
except Exception as foo:
pass
except TypeError as bar:
pass""")))
self.assertEqual(sorted(visitor.vars.keys()), ['bar', 'foo'])
self.assertRegexpMatches(visitor.vars['foo'].init_expr, r'UnboundLocal')
self.assertRegexpMatches(visitor.vars['bar'].init_expr, r'UnboundLocal')
def testFor(self):
visitor = block.BlockVisitor()
visitor.visit(_ParseStmt('for i in foo: pass'))
self.assertEqual(visitor.vars.keys(), ['i'])
self.assertRegexpMatches(visitor.vars['i'].init_expr, r'UnboundLocal')
def testFunctionDef(self):
visitor = block.BlockVisitor()
visitor.visit(_ParseStmt('def foo(): pass'))
self.assertEqual(visitor.vars.keys(), ['foo'])
self.assertRegexpMatches(visitor.vars['foo'].init_expr, r'UnboundLocal')
def testImport(self):
visitor = block.BlockVisitor()
visitor.visit(_ParseStmt('import foo.bar, baz'))
self.assertEqual(sorted(visitor.vars.keys()), ['baz', 'foo'])
self.assertRegexpMatches(visitor.vars['foo'].init_expr, r'UnboundLocal')
self.assertRegexpMatches(visitor.vars['baz'].init_expr, r'UnboundLocal')
def testImportFrom(self):
visitor = block.BlockVisitor()
visitor.visit(_ParseStmt('from foo.bar import baz, qux'))
self.assertEqual(sorted(visitor.vars.keys()), ['baz', 'qux'])
self.assertRegexpMatches(visitor.vars['baz'].init_expr, r'UnboundLocal')
self.assertRegexpMatches(visitor.vars['qux'].init_expr, r'UnboundLocal')
def testGlobal(self):
visitor = block.BlockVisitor()
visitor.visit(_ParseStmt('global foo, bar'))
self.assertEqual(sorted(visitor.vars.keys()), ['bar', 'foo'])
self.assertIsNone(visitor.vars['foo'].init_expr)
self.assertIsNone(visitor.vars['bar'].init_expr)
def testGlobalIsParam(self):
visitor = block.BlockVisitor()
visitor.vars['foo'] = block.Var('foo', block.Var.TYPE_PARAM, arg_index=0)
self.assertRaisesRegexp(util.ParseError, 'is parameter and global',
visitor.visit, _ParseStmt('global foo'))
def testGlobalUsedPriorToDeclaration(self):
node = pythonparser.parse('foo = 42\nglobal foo')
visitor = block.BlockVisitor()
self.assertRaisesRegexp(util.ParseError, 'used prior to global declaration',
visitor.generic_visit, node)
class FunctionBlockVisitorTest(unittest.TestCase):
def testArgs(self):
func = _ParseStmt('def foo(bar, baz, *args, **kwargs): pass')
visitor = block.FunctionBlockVisitor(func)
self.assertIn('bar', visitor.vars)
self.assertIn('baz', visitor.vars)
self.assertIn('args', visitor.vars)
self.assertIn('kwargs', visitor.vars)
self.assertRegexpMatches(visitor.vars['bar'].init_expr, r'Args\[0\]')
self.assertRegexpMatches(visitor.vars['baz'].init_expr, r'Args\[1\]')
self.assertRegexpMatches(visitor.vars['args'].init_expr, r'Args\[2\]')
self.assertRegexpMatches(visitor.vars['kwargs'].init_expr, r'Args\[3\]')
def testArgsDuplicate(self):
func = _ParseStmt('def foo(bar, baz, bar=None): pass')
self.assertRaisesRegexp(util.ParseError, 'duplicate argument',
block.FunctionBlockVisitor, func)
def testYield(self):
visitor = block.FunctionBlockVisitor(_ParseStmt('def foo(): pass'))
visitor.visit(_ParseStmt('yield "foo"'))
self.assertTrue(visitor.is_generator)
def testYieldExpr(self):
visitor = block.FunctionBlockVisitor(_ParseStmt('def foo(): pass'))
visitor.visit(_ParseStmt('foo = (yield)'))
self.assertTrue(visitor.is_generator)
self.assertEqual(sorted(visitor.vars.keys()), ['foo'])
self.assertRegexpMatches(visitor.vars['foo'].init_expr, r'UnboundLocal')
def _MakeModuleBlock():
importer = imputil.Importer(None, '__main__', '/tmp/foo.py', False)
return block.ModuleBlock(importer, '__main__', '<test>', '',
imputil.FutureFeatures())
def _ParseStmt(stmt_str):
return pythonparser.parse(stmt_str).body[0]
if __name__ == '__main__':
unittest.main()
================================================
FILE: compiler/expr.py
================================================
# coding=utf-8
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Classes representing generated expressions."""
from __future__ import unicode_literals
import abc
from grumpy.compiler import util
class GeneratedExpr(object):
"""GeneratedExpr is a generated Go expression in transcompiled output."""
__metaclass__ = abc.ABCMeta
def __enter__(self):
return self
def __exit__(self, unused_type, unused_value, unused_traceback):
self.free()
@abc.abstractproperty
def expr(self):
pass
def free(self):
pass
class GeneratedTempVar(GeneratedExpr):
"""GeneratedTempVar is an expression result stored in a temporary value."""
def __init__(self, block_, name, type_):
self.block = block_
self.name = name
self.type_ = type_
@property
def expr(self):
return self.name
def free(self):
self.block.free_temp(self)
class GeneratedLocalVar(GeneratedExpr):
"""GeneratedLocalVar is the Go local var corresponding to a Python local."""
def __init__(self, name):
self._name = name
@property
def expr(self):
return util.adjust_local_name(self._name)
class GeneratedLiteral(GeneratedExpr):
"""GeneratedLiteral is a generated literal Go expression."""
def __init__(self, expr):
self._expr = expr
@property
def expr(self):
return self._expr
nil_expr = GeneratedLiteral('nil')
class BlankVar(GeneratedExpr):
def __init__(self):
self.name = '_'
@property
def expr(self):
return '_'
blank_var = BlankVar()
================================================
FILE: compiler/expr_visitor.py
================================================
# coding=utf-8
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Visitor class for traversing Python expressions."""
from __future__ import unicode_literals
import contextlib
import textwrap
from grumpy.compiler import expr
from grumpy.compiler import util
from grumpy.pythonparser import algorithm
from grumpy.pythonparser import ast
class ExprVisitor(algorithm.Visitor):
"""Builds and returns a Go expression representing the Python nodes."""
# pylint: disable=invalid-name,missing-docstring
def __init__(self, stmt_visitor):
self.stmt_visitor = stmt_visitor
self.block = stmt_visitor.block
self.writer = stmt_visitor.writer
def generic_visit(self, node):
msg = 'expression node not yet implemented: ' + type(node).__name__
raise util.ParseError(node, msg)
def visit_Attribute(self, node):
with self.visit(node.value) as obj:
attr = self.block.alloc_temp()
self.writer.write_checked_call2(
attr, 'πg.GetAttr(πF, {}, {}, nil)',
obj.expr, self.block.root.intern(node.attr))
return attr
def visit_BinOp(self, node):
result = self.block.alloc_temp()
with self.visit(node.left) as lhs, self.visit(node.right) as rhs:
op_type = type(node.op)
if op_type in ExprVisitor._BIN_OP_TEMPLATES:
tmpl = ExprVisitor._BIN_OP_TEMPLATES[op_type]
self.writer.write_checked_call2(
result, tmpl, lhs=lhs.expr, rhs=rhs.expr)
else:
msg = 'binary op not implemented: {}'.format(op_type.__name__)
raise util.ParseError(node, msg)
return result
def visit_BoolOp(self, node):
result = self.block.alloc_temp()
with self.block.alloc_temp('bool') as is_true:
if isinstance(node.op, ast.And):
cond_expr = '!' + is_true.expr
else:
cond_expr = is_true.expr
end_label = self.block.genlabel()
num_values = len(node.values)
for i, n in enumerate(node.values):
with self.visit(n) as v:
self.writer.write('{} = {}'.format(result.expr, v.expr))
if i < num_values - 1:
self.writer.write_checked_call2(
is_true, 'πg.IsTrue(πF, {})', result.expr)
self.writer.write_tmpl(textwrap.dedent("""\
if $cond_expr {
\tgoto Label$end_label
}"""), cond_expr=cond_expr, end_label=end_label)
self.writer.write_label(end_label)
return result
def visit_Call(self, node):
# Build positional arguments.
args = expr.nil_expr
if node.args:
args = self.block.alloc_temp('[]*πg.Object')
self.writer.write('{} = πF.MakeArgs({})'.format(args.expr,
len(node.args)))
for i, n in enumerate(node.args):
with self.visit(n) as a:
self.writer.write('{}[{}] = {}'.format(args.expr, i, a.expr))
varg = expr.nil_expr
if node.starargs:
varg = self.visit(node.starargs)
# Build keyword arguments
keywords = expr.nil_expr
if node.keywords:
values = []
for k in node.keywords:
values.append((util.go_str(k.arg), self.visit(k.value)))
keywords = self.block.alloc_temp('πg.KWArgs')
self.writer.write_tmpl('$keywords = πg.KWArgs{', keywords=keywords.name)
with self.writer.indent_block():
for k, v in values:
with v:
self.writer.write_tmpl('{$name, $value},', name=k, value=v.expr)
self.writer.write('}')
kwargs = expr.nil_expr
if node.kwargs:
kwargs = self.visit(node.kwargs)
# Invoke function with all parameters.
with args, varg, keywords, kwargs, self.visit(node.func) as func:
result = self.block.alloc_temp()
if varg is expr.nil_expr and kwargs is expr.nil_expr:
self.writer.write_checked_call2(result, '{}.Call(πF, {}, {})',
func.expr, args.expr, keywords.expr)
else:
self.writer.write_checked_call2(result,
'πg.Invoke(πF, {}, {}, {}, {}, {})',
func.expr, args.expr, varg.expr,
keywords.expr, kwargs.expr)
if node.args:
self.writer.write('πF.FreeArgs({})'.format(args.expr))
return result
def visit_Compare(self, node):
result = self.block.alloc_temp()
lhs = self.visit(node.left)
n = len(node.ops)
end_label = self.block.genlabel() if n > 1 else None
for i, (op, comp) in enumerate(zip(node.ops, node.comparators)):
rhs = self.visit(comp)
op_type = type(op)
if op_type in ExprVisitor._CMP_OP_TEMPLATES:
tmpl = ExprVisitor._CMP_OP_TEMPLATES[op_type]
self.writer.write_checked_call2(
result, tmpl, lhs=lhs.expr, rhs=rhs.expr)
elif isinstance(op, (ast.In, ast.NotIn)):
with self.block.alloc_temp('bool') as contains:
self.writer.write_checked_call2(
contains, 'πg.Contains(πF, {}, {})', rhs.expr, lhs.expr)
invert = '' if isinstance(op, ast.In) else '!'
self.writer.write('{} = πg.GetBool({}{}).ToObject()'.format(
result.name, invert, contains.expr))
elif isinstance(op, ast.Is):
self.writer.write('{} = πg.GetBool({} == {}).ToObject()'.format(
result.name, lhs.expr, rhs.expr))
elif isinstance(op, ast.IsNot):
self.writer.write('{} = πg.GetBool({} != {}).ToObject()'.format(
result.name, lhs.expr, rhs.expr))
else:
raise AssertionError('unrecognized compare op: {}'.format(
op_type.__name__))
if i < n - 1:
with self.block.alloc_temp('bool') as cond:
self.writer.write_checked_call2(
cond, 'πg.IsTrue(πF, {})', result.expr)
self.writer.write_tmpl(textwrap.dedent("""\
if !$cond {
\tgoto Label$end_label
}"""), cond=cond.expr, end_label=end_label)
lhs.free()
lhs = rhs
rhs.free()
if end_label is not None:
self.writer.write_label(end_label)
return result
def visit_Dict(self, node):
with self.block.alloc_temp('*πg.Dict') as d:
self.writer.write('{} = πg.NewDict()'.format(d.name))
for k, v in zip(node.keys, node.values):
with self.visit(k) as key, self.visit(v) as value:
self.writer.write_checked_call1('{}.SetItem(πF, {}, {})',
d.expr, key.expr, value.expr)
result = self.block.alloc_temp()
self.writer.write('{} = {}.ToObject()'.format(result.name, d.expr))
return result
def visit_Set(self, node):
with self.block.alloc_temp('*πg.Set') as s:
self.writer.write('{} = πg.NewSet()'.format(s.name))
for e in node.elts:
with self.visit(e) as value:
self.writer.write_checked_call2(expr.blank_var, '{}.Add(πF, {})',
s.expr, value.expr)
result = self.block.alloc_temp()
self.writer.write('{} = {}.ToObject()'.format(result.name, s.expr))
return result
def visit_DictComp(self, node):
result = self.block.alloc_temp()
elt = ast.Tuple(elts=[node.key, node.value])
gen_node = ast.GeneratorExp(
elt=elt, generators=node.generators, loc=node.loc)
with self.visit(gen_node) as gen:
self.writer.write_checked_call2(
result, 'πg.DictType.Call(πF, πg.Args{{{}}}, nil)', gen.expr)
return result
def visit_ExtSlice(self, node):
result = self.block.alloc_temp()
if len(node.dims) <= util.MAX_DIRECT_TUPLE:
with contextlib.nested(*(self.visit(d) for d in node.dims)) as dims:
self.writer.write('{} = πg.NewTuple{}({}).ToObject()'.format(
result.name, len(dims), ', '.join(d.expr for d in dims)))
else:
with self.block.alloc_temp('[]*πg.Object') as dims:
self.writer.write('{} = make([]*πg.Object, {})'.format(
dims.name, len(node.dims)))
for i, dim in enumerate(node.dims):
with self.visit(dim) as s:
self.writer.write('{}[{}] = {}'.format(dims.name, i, s.expr))
self.writer.write('{} = πg.NewTuple({}...).ToObject()'.format(
result.name, dims.expr))
return result
def visit_GeneratorExp(self, node):
body = ast.Expr(value=ast.Yield(value=node.elt), loc=node.loc)
for comp_node in reversed(node.generators):
for if_node in reversed(comp_node.ifs):
body = ast.If(test=if_node, body=[body], orelse=[], loc=node.loc) # pylint: disable=redefined-variable-type
body = ast.For(target=comp_node.target, iter=comp_node.iter,
body=[body], orelse=[], loc=node.loc)
args = ast.arguments(args=[], vararg=None, kwarg=None, defaults=[])
node = ast.FunctionDef(name='<generator>', args=args, body=[body])
gen_func = self.stmt_visitor.visit_function_inline(node)
result = self.block.alloc_temp()
self.writer.write_checked_call2(
result, '{}.Call(πF, nil, nil)', gen_func.expr)
return result
def visit_IfExp(self, node):
else_label, end_label = self.block.genlabel(), self.block.genlabel()
result = self.block.alloc_temp()
with self.visit(node.test) as test, self.block.alloc_temp('bool') as cond:
self.writer.write_checked_call2(
cond, 'πg.IsTrue(πF, {})', test.expr)
self.writer.write_tmpl(textwrap.dedent("""\
if !$cond {
\tgoto Label$else_label
}"""), cond=cond.expr, else_label=else_label)
with self.visit(node.body) as value:
self.writer.write('{} = {}'.format(result.name, value.expr))
self.writer.write('goto Label{}'.format(end_label))
self.writer.write_label(else_label)
with self.visit(node.orelse) as value:
self.writer.write('{} = {}'.format(result.name, value.expr))
self.writer.write_label(end_label)
return result
def visit_Index(self, node):
result = self.block.alloc_temp()
with self.visit(node.value) as v:
self.writer.write('{} = {}'.format(result.name, v.expr))
return result
def visit_Lambda(self, node):
ret = ast.Return(value=node.body, loc=node.loc)
func_node = ast.FunctionDef(
name='<lambda>', args=node.args, body=[ret])
return self.stmt_visitor.visit_function_inline(func_node)
def visit_List(self, node):
with self._visit_seq_elts(node.elts) as elems:
result = self.block.alloc_temp()
self.writer.write('{} = πg.NewList({}...).ToObject()'.format(
result.expr, elems.expr))
return result
def visit_ListComp(self, node):
result = self.block.alloc_temp()
gen_node = ast.GeneratorExp(
elt=node.elt, generators=node.generators, loc=node.loc)
with self.visit(gen_node) as gen:
self.writer.write_checked_call2(
result, 'πg.ListType.Call(πF, πg.Args{{{}}}, nil)', gen.expr)
return result
def visit_Name(self, node):
return self.block.resolve_name(self.writer, node.id)
def visit_Num(self, node):
if isinstance(node.n, int):
expr_str = 'NewInt({})'.format(node.n)
elif isinstance(node.n, long):
a = abs(node.n)
gobytes = ''
while a:
gobytes = hex(int(a&255)) + ',' + gobytes
a >>= 8
expr_str = 'NewLongFromBytes([]byte{{{}}})'.format(gobytes)
if node.n < 0:
expr_str = expr_str + '.Neg()'
elif isinstance(node.n, float):
expr_str = 'NewFloat({})'.format(node.n)
elif isinstance(node.n, complex):
expr_str = 'NewComplex(complex({}, {}))'.format(node.n.real, node.n.imag)
else:
msg = 'number type not yet implemented: ' + type(node.n).__name__
raise util.ParseError(node, msg)
return expr.GeneratedLiteral('πg.' + expr_str + '.ToObject()')
def visit_Slice(self, node):
result = self.block.alloc_temp()
lower = upper = step = expr.GeneratedLiteral('πg.None')
if node.lower:
lower = self.visit(node.lower)
if node.upper:
upper = self.visit(node.upper)
if node.step:
step = self.visit(node.step)
with lower, upper, step:
self.writer.write_checked_call2(
result, 'πg.SliceType.Call(πF, πg.Args{{{}, {}, {}}}, nil)',
lower.expr, upper.expr, step.expr)
return result
def visit_Subscript(self, node):
rhs = self.visit(node.slice)
result = self.block.alloc_temp()
with rhs, self.visit(node.value) as lhs:
self.writer.write_checked_call2(result, 'πg.GetItem(πF, {}, {})',
lhs.expr, rhs.expr)
return result
def visit_Str(self, node):
if isinstance(node.s, unicode):
expr_str = 'πg.NewUnicode({}).ToObject()'.format(
util.go_str(node.s.encode('utf-8')))
else:
expr_str = '{}.ToObject()'.format(self.block.root.intern(node.s))
return expr.GeneratedLiteral(expr_str)
def visit_Tuple(self, node):
result = self.block.alloc_temp()
if len(node.elts) <= util.MAX_DIRECT_TUPLE:
with contextlib.nested(*(self.visit(e) for e in node.elts)) as elts:
self.writer.write('{} = πg.NewTuple{}({}).ToObject()'.format(
result.name, len(elts), ', '.join(e.expr for e in elts)))
else:
with self._visit_seq_elts(node.elts) as elems:
self.writer.write('{} = πg.NewTuple({}...).ToObject()'.format(
result.expr, elems.expr))
return result
def visit_UnaryOp(self, node):
result = self.block.alloc_temp()
with self.visit(node.operand) as operand:
op_type = type(node.op)
if op_type in ExprVisitor._UNARY_OP_TEMPLATES:
self.writer.write_checked_call2(
result, ExprVisitor._UNARY_OP_TEMPLATES[op_type],
operand=operand.expr)
elif isinstance(node.op, ast.Not):
with self.block.alloc_temp('bool') as is_true:
self.writer.write_checked_call2(
is_true, 'πg.IsTrue(πF, {})', operand.expr)
self.writer.write('{} = πg.GetBool(!{}).ToObject()'.format(
result.name, is_true.expr))
else:
msg = 'unary op not implemented: {}'.format(op_type.__name__)
raise util.ParseError(node, msg)
return result
def visit_Yield(self, node):
if node.value:
value = self.visit(node.value)
else:
value = expr.GeneratedLiteral('πg.None')
resume_label = self.block.genlabel(is_checkpoint=True)
self.writer.write('πF.PushCheckpoint({})'.format(resume_label))
self.writer.write('return {}, nil'.format(value.expr))
self.writer.write_label(resume_label)
result = self.block.alloc_temp()
self.writer.write('{} = πSent'.format(result.name))
return result
_BIN_OP_TEMPLATES = {
ast.BitAnd: 'πg.And(πF, {lhs}, {rhs})',
ast.BitOr: 'πg.Or(πF, {lhs}, {rhs})',
ast.BitXor: 'πg.Xor(πF, {lhs}, {rhs})',
ast.Add: 'πg.Add(πF, {lhs}, {rhs})',
ast.Div: 'πg.Div(πF, {lhs}, {rhs})',
# TODO: Support "from __future__ import division".
ast.FloorDiv: 'πg.FloorDiv(πF, {lhs}, {rhs})',
ast.LShift: 'πg.LShift(πF, {lhs}, {rhs})',
ast.Mod: 'πg.Mod(πF, {lhs}, {rhs})',
ast.Mult: 'πg.Mul(πF, {lhs}, {rhs})',
ast.Pow: 'πg.Pow(πF, {lhs}, {rhs})',
ast.RShift: 'πg.RShift(πF, {lhs}, {rhs})',
ast.Sub: 'πg.Sub(πF, {lhs}, {rhs})',
}
_CMP_OP_TEMPLATES = {
ast.Eq: 'πg.Eq(πF, {lhs}, {rhs})',
ast.Gt: 'πg.GT(πF, {lhs}, {rhs})',
ast.GtE: 'πg.GE(πF, {lhs}, {rhs})',
ast.Lt: 'πg.LT(πF, {lhs}, {rhs})',
ast.LtE: 'πg.LE(πF, {lhs}, {rhs})',
ast.NotEq: 'πg.NE(πF, {lhs}, {rhs})',
}
_UNARY_OP_TEMPLATES = {
ast.Invert: 'πg.Invert(πF, {operand})',
ast.UAdd: 'πg.Pos(πF, {operand})',
ast.USub: 'πg.Neg(πF, {operand})',
}
def _visit_seq_elts(self, elts):
result = self.block.alloc_temp('[]*πg.Object')
self.writer.write('{} = make([]*πg.Object, {})'.format(
result.expr, len(elts)))
for i, e in enumerate(elts):
with self.visit(e) as elt:
self.writer.write('{}[{}] = {}'.format(result.expr, i, elt.expr))
return result
def _node_not_implemented(self, node):
msg = 'node not yet implemented: ' + type(node).__name__
raise util.ParseError(node, msg)
visit_SetComp = _node_not_implemented
================================================
FILE: compiler/expr_visitor_test.py
================================================
# coding=utf-8
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for ExprVisitor."""
from __future__ import unicode_literals
import subprocess
import textwrap
import unittest
from grumpy.compiler import block
from grumpy.compiler import imputil
from grumpy.compiler import shard_test
from grumpy.compiler import stmt
from grumpy import pythonparser
def _MakeExprTest(expr):
def Test(self):
code = 'assert ({}) == ({!r}), {!r}'.format(expr, eval(expr), expr) # pylint: disable=eval-used
self.assertEqual((0, ''), _GrumpRun(code))
return Test
def _MakeLiteralTest(lit, expected=None):
if expected is None:
expected = lit
def Test(self):
status, output = _GrumpRun('print repr({}),'.format(lit))
self.assertEqual(0, status, output)
self.assertEqual(expected, output.strip()) # pylint: disable=eval-used
return Test
def _MakeSliceTest(subscript, want):
"""Define a test function that evaluates a slice expression."""
def Test(self):
code = textwrap.dedent("""\
class Slicer(object):
def __getitem__(self, slice):
print slice
Slicer()[{}]""")
status, output = _GrumpRun(code.format(subscript))
self.assertEqual(0, status, output)
self.assertEqual(want, output.strip())
return Test
class ExprVisitorTest(unittest.TestCase):
# pylint: disable=invalid-name
def testAttribute(self):
code = textwrap.dedent("""\
class Foo(object):
bar = 42
assert Foo.bar == 42""")
self.assertEqual((0, ''), _GrumpRun(code))
testBinOpArithmeticAdd = _MakeExprTest('1 + 2')
testBinOpArithmeticAnd = _MakeExprTest('7 & 12')
testBinOpArithmeticDiv = _MakeExprTest('8 / 4')
testBinOpArithmeticFloorDiv = _MakeExprTest('8 // 4')
testBinOpArithmeticFloorDivRemainder = _MakeExprTest('5 // 2')
testBinOpArithmeticMod = _MakeExprTest('9 % 5')
testBinOpArithmeticMul = _MakeExprTest('3 * 2')
testBinOpArithmeticOr = _MakeExprTest('2 | 6')
testBinOpArithmeticPow = _MakeExprTest('2 ** 16')
testBinOpArithmeticSub = _MakeExprTest('10 - 3')
testBinOpArithmeticXor = _MakeExprTest('3 ^ 5')
testBoolOpTrueAndFalse = _MakeExprTest('True and False')
testBoolOpTrueAndTrue = _MakeExprTest('True and True')
testBoolOpTrueAndExpr = _MakeExprTest('True and 2 == 2')
testBoolOpTrueOrFalse = _MakeExprTest('True or False')
testBoolOpFalseOrFalse = _MakeExprTest('False or False')
testBoolOpFalseOrExpr = _MakeExprTest('False or 2 == 2')
def testCall(self):
code = textwrap.dedent("""\
def foo():
print 'bar'
foo()""")
self.assertEqual((0, 'bar\n'), _GrumpRun(code))
def testCallKeywords(self):
code = textwrap.dedent("""\
def foo(a=1, b=2):
print a, b
foo(b=3)""")
self.assertEqual((0, '1 3\n'), _GrumpRun(code))
def testCallVarArgs(self):
code = textwrap.dedent("""\
def foo(a, b):
print a, b
foo(*(123, 'abc'))""")
self.assertEqual((0, '123 abc\n'), _GrumpRun(code))
def testCallKwargs(self):
code = textwrap.dedent("""\
def foo(a, b=2):
print a, b
foo(**{'a': 4})""")
self.assertEqual((0, '4 2\n'), _GrumpRun(code))
testCompareLT = _MakeExprTest('1 < 2')
testCompareLE = _MakeExprTest('7 <= 12')
testCompareEq = _MakeExprTest('8 == 4')
testCompareNE = _MakeExprTest('9 != 5')
testCompareGE = _MakeExprTest('3 >= 2')
testCompareGT = _MakeExprTest('2 > 6')
testCompareLTLT = _MakeExprTest('3 < 6 < 9')
testCompareLTEq = _MakeExprTest('3 < 6 == 9')
testCompareLTGE = _MakeExprTest('3 < 6 >= -2')
testCompareGTEq = _MakeExprTest('88 > 12 == 12')
testCompareInStr = _MakeExprTest('"1" in "abc"')
testCompareInTuple = _MakeExprTest('1 in (1, 2, 3)')
testCompareNotInTuple = _MakeExprTest('10 < 12 not in (1, 2, 3)')
testDictEmpty = _MakeLiteralTest('{}')
testDictNonEmpty = _MakeLiteralTest("{'foo': 42, 'bar': 43}")
testSetNonEmpty = _MakeLiteralTest("{'foo', 'bar'}", "set(['foo', 'bar'])")
testDictCompFor = _MakeExprTest('{x: str(x) for x in range(3)}')
testDictCompForIf = _MakeExprTest(
'{x: 3 * x for x in range(10) if x % 3 == 0}')
testDictCompForFor = _MakeExprTest(
'{x: y for x in range(3) for y in range(x)}')
testGeneratorExpFor = _MakeExprTest('tuple(int(x) for x in "123")')
testGeneratorExpForIf = _MakeExprTest(
'tuple(x / 3 for x in range(10) if x % 3)')
testGeneratorExprForFor = _MakeExprTest(
'tuple(x + y for x in range(3) for y in range(x + 2))')
testIfExpr = _MakeExprTest('1 if True else 0')
testIfExprCompound = _MakeExprTest('42 if "ab" == "a" + "b" else 24')
testIfExprNested = _MakeExprTest(
'"foo" if "" else "bar" if 0 else "baz"')
testLambda = _MakeExprTest('(lambda: 123)()')
testLambda = _MakeExprTest('(lambda a, b: (a, b))("foo", "bar")')
testLambda = _MakeExprTest('(lambda a, b=3: (a, b))("foo")')
testLambda = _MakeExprTest('(lambda *args: args)(1, 2, 3)')
testLambda = _MakeExprTest('(lambda **kwargs: kwargs)(x="foo", y="bar")')
testListEmpty = _MakeLiteralTest('[]')
testListNonEmpty = _MakeLiteralTest('[1, 2]')
testListCompFor = _MakeExprTest('[int(x) for x in "123"]')
testListCompForIf = _MakeExprTest('[x / 3 for x in range(10) if x % 3]')
testListCompForFor = _MakeExprTest(
'[x + y for x in range(3) for y in range(x + 2)]')
def testNameGlobal(self):
code = textwrap.dedent("""\
foo = 123
assert foo == 123""")
self.assertEqual((0, ''), _GrumpRun(code))
def testNameLocal(self):
code = textwrap.dedent("""\
def foo():
bar = 'abc'
assert bar == 'abc'
foo()""")
self.assertEqual((0, ''), _GrumpRun(code))
testNumInt = _MakeLiteralTest('42')
testNumLong = _MakeLiteralTest('42L')
testNumIntLarge = _MakeLiteralTest('12345678901234567890',
'12345678901234567890L')
testNumFloat = _MakeLiteralTest('102.1')
testNumFloatOnlyDecimal = _MakeLiteralTest('.5', '0.5')
testNumFloatNoDecimal = _MakeLiteralTest('5.', '5.0')
testNumFloatSci = _MakeLiteralTest('1e6', '1000000.0')
testNumFloatSciCap = _MakeLiteralTest('1E6', '1000000.0')
testNumFloatSciCapPlus = _MakeLiteralTest('1E+6', '1000000.0')
testNumFloatSciMinus = _MakeLiteralTest('1e-06')
testNumComplex = _MakeLiteralTest('3j')
testSubscriptDictStr = _MakeExprTest('{"foo": 42}["foo"]')
testSubscriptListInt = _MakeExprTest('[1, 2, 3][2]')
testSubscriptTupleSliceStart = _MakeExprTest('(1, 2, 3)[2:]')
testSubscriptTupleSliceStartStop = _MakeExprTest('(1, 2, 3)[10:11]')
testSubscriptTupleSliceStartStep = _MakeExprTest('(1, 2, 3, 4, 5, 6)[-2::-2]')
testSubscriptStartStop = _MakeSliceTest('2:3', 'slice(2, 3, None)')
testSubscriptMultiDim = _MakeSliceTest('1,2,3', '(1, 2, 3)')
testSubscriptStartStopObjects = _MakeSliceTest(
'True:False', 'slice(True, False, None)')
testSubscriptMultiDimSlice = _MakeSliceTest(
"'foo','bar':'baz':'qux'", "('foo', slice('bar', 'baz', 'qux'))")
testStrEmpty = _MakeLiteralTest("''")
testStrAscii = _MakeLiteralTest("'abc'")
testStrUtf8 = _MakeLiteralTest(r"'\tfoo\n\xcf\x80'")
testStrQuoted = _MakeLiteralTest('\'"foo"\'', '\'"foo"\'')
testStrUtf16 = _MakeLiteralTest("u'\\u0432\\u043e\\u043b\\u043d'")
testTupleEmpty = _MakeLiteralTest('()')
testTupleNonEmpty = _MakeLiteralTest('(1, 2, 3)')
testUnaryOpNot = _MakeExprTest('not True')
testUnaryOpInvert = _MakeExprTest('~4')
testUnaryOpPos = _MakeExprTest('+4')
def _MakeModuleBlock():
return block.ModuleBlock(None, '__main__', '<test>', '',
imputil.FutureFeatures())
def _ParseExpr(expr):
return pythonparser.parse(expr).body[0].value
def _ParseAndVisitExpr(expr):
visitor = stmt.StatementVisitor(_MakeModuleBlock())
visitor.visit_expr(_ParseExpr(expr))
return visitor.writer.getvalue()
def _GrumpRun(cmd):
p = subprocess.Popen(['grumprun'], stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
out, _ = p.communicate(cmd)
return p.returncode, out
if __name__ == '__main__':
shard_test.main()
================================================
FILE: compiler/imputil.py
================================================
# coding=utf-8
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Functionality for importing modules in Grumpy."""
from __future__ import unicode_literals
import collections
import functools
import os
import os.path
from grumpy.compiler import util
from grumpy import pythonparser
from grumpy.pythonparser import algorithm
from grumpy.pythonparser import ast
_NATIVE_MODULE_PREFIX = '__go__/'
class Import(object):
"""Represents a single module import and all its associated bindings.
Each import pertains to a single module that is imported. Thus one import
statement may produce multiple Import objects. E.g. "import foo, bar" makes
an Import object for module foo and another one for module bar.
"""
Binding = collections.namedtuple('Binding', ('bind_type', 'alias', 'value'))
MODULE = "<BindType 'module'>"
MEMBER = "<BindType 'member'>"
def __init__(self, name, script=None, is_native=False):
self.name = name
self.script = script
self.is_native = is_native
self.bindings = []
def add_binding(self, bind_type, alias, value):
self.bindings.append(Import.Binding(bind_type, alias, value))
class Importer(algorithm.Visitor):
"""Visits import nodes and produces corresponding Import objects."""
# pylint: disable=invalid-name,missing-docstring,no-init
def __init__(self, gopath, modname, script, absolute_import):
self.pathdirs = []
if gopath:
self.pathdirs.extend(os.path.join(d, 'src', '__python__')
for d in gopath.split(os.pathsep))
dirname, basename = os.path.split(script)
if basename == '__init__.py':
self.package_dir = dirname
self.package_name = modname
elif (modname.find('.') != -1 and
os.path.isfile(os.path.join(dirname, '__init__.py'))):
self.package_dir = dirname
self.package_name = modname[:modname.rfind('.')]
else:
self.package_dir = None
self.package_name = None
self.absolute_import = absolute_import
def generic_visit(self, node):
raise ValueError('Import cannot visit {} node'.format(type(node).__name__))
def visit_Import(self, node):
imports = []
for alias in node.names:
if alias.name.startswith(_NATIVE_MODULE_PREFIX):
imp = Import(alias.name, is_native=True)
asname = alias.asname if alias.asname else alias.name.split('/')[-1]
imp.add_binding(Import.MODULE, asname, 0)
else:
imp = self._resolve_import(node, alias.name)
if alias.asname:
imp.add_binding(Import.MODULE, alias.asname, imp.name.count('.'))
else:
parts = alias.name.split('.')
imp.add_binding(Import.MODULE, parts[0],
imp.name.count('.') - len(parts) + 1)
imports.append(imp)
return imports
def visit_ImportFrom(self, node):
if any(a.name == '*' for a in node.names):
raise util.ImportError(node, 'wildcard member import is not implemented')
if not node.level and node.module == '__future__':
return []
if not node.level and node.module.startswith(_NATIVE_MODULE_PREFIX):
imp = Import(node.module, is_native=True)
for alias in node.names:
asname = alias.asname or alias.name
imp.add_binding(Import.MEMBER, asname, alias.name)
return [imp]
imports = []
if not node.module:
# Import of the form 'from .. import foo, bar'. All named imports must be
# modules, not module members.
for alias in node.names:
imp = self._resolve_relative_import(node.level, node, alias.name)
imp.add_binding(Import.MODULE, alias.asname or alias.name,
imp.name.count('.'))
imports.append(imp)
return imports
member_imp = None
for alias in node.names:
asname = alias.asname or alias.name
if node.level:
resolver = functools.partial(self._resolve_relative_import, node.level)
else:
resolver = self._resolve_import
try:
imp = resolver(node, '{}.{}'.format(node.module, alias.name))
except util.ImportError:
# A member (not a submodule) is being imported, so bind it.
if not member_imp:
member_imp = resolver(node, node.module)
imports.append(member_imp)
member_imp.add_binding(Import.MEMBER, asname, alias.name)
else:
# Imported name is a submodule within a package, so bind that module.
imp.add_binding(Import.MODULE, asname, imp.name.count('.'))
imports.append(imp)
return imports
def _resolve_import(self, node, modname):
if not self.absolute_import and self.package_dir:
script = find_script(self.package_dir, modname)
if script:
return Import('{}.{}'.format(self.package_name, modname), script)
for dirname in self.pathdirs:
script = find_script(dirname, modname)
if script:
return Import(modname, script)
raise util.ImportError(node, 'no such module: {}'.format(modname))
def _resolve_relative_import(self, level, node, modname):
if not self.package_dir:
raise util.ImportError(node, 'attempted relative import in non-package')
uplevel = level - 1
if uplevel > self.package_name.count('.'):
raise util.ImportError(
node, 'attempted relative import beyond toplevel package')
dirname = os.path.normpath(os.path.join(
self.package_dir, *(['..'] * uplevel)))
script = find_script(dirname, modname)
if not script:
raise util.ImportError(node, 'no such module: {}'.format(modname))
parts = self.package_name.split('.')
return Import('.'.join(parts[:len(parts)-uplevel]) + '.' + modname, script)
class _ImportCollector(algorithm.Visitor):
# pylint: disable=invalid-name
def __init__(self, importer, future_node):
self.importer = importer
self.future_node = future_node
self.imports = []
def visit_Import(self, node):
self.imports.extend(self.importer.visit(node))
def visit_ImportFrom(self, node):
if node.module == '__future__':
if node != self.future_node:
raise util.LateFutureError(node)
return
self.imports.extend(self.importer.visit(node))
def collect_imports(modname, script, gopath):
with open(script) as py_file:
py_contents = py_file.read()
mod = pythonparser.parse(py_contents)
future_node, future_features = parse_future_features(mod)
importer = Importer(gopath, modname, script, future_features.absolute_import)
collector = _ImportCollector(importer, future_node)
collector.visit(mod)
return collector.imports
def calculate_transitive_deps(modname, script, gopath):
"""Determines all modules that script transitively depends upon."""
deps = set()
def calc(modname, script):
if modname in deps:
return
deps.add(modname)
for imp in collect_imports(modname, script, gopath):
if imp.is_native:
deps.add(imp.name)
continue
parts = imp.name.split('.')
calc(imp.name, imp.script)
if len(parts) == 1:
continue
# For submodules, the parent packages are also deps.
package_dir, filename = os.path.split(imp.script)
if filename == '__init__.py':
package_dir = os.path.dirname(package_dir)
for i in xrange(len(parts) - 1, 0, -1):
modname = '.'.join(parts[:i])
script = os.path.join(package_dir, '__init__.py')
calc(modname, script)
package_dir = os.path.dirname(package_dir)
calc(modname, script)
deps.remove(modname)
return deps
def find_script(dirname, name):
prefix = os.path.join(dirname, name.replace('.', os.sep))
script = prefix + '.py'
if os.path.isfile(script):
return script
script = os.path.join(prefix, '__init__.py')
if os.path.isfile(script):
return script
return None
_FUTURE_FEATURES = (
'absolute_import',
'division',
'print_function',
'unicode_literals',
)
_IMPLEMENTED_FUTURE_FEATURES = (
'absolute_import',
'print_function',
'unicode_literals'
)
# These future features are already in the language proper as of 2.6, so
# importing them via __future__ has no effect.
_REDUNDANT_FUTURE_FEATURES = ('generators', 'with_statement', 'nested_scopes')
class FutureFeatures(object):
"""Spec for future feature flags imported by a module."""
def __init__(self, absolute_import=False, division=False,
print_function=False, unicode_literals=False):
self.absolute_import = absolute_import
self.division = division
self.print_function = print_function
self.unicode_literals = unicode_literals
def _make_future_features(node):
"""Processes a future import statement, returning set of flags it defines."""
assert isinstance(node, ast.ImportFrom)
assert node.module == '__future__'
features = FutureFeatures()
for alias in node.names:
name = alias.name
if name in _FUTURE_FEATURES:
if name not in _IMPLEMENTED_FUTURE_FEATURES:
msg = 'future feature {} not yet implemented by grumpy'.format(name)
raise util.ParseError(node, msg)
setattr(features, name, True)
elif name == 'braces':
raise util.ParseError(node, 'not a chance')
elif name not in _REDUNDANT_FUTURE_FEATURES:
msg = 'future feature {} is not defined'.format(name)
raise util.ParseError(node, msg)
return features
def parse_future_features(mod):
"""Accumulates a set of flags for the compiler __future__ imports."""
assert isinstance(mod, ast.Module)
found_docstring = False
for node in mod.body:
if isinstance(node, ast.ImportFrom):
if node.module == '__future__':
return node, _make_future_features(node)
break
elif isinstance(node, ast.Expr) and not found_docstring:
if not isinstance(node.value, ast.Str):
break
found_docstring = True
else:
break
return None, FutureFeatures()
================================================
FILE: compiler/imputil_test.py
================================================
# coding=utf-8
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests ImportVisitor and related classes."""
from __future__ import unicode_literals
import copy
import os
import shutil
import tempfile
import textwrap
import unittest
from grumpy.compiler import imputil
from grumpy.compiler import util
from grumpy import pythonparser
class ImportVisitorTest(unittest.TestCase):
_PATH_SPEC = {
'foo.py': None,
'qux.py': None,
'bar/': {
'fred/': {
'__init__.py': None,
'quux.py': None,
},
'__init__.py': None,
'baz.py': None,
'foo.py': None,
},
'baz.py': None,
}
def setUp(self):
self.rootdir = tempfile.mkdtemp()
self.pydir = os.path.join(self.rootdir, 'src', '__python__')
self._materialize_tree(
self.rootdir, {'src/': {'__python__/': self._PATH_SPEC}})
foo_script = os.path.join(self.rootdir, 'foo.py')
self.importer = imputil.Importer(self.rootdir, 'foo', foo_script, False)
bar_script = os.path.join(self.pydir, 'bar', '__init__.py')
self.bar_importer = imputil.Importer(
self.rootdir, 'bar', bar_script, False)
fred_script = os.path.join(self.pydir, 'bar', 'fred', '__init__.py')
self.fred_importer = imputil.Importer(
self.rootdir, 'bar.fred', fred_script, False)
self.foo_import = imputil.Import(
'foo', os.path.join(self.pydir, 'foo.py'))
self.qux_import = imputil.Import(
'qux', os.path.join(self.pydir, 'qux.py'))
self.bar_import = imputil.Import(
'bar', os.path.join(self.pydir, 'bar/__init__.py'))
self.fred_import = imputil.Import(
'bar.fred', os.path.join(self.pydir, 'bar/fred/__init__.py'))
self.quux_import = imputil.Import(
'bar.fred.quux', os.path.join(self.pydir, 'bar/fred/quux.py'))
self.baz2_import = imputil.Import(
'bar.baz', os.path.join(self.pydir, 'bar/baz.py'))
self.foo2_import = imputil.Import(
'bar.foo', os.path.join(self.pydir, 'bar/foo.py'))
self.baz_import = imputil.Import(
'baz', os.path.join(self.pydir, 'baz.py'))
def tearDown(self):
shutil.rmtree(self.rootdir)
def testImportEmptyPath(self):
importer = imputil.Importer(None, 'foo', 'foo.py', False)
self.assertRaises(util.ImportError, importer.visit,
pythonparser.parse('import bar').body[0])
def testImportTopLevelModule(self):
imp = copy.deepcopy(self.qux_import)
imp.add_binding(imputil.Import.MODULE, 'qux', 0)
self._check_imports('import qux', [imp])
def testImportTopLevelPackage(self):
imp = copy.deepcopy(self.bar_import)
imp.add_binding(imputil.Import.MODULE, 'bar', 0)
self._check_imports('import bar', [imp])
def testImportPackageModuleAbsolute(self):
imp = copy.deepcopy(self.baz2_import)
imp.add_binding(imputil.Import.MODULE, 'bar', 0)
self._check_imports('import bar.baz', [imp])
def testImportFromSubModule(self):
imp = copy.deepcopy(self.baz2_import)
imp.add_binding(imputil.Import.MODULE, 'baz', 1)
self._check_imports('from bar import baz', [imp])
def testImportPackageModuleRelative(self):
imp = copy.deepcopy(self.baz2_import)
imp.add_binding(imputil.Import.MODULE, 'baz', 1)
got = self.bar_importer.visit(pythonparser.parse('import baz').body[0])
self._assert_imports_equal([imp], got)
def testImportPackageModuleRelativeFromSubModule(self):
imp = copy.deepcopy(self.baz2_import)
imp.add_binding(imputil.Import.MODULE, 'baz', 1)
foo_script = os.path.join(self.pydir, 'bar', 'foo.py')
importer = imputil.Importer(self.rootdir, 'bar.foo', foo_script, False)
got = importer.visit(pythonparser.parse('import baz').body[0])
self._assert_imports_equal([imp], got)
def testImportPackageModuleAbsoluteImport(self):
imp = copy.deepcopy(self.baz_import)
imp.add_binding(imputil.Import.MODULE, 'baz', 0)
bar_script = os.path.join(self.pydir, 'bar', '__init__.py')
importer = imputil.Importer(self.rootdir, 'bar', bar_script, True)
got = importer.visit(pythonparser.parse('import baz').body[0])
self._assert_imports_equal([imp], got)
def testImportMultiple(self):
imp1 = copy.deepcopy(self.foo_import)
imp1.add_binding(imputil.Import.MODULE, 'foo', 0)
imp2 = copy.deepcopy(self.baz2_import)
imp2.add_binding(imputil.Import.MODULE, 'bar', 0)
self._check_imports('import foo, bar.baz', [imp1, imp2])
def testImportAs(self):
imp = copy.deepcopy(self.foo_import)
imp.add_binding(imputil.Import.MODULE, 'bar', 0)
self._check_imports('import foo as bar', [imp])
def testImportFrom(self):
imp = copy.deepcopy(self.baz2_import)
imp.add_binding(imputil.Import.MODULE, 'baz', 1)
self._check_imports('from bar import baz', [imp])
def testImportFromMember(self):
imp = copy.deepcopy(self.foo_import)
imp.add_binding(imputil.Import.MEMBER, 'bar', 'bar')
self._check_imports('from foo import bar', [imp])
def testImportFromMultiple(self):
imp1 = copy.deepcopy(self.baz2_import)
imp1.add_binding(imputil.Import.MODULE, 'baz', 1)
imp2 = copy.deepcopy(self.foo2_import)
imp2.add_binding(imputil.Import.MODULE, 'foo', 1)
self._check_imports('from bar import baz, foo', [imp1, imp2])
def testImportFromMixedMembers(self):
imp1 = copy.deepcopy(self.bar_import)
imp1.add_binding(imputil.Import.MEMBER, 'qux', 'qux')
imp2 = copy.deepcopy(self.baz2_import)
imp2.add_binding(imputil.Import.MODULE, 'baz', 1)
self._check_imports('from bar import qux, baz', [imp1, imp2])
def testImportFromAs(self):
imp = copy.deepcopy(self.baz2_import)
imp.add_binding(imputil.Import.MODULE, 'qux', 1)
self._check_imports('from bar import baz as qux', [imp])
def testImportFromAsMembers(self):
imp = copy.deepcopy(self.foo_import)
imp.add_binding(imputil.Import.MEMBER, 'baz', 'bar')
self._check_imports('from foo import bar as baz', [imp])
def testImportFromWildcardRaises(self):
self.assertRaises(util.ImportError, self.importer.visit,
pythonparser.parse('from foo import *').body[0])
def testImportFromFuture(self):
self._check_imports('from __future__ import print_function', [])
def testImportFromNative(self):
imp = imputil.Import('__go__/fmt', is_native=True)
imp.add_binding(imputil.Import.MEMBER, 'Printf', 'Printf')
self._check_imports('from "__go__/fmt" import Printf', [imp])
def testImportFromNativeMultiple(self):
imp = imputil.Import('__go__/fmt', is_native=True)
imp.add_binding(imputil.Import.MEMBER, 'Printf', 'Printf')
imp.add_binding(imputil.Import.MEMBER, 'Println', 'Println')
self._check_imports('from "__go__/fmt" import Printf, Println', [imp])
def testImportFromNativeAs(self):
imp = imputil.Import('__go__/fmt', is_native=True)
imp.add_binding(imputil.Import.MEMBER, 'foo', 'Printf')
self._check_imports('from "__go__/fmt" import Printf as foo', [imp])
def testRelativeImportNonPackage(self):
self.assertRaises(util.ImportError, self.importer.visit,
pythonparser.parse('from . import bar').body[0])
def testRelativeImportBeyondTopLevel(self):
self.assertRaises(util.ImportError, self.bar_importer.visit,
pythonparser.parse('from .. import qux').body[0])
def testRelativeModuleNoExist(self):
self.assertRaises(util.ImportError, self.bar_importer.visit,
pythonparser.parse('from . import qux').body[0])
def testRelativeModule(self):
imp = copy.deepcopy(self.foo2_import)
imp.add_binding(imputil.Import.MODULE, 'foo', 1)
node = pythonparser.parse('from . import foo').body[0]
self._assert_imports_equal([imp], self.bar_importer.visit(node))
def testRelativeModuleFromSubModule(self):
imp = copy.deepcopy(self.foo2_import)
imp.add_binding(imputil.Import.MODULE, 'foo', 1)
baz_script = os.path.join(self.pydir, 'bar', 'baz.py')
importer = imputil.Importer(self.rootdir, 'bar.baz', baz_script, False)
node = pythonparser.parse('from . import foo').body[0]
self._assert_imports_equal([imp], importer.visit(node))
def testRelativeModuleMember(self):
imp = copy.deepcopy(self.foo2_import)
imp.add_binding(imputil.Import.MEMBER, 'qux', 'qux')
node = pythonparser.parse('from .foo import qux').body[0]
self._assert_imports_equal([imp], self.bar_importer.visit(node))
def testRelativeModuleMemberMixed(self):
imp1 = copy.deepcopy(self.fred_import)
imp1.add_binding(imputil.Import.MEMBER, 'qux', 'qux')
imp2 = copy.deepcopy(self.quux_import)
imp2.add_binding(imputil.Import.MODULE, 'quux', 2)
node = pythonparser.parse('from .fred import qux, quux').body[0]
self._assert_imports_equal([imp1, imp2], self.bar_importer.visit(node))
def testRelativeUpLevel(self):
imp = copy.deepcopy(self.foo2_import)
imp.add_binding(imputil.Import.MODULE, 'foo', 1)
node = pythonparser.parse('from .. import foo').body[0]
self._assert_imports_equal([imp], self.fred_importer.visit(node))
def testRelativeUpLevelMember(self):
imp = copy.deepcopy(self.foo2_import)
imp.add_binding(imputil.Import.MEMBER, 'qux', 'qux')
node = pythonparser.parse('from ..foo import qux').body[0]
self._assert_imports_equal([imp], self.fred_importer.visit(node))
def _check_imports(self, stmt, want):
got = self.importer.visit(pythonparser.parse(stmt).body[0])
self._assert_imports_equal(want, got)
def _assert_imports_equal(self, want, got):
self.assertEqual([imp.__dict__ for imp in want],
[imp.__dict__ for imp in got])
def _materialize_tree(self, dirname, spec):
for name, sub_spec in spec.iteritems():
if name.endswith('/'):
subdir = os.path.join(dirname, name[:-1])
os.mkdir(subdir)
self._materialize_tree(subdir, sub_spec)
else:
with open(os.path.join(dirname, name), 'w'):
pass
class MakeFutureFeaturesTest(unittest.TestCase):
def testImportFromFuture(self):
testcases = [
('from __future__ import print_function',
imputil.FutureFeatures(print_function=True)),
('from __future__ import generators', imputil.FutureFeatures()),
('from __future__ import generators, print_function',
imputil.FutureFeatures(print_function=True)),
]
for tc in testcases:
source, want = tc
mod = pythonparser.parse(textwrap.dedent(source))
node = mod.body[0]
got = imputil._make_future_features(node) # pylint: disable=protected-access
self.assertEqual(want.__dict__, got.__dict__)
def testImportFromFutureParseError(self):
testcases = [
# NOTE: move this group to testImportFromFuture as they are implemented
# by grumpy
('from __future__ import division',
r'future feature \w+ not yet implemented'),
('from __future__ import braces', 'not a chance'),
('from __future__ import nonexistant_feature',
r'future feature \w+ is not defined'),
]
for tc in testcases:
source, want_regexp = tc
mod = pythonparser.parse(source)
node = mod.body[0]
self.assertRaisesRegexp(util.ParseError, want_regexp,
imputil._make_future_features, node) # pylint: disable=protected-access
class ParseFutureFeaturesTest(unittest.TestCase):
def testFutureFeatures(self):
testcases = [
('from __future__ import print_function',
imputil.FutureFeatures(print_function=True)),
("""\
"module docstring"
from __future__ import print_function
""", imputil.FutureFeatures(print_function=True)),
("""\
"module docstring"
from __future__ import print_function, with_statement
from __future__ import nested_scopes
""", imputil.FutureFeatures(print_function=True)),
('from __future__ import absolute_import',
imputil.FutureFeatures(absolute_import=True)),
('from __future__ import absolute_import, print_function',
imputil.FutureFeatures(absolute_import=True, print_function=True)),
('foo = 123\nfrom __future__ import print_function',
imputil.FutureFeatures()),
('import os\nfrom __future__ import print_function',
imputil.FutureFeatures()),
]
for tc in testcases:
source, want = tc
mod = pythonparser.parse(textwrap.dedent(source))
_, got = imputil.parse_future_features(mod)
self.assertEqual(want.__dict__, got.__dict__)
def testUnimplementedFutureRaises(self):
mod = pythonparser.parse('from __future__ import division')
msg = 'future feature division not yet implemented by grumpy'
self.assertRaisesRegexp(util.ParseError, msg,
imputil.parse_future_features, mod)
def testUndefinedFutureRaises(self):
mod = pythonparser.parse('from __future__ import foo')
self.assertRaisesRegexp(
util.ParseError, 'future feature foo is not defined',
imputil.parse_future_features, mod)
if __name__ == '__main__':
unittest.main()
================================================
FILE: compiler/shard_test.py
================================================
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Wrapper for unit tests that loads a subset of all test methods."""
from __future__ import unicode_literals
import argparse
import random
import re
import sys
import unittest
class _ShardAction(argparse.Action):
def __call__(self, parser, args, values, option_string=None):
match = re.match(r'(\d+)of(\d+)$', values)
if not match:
raise argparse.ArgumentError(self, 'bad shard spec: {}'.format(values))
shard = int(match.group(1))
count = int(match.group(2))
if shard < 1 or count < 1 or shard > count:
raise argparse.ArgumentError(self, 'bad shard spec: {}'.format(values))
setattr(args, self.dest, (shard, count))
class _ShardTestLoader(unittest.TestLoader):
def __init__(self, shard, count):
super(_ShardTestLoader, self).__init__()
self.shard = shard
self.count = count
def getTestCaseNames(self, test_case_cls):
names = super(_ShardTestLoader, self).getTestCaseNames(test_case_cls)
state = random.getstate()
random.seed(self.count)
random.shuffle(names)
random.setstate(state)
n = len(names)
# self.shard is one-based.
return names[(self.shard - 1) * n / self.count:self.shard * n / self.count]
class _ShardTestRunner(object):
def run(self, test):
result = unittest.TestResult()
unittest.registerResult(result)
test(result)
for kind, errors in [('FAIL', result.failures), ('ERROR', result.errors)]:
for test, err in errors:
sys.stderr.write('{} {}\n{}'.format(test, kind, err))
return result
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--shard', default=(1, 1), action=_ShardAction)
parser.add_argument('unittest_args', nargs='*')
args = parser.parse_args()
unittest.main(argv=[sys.argv[0]] + args.unittest_args,
testLoader=_ShardTestLoader(*args.shard),
testRunner=_ShardTestRunner)
================================================
FILE: compiler/stmt.py
================================================
# coding=utf-8
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Visitor class for traversing Python statements."""
from __future__ import unicode_literals
import string
import textwrap
from grumpy.compiler import block
from grumpy.compiler import expr
from grumpy.compiler import expr_visitor
from grumpy.compiler import imputil
from grumpy.compiler import util
from grumpy.pythonparser import algorithm
from grumpy.pythonparser import ast
_NATIVE_TYPE_PREFIX = 'type_'
# Partial list of known vcs for go module import
# Full list can be found at https://golang.org/src/cmd/go/vcs.go
# TODO: Use official vcs.go module instead of partial list
_KNOWN_VCS = [
'golang.org', 'github.com', 'bitbucket.org', 'git.apache.org',
'git.openstack.org', 'launchpad.net'
]
_nil_expr = expr.nil_expr
class StatementVisitor(algorithm.Visitor):
"""Outputs Go statements to a Writer for the given Python nodes."""
# pylint: disable=invalid-name,missing-docstring
def __init__(self, block_, future_node=None):
self.block = block_
self.future_node = future_node
self.writer = util.Writer()
self.expr_visitor = expr_visitor.ExprVisitor(self)
def generic_visit(self, node):
msg = 'node not yet implemented: {}'.format(type(node).__name__)
raise util.ParseError(node, msg)
def visit_expr(self, node):
return self.expr_visitor.visit(node)
def visit_Assert(self, node):
self._write_py_context(node.lineno)
# TODO: Only evaluate msg if cond is false.
with self.visit_expr(node.msg) if node.msg else _nil_expr as msg,\
self.visit_expr(node.test) as cond:
self.writer.write_checked_call1(
'πg.Assert(πF, {}, {})', cond.expr, msg.expr)
def visit_AugAssign(self, node):
op_type = type(node.op)
if op_type not in StatementVisitor._AUG_ASSIGN_TEMPLATES:
fmt = 'augmented assignment op not implemented: {}'
raise util.ParseError(node, fmt.format(op_type.__name__))
self._write_py_context(node.lineno)
with self.visit_expr(node.target) as target,\
self.visit_expr(node.value) as value,\
self.block.alloc_temp() as temp:
self.writer.write_checked_call2(
temp, StatementVisitor._AUG_ASSIGN_TEMPLATES[op_type],
lhs=target.expr, rhs=value.expr)
self._assign_target(node.target, temp.expr)
def visit_Assign(self, node):
self._write_py_context(node.lineno)
with self.visit_expr(node.value) as value:
for target in node.targets:
self._tie_target(target, value.expr)
def visit_Break(self, node):
if not self.block.loop_stack:
raise util.ParseError(node, "'break' not in loop")
self._write_py_context(node.lineno)
self.writer.write_tmpl(textwrap.dedent("""\
$breakvar = true
continue"""), breakvar=self.block.top_loop().breakvar.name)
def visit_ClassDef(self, node):
# Since we only care about global vars, we end up throwing away the locals
# collected by BlockVisitor. But use it anyway since it buys us detection of
# assignment to vars that are later declared global.
block_visitor = block.BlockVisitor()
for child in node.body:
block_visitor.visit(child)
global_vars = {v.name for v in block_visitor.vars.values()
if v.type == block.Var.TYPE_GLOBAL}
# Visit all the statements inside body of the class definition.
body_visitor = StatementVisitor(block.ClassBlock(
self.block, node.name, global_vars), self.future_node)
# Indent so that the function body is aligned with the goto labels.
with body_visitor.writer.indent_block():
body_visitor._visit_each(node.body) # pylint: disable=protected-access
self._write_py_context(node.lineno)
with self.block.alloc_temp('*πg.Dict') as cls, \
self.block.alloc_temp() as mod_name, \
self.block.alloc_temp('[]*πg.Object') as bases, \
self.block.alloc_temp() as meta:
self.writer.write('{} = make([]*πg.Object, {})'.format(
bases.expr, len(node.bases)))
for i, b in enumerate(node.bases):
with self.visit_expr(b) as b:
self.writer.write('{}[{}] = {}'.format(bases.expr, i, b.expr))
self.writer.write('{} = πg.NewDict()'.format(cls.name))
self.writer.write_checked_call2(
mod_name, 'πF.Globals().GetItem(πF, {}.ToObject())',
self.block.root.intern('__name__'))
self.writer.write_checked_call1(
'{}.SetItem(πF, {}.ToObject(), {})',
cls.expr, self.block.root.intern('__module__'), mod_name.expr)
tmpl = textwrap.dedent("""
_, πE = πg.NewCode($name, $filename, nil, 0, func(πF *πg.Frame, _ []*πg.Object) (*πg.Object, *πg.BaseException) {
\tπClass := $cls
\t_ = πClass""")
self.writer.write_tmpl(tmpl, name=util.go_str(node.name),
filename=util.go_str(self.block.root.filename),
cls=cls.expr)
with self.writer.indent_block():
self.writer.write_temp_decls(body_visitor.block)
self.writer.write_block(body_visitor.block,
body_visitor.writer.getvalue())
self.writer.write('return nil, nil')
tmpl = textwrap.dedent("""\
}).Eval(πF, πF.Globals(), nil, nil)
if πE != nil {
\tcontinue
}
if $meta, πE = $cls.GetItem(πF, $metaclass_str.ToObject()); πE != nil {
\tcontinue
}
if $meta == nil {
\t$meta = πg.TypeType.ToObject()
}""")
self.writer.write_tmpl(
tmpl, meta=meta.name, cls=cls.expr,
metaclass_str=self.block.root.intern('__metaclass__'))
with self.block.alloc_temp() as type_:
type_expr = ('{}.Call(πF, []*πg.Object{{πg.NewStr({}).ToObject(), '
'πg.NewTuple({}...).ToObject(), {}.ToObject()}}, nil)')
self.writer.write_checked_call2(
type_, type_expr, meta.expr,
util.go_str(node.name), bases.expr, cls.expr)
self.block.bind_var(self.writer, node.name, type_.expr)
def visit_Continue(self, node):
if not self.block.loop_stack:
raise util.ParseError(node, "'continue' not in loop")
self._write_py_context(node.lineno)
self.writer.write('continue')
def visit_Delete(self, node):
self._write_py_context(node.lineno)
for target in node.targets:
if isinstance(target, ast.Attribute):
with self.visit_expr(target.value) as t:
self.writer.write_checked_call1(
'πg.DelAttr(πF, {}, {})', t.expr,
self.block.root.intern(target.attr))
elif isinstance(target, ast.Name):
self.block.del_var(self.writer, target.id)
elif isinstance(target, ast.Subscript):
with self.visit_expr(target.value) as t,\
self.visit_expr(target.slice) as index:
self.writer.write_checked_call1('πg.DelItem(πF, {}, {})',
t.expr, index.expr)
else:
msg = 'del target not implemented: {}'.format(type(target).__name__)
raise util.ParseError(node, msg)
def visit_Expr(self, node):
self._write_py_context(node.lineno)
self.visit_expr(node.value).free()
def visit_For(self, node):
with self.block.alloc_temp() as i:
with self.visit_expr(node.iter) as iter_expr:
self.writer.write_checked_call2(i, 'πg.Iter(πF, {})', iter_expr.expr)
def testfunc(testvar):
with self.block.alloc_temp() as n:
self.writer.write_tmpl(textwrap.dedent("""\
if $n, πE = πg.Next(πF, $i); πE != nil {
\tisStop, exc := πg.IsInstance(πF, πE.ToObject(), πg.StopIterationType.ToObject())
\tif exc != nil {
\t\tπE = exc
\t} else if isStop {
\t\tπE = nil
\t\tπF.RestoreExc(nil, nil)
\t}
\t$testvar = !isStop
} else {
\t$testvar = true"""), n=n.name, i=i.expr, testvar=testvar.name)
with self.writer.indent_block():
self._tie_target(node.target, n.expr)
self.writer.write('}')
self._visit_loop(testfunc, node)
def visit_FunctionDef(self, node):
self._write_py_context(node.lineno + len(node.decorator_list))
func = self.visit_function_inline(node)
self.block.bind_var(self.writer, node.name, func.expr)
while node.decorator_list:
decorator = node.decorator_list.pop()
wrapped = ast.Name(id=node.name)
decorated = ast.Call(func=decorator, args=[wrapped], keywords=[],
starargs=None, kwargs=None)
target = ast.Assign(targets=[wrapped], value=decorated, loc=node.loc)
self.visit_Assign(target)
def visit_Global(self, node):
self._write_py_context(node.lineno)
def visit_If(self, node):
# Collect the nodes for each if/elif/else body and write the dispatching
# switch statement.
bodies = []
# An elif clause is represented as a single If node within the orelse
# section of the previous If node. Thus this loop terminates once we are
# done all the elif clauses at which time the orelse var will contain the
# nodes (if any) for the else clause.
orelse = [node]
while len(orelse) == 1 and isinstance(orelse[0], ast.If):
ifnode = orelse[0]
with self.visit_expr(ifnode.test) as cond:
label = self.block.genlabel()
# We goto the body of the if statement instead of executing it inline
# because the body itself may be a goto target and Go does not support
# jumping to targets inside a block.
with self.block.alloc_temp('bool') as is_true:
self.writer.write_tmpl(textwrap.dedent("""\
if $is_true, πE = πg.IsTrue(πF, $cond); πE != nil {
\tcontinue
}
if $is_true {
\tgoto Label$label
}"""), is_true=is_true.name, cond=cond.expr, label=label)
bodies.append((label, ifnode.body, ifnode.lineno))
orelse = ifnode.orelse
default_label = end_label = self.block.genlabel()
if orelse:
end_label = self.block.genlabel()
# The else is not represented by ast and thus there is no lineno.
bodies.append((default_label, orelse, None))
self.writer.write('goto Label{}'.format(default_label))
# Write the body of each clause.
for label, body, lineno in bodies:
if lineno:
self._write_py_context(lineno)
self.writer.write_label(label)
self._visit_each(body)
self.writer.write('goto Label{}'.format(end_label))
self.writer.write_label(end_label)
def visit_Import(self, node):
self._write_py_context(node.lineno)
for imp in self.block.root.importer.visit(node):
self._import_and_bind(imp)
def visit_ImportFrom(self, node):
self._write_py_context(node.lineno)
if node.module == '__future__' and node != self.future_node:
raise util.LateFutureError(node)
for imp in self.block.root.importer.visit(node):
self._import_and_bind(imp)
def visit_Module(self, node):
self._visit_each(node.body)
def visit_Pass(self, node):
self._write_py_context(node.lineno)
def visit_Print(self, node):
if self.block.root.future_features.print_function:
raise util.ParseError(node, 'syntax error (print is not a keyword)')
self._write_py_context(node.lineno)
with self.block.alloc_temp('[]*πg.Object') as args:
self.writer.write('{} = make([]*πg.Object, {})'.format(
args.expr, len(node.values)))
for i, v in enumerate(node.values):
with self.visit_expr(v) as arg:
self.writer.write('{}[{}] = {}'.format(args.expr, i, arg.expr))
self.writer.write_checked_call1('πg.Print(πF, {}, {})', args.expr,
'true' if node.nl else 'false')
def visit_Raise(self, node):
with self.visit_expr(node.exc) if node.exc else _nil_expr as t,\
self.visit_expr(node.inst) if node.inst else _nil_expr as inst,\
self.visit_expr(node.tback) if node.tback else _nil_expr as tb:
if node.inst:
assert node.exc, 'raise had inst but no type'
if node.tback:
assert node.inst, 'raise had tback but no inst'
self._write_py_context(node.lineno)
self.writer.write('πE = πF.Raise({}, {}, {})'.format(
t.expr, inst.expr, tb.expr))
self.writer.write('continue')
def visit_Return(self, node):
assert isinstance(self.block, block.FunctionBlock)
self._write_py_context(node.lineno)
if self.block.is_generator and node.value:
raise util.ParseError(node, 'returning a value in a generator function')
if node.value:
with self.visit_expr(node.value) as value:
self.writer.write('πR = {}'.format(value.expr))
else:
self.writer.write('πR = πg.None')
self.writer.write('continue')
def visit_Try(self, node):
# The general structure generated by this method is shown below:
#
# checkpoints.Push(Except)
# <try body>
# Checkpoints.Pop()
# <else body>
# goto Finally
# Except:
# <dispatch table>
# Handler1:
# <handler 1 body>
# Checkpoints.Pop() // Finally
# goto Finally
# Handler2:
# <handler 2 body>
# Checkpoints.Pop() // Finally
# goto Finally
# ...
# Finally:
# <finally body>
#
# The dispatch table maps the current exception to the appropriate handler
# label according to the exception clauses.
# Write the try body.
self._write_py_context(node.lineno)
finally_label = self.block.genlabel(is_checkpoint=bool(node.finalbody))
if node.finalbody:
self.writer.write('πF.PushCheckpoint({})'.format(finally_label))
except_label = None
if node.handlers:
except_label = self.block.genlabel(is_checkpoint=True)
self.writer.write('πF.PushCheckpoint({})'.format(except_label))
self._visit_each(node.body)
if except_label:
self.writer.write('πF.PopCheckpoint()') # except_label
if node.orelse:
self._visit_each(node.orelse)
if node.finalbody:
self.writer.write('πF.PopCheckpoint()') # finally_label
self.writer.write('goto Label{}'.format(finally_label))
with self.block.alloc_temp('*πg.BaseException') as exc:
if except_label:
with self.block.alloc_temp('*πg.Traceback') as tb:
self.writer.write_label(except_label)
self.writer.write_tmpl(textwrap.dedent("""\
if πE == nil {
continue
}
πE = nil
$exc, $tb = πF.ExcInfo()"""), exc=exc.expr, tb=tb.expr)
handler_labels = self._write_except_dispatcher(
exc.expr, tb.expr, node.handlers)
# Write the bodies of each of the except handlers.
for handler_label, except_node in zip(handler_labels, node.handlers):
self._write_except_block(handler_label, exc.expr, except_node)
if node.finalbody:
self.writer.write('πF.PopCheckpoint()') # finally_label
self.writer.write('goto Label{}'.format(finally_label))
# Write the finally body.
self.writer.write_label(finally_label)
if node.finalbody:
with self.block.alloc_temp('*πg.Traceback') as tb:
self.writer.write('{}, {} = πF.RestoreExc(nil, nil)'.format(
exc.expr, tb.expr))
self._visit_each(node.finalbody)
self.writer.write_tmpl(textwrap.dedent("""\
if $exc != nil {
\tπE = πF.Raise($exc.ToObject(), nil, $tb.ToObject())
\tcontinue
}
if πR != nil {
\tcontinue
}"""), exc=exc.expr, tb=tb.expr)
def visit_While(self, node):
self._write_py_context(node.lineno)
def testfunc(testvar):
with self.visit_expr(node.test) as cond:
self.writer.write_checked_call2(
testvar, 'πg.IsTrue(πF, {})', cond.expr)
self._visit_loop(testfunc, node)
def visit_With(self, node):
assert len(node.items) == 1, 'multiple items in a with not yet supported'
item = node.items[0]
self._write_py_context(node.loc.line())
# mgr := EXPR
with self.visit_expr(item.context_expr) as mgr,\
self.block.alloc_temp() as exit_func,\
self.block.alloc_temp() as value:
# The code here has a subtle twist: It gets the exit function attribute
# from the class, not from the object. This matches the pseudo code from
# PEP 343 exactly, and is very close to what CPython actually does. (The
# CPython implementation actually uses a special lookup which is performed
# on the object, but skips the instance dictionary: see ceval.c and
# lookup_maybe in typeobject.c.)
# exit := type(mgr).__exit__
self.writer.write_checked_call2(
exit_func, 'πg.GetAttr(πF, {}.Type().ToObject(), {}, nil)',
mgr.expr, self.block.root.intern('__exit__'))
# value := type(mgr).__enter__(mgr)
self.writer.write_checked_call2(
value, 'πg.GetAttr(πF, {}.Type().ToObject(), {}, nil)',
mgr.expr, self.block.root.intern('__enter__'))
self.writer.write_checked_call2(
value, '{}.Call(πF, πg.Args{{{}}}, nil)',
value.expr, mgr.expr)
finally_label = self.block.genlabel(is_checkpoint=True)
self.writer.write('πF.PushCheckpoint({})'.format(finally_label))
if item.optional_vars:
self._tie_target(item.optional_vars, value.expr)
self._visit_each(node.body)
self.writer.write('πF.PopCheckpoint()')
self.writer.write_label(finally_label)
with self.block.alloc_temp() as swallow_exc,\
self.block.alloc_temp('bool') as swallow_exc_bool,\
self.block.alloc_temp('*πg.BaseException') as exc,\
self.block.alloc_temp('*πg.Traceback') as tb,\
self.block.alloc_temp('*πg.Type') as t:
# temp := exit(mgr, *sys.exec_info())
tmpl = """\
$exc, $tb = nil, nil
if πE != nil {
\t$exc, $tb = πF.ExcInfo()
}
if $exc != nil {
\t$t = $exc.Type()
\tif $swallow_exc, πE = $exit_func.Call(πF, πg.Args{$mgr, $t.ToObject(), $exc.ToObject(), $tb.ToObject()}, nil); πE != nil {
\t\tcontinue
\t}
} else {
\tif $swallow_exc, πE = $exit_func.Call(πF, πg.Args{$mgr, πg.None, πg.None, πg.None}, nil); πE != nil {
\t\tcontinue
\t}
}
"""
self.writer.write_tmpl(
textwrap.dedent(tmpl), exc=exc.expr, tb=tb.expr, t=t.name,
mgr=mgr.expr, exit_func=exit_func.expr,
swallow_exc=swallow_exc.name)
# if Exc != nil && swallow_exc != true {
# Raise(nil, nil)
# }
self.writer.write_checked_call2(
swallow_exc_bool, 'πg.IsTrue(πF, {})', swallow_exc.expr)
self.writer.write_tmpl(textwrap.dedent("""\
if $exc != nil && $swallow_exc != true {
\tπE = πF.Raise(nil, nil, nil)
\tcontinue
}
if πR != nil {
\tcontinue
}"""), exc=exc.expr, swallow_exc=swallow_exc_bool.expr)
def visit_function_inline(self, node):
"""Returns an GeneratedExpr for a function with the given body."""
# First pass collects the names of locals used in this function. Do this in
# a separate pass so that we know whether to resolve a name as a local or a
# global during the second pass.
func_visitor = block.FunctionBlockVisitor(node)
for child in node.body:
func_visitor.visit(child)
func_block = block.FunctionBlock(self.block, node.name, func_visitor.vars,
func_visitor.is_generator)
visitor = StatementVisitor(func_block, self.future_node)
# Indent so that the function body is aligned with the goto labels.
with visitor.writer.indent_block():
visitor._visit_each(node.body) # pylint: disable=protected-access
result = self.block.alloc_temp()
with self.block.alloc_temp('[]πg.Param') as func_args:
args = node.args
argc = len(args.args)
self.writer.write('{} = make([]πg.Param, {})'.format(
func_args.expr, argc))
# The list of defaults only contains args for which a default value is
# specified so pad it with None to make it the same length as args.
defaults = [None] * (argc - len(args.defaults)) + args.defaults
for i, (a, d) in enumerate(zip(args.args, defaults)):
with self.visit_expr(d) if d else expr.nil_expr as default:
tmpl = '$args[$i] = πg.Param{Name: $name, Def: $default}'
self.writer.write_tmpl(tmpl, args=func_args.expr, i=i,
name=util.go_str(a.arg), default=default.expr)
flags = []
if args.vararg:
flags.append('πg.CodeFlagVarArg')
if args.kwarg:
flags.append('πg.CodeFlagKWArg')
# The function object gets written to a temporary writer because we need
# it as an expression that we subsequently bind to some variable.
self.writer.write_tmpl(
'$result = πg.NewFunction(πg.NewCode($name, $filename, $args, '
'$flags, func(πF *πg.Frame, πArgs []*πg.Object) '
'(*πg.Object, *πg.BaseException) {',
result=result.name, name=util.go_str(node.name),
filename=util.go_str(self.block.root.filename), args=func_args.expr,
flags=' | '.join(flags) if flags else 0)
with self.writer.indent_block():
for var in func_block.vars.values():
if var.type != block.Var.TYPE_GLOBAL:
fmt = 'var {0} *πg.Object = {1}; _ = {0}'
self.writer.write(fmt.format(
util.adjust_local_name(var.name), var.init_expr))
self.writer.write_temp_decls(func_block)
self.writer.write('var πR *πg.Object; _ = πR')
self.writer.write('var πE *πg.BaseException; _ = πE')
if func_block.is_generator:
self.writer.write(
'return πg.NewGenerator(πF, func(πSent *πg.Object) '
'(*πg.Object, *πg.BaseException) {')
with self.writer.indent_block():
self.writer.write_block(func_block, visitor.writer.getvalue())
self.writer.write('return nil, πE')
self.writer.write('}).ToObject(), nil')
else:
self.writer.write_block(func_block, visitor.writer.getvalue())
self.writer.write(textwrap.dedent("""\
if πE != nil {
\tπR = nil
} else if πR == nil {
\tπR = πg.None
}
return πR, πE"""))
self.writer.write('}), πF.Globals()).ToObject()')
return result
_AUG_ASSIGN_TEMPLATES = {
ast.Add: 'πg.IAdd(πF, {lhs}, {rhs})',
ast.BitAnd: 'πg.IAnd(πF, {lhs}, {rhs})',
ast.Div: 'πg.IDiv(πF, {lhs}, {rhs})',
ast.FloorDiv: 'πg.IFloorDiv(πF, {lhs}, {rhs})',
ast.LShift: 'πg.ILShift(πF, {lhs}, {rhs})',
ast.Mod: 'πg.IMod(πF, {lhs}, {rhs})',
ast.Mult: 'πg.IMul(πF, {lhs}, {rhs})',
ast.BitOr: 'πg.IOr(πF, {lhs}, {rhs})',
ast.Pow: 'πg.IPow(πF, {lhs}, {rhs})',
ast.RShift: 'πg.IRShift(πF, {lhs}, {rhs})',
ast.Sub: 'πg.ISub(πF, {lhs}, {rhs})',
ast.BitXor: 'πg.IXor(πF, {lhs}, {rhs})',
}
def _assign_target(self, target, value):
if isinstance(target, ast.Name):
self.block.bind_var(self.writer, target.id, value)
elif isinstance(target, ast.Attribute):
with self.visit_expr(target.value) as obj:
self.writer.write_checked_call1(
'πg.SetAttr(πF, {}, {}, {})', obj.expr,
self.block.root.intern(target.attr), value)
elif isinstance(target, ast.Subscript):
with self.visit_expr(target.value) as mapping,\
self.visit_expr(target.slice) as index:
self.writer.write_checked_call1('πg.SetItem(πF, {}, {}, {})',
mapping.expr, index.expr, value)
else:
msg = 'assignment target not yet implemented: ' + type(target).__name__
raise util.ParseError(target, msg)
def _build_assign_target(self, target, assigns):
if isinstance(target, (ast.Tuple, ast.List)):
children = []
for elt in target.elts:
children.append(self._build_assign_target(elt, assigns))
tmpl = 'πg.TieTarget{Children: []πg.TieTarget{$children}}'
return string.Template(tmpl).substitute(children=', '.join(children))
temp = self.block.alloc_temp()
assigns.append((target, temp))
tmpl = 'πg.TieTarget{Target: &$temp}'
return string.Template(tmpl).substitute(temp=temp.name)
def _import_and_bind(self, imp):
"""Generates code that imports a module and binds it to a variable.
Args:
imp: Import object representing an import of the form "import x.y.z" or
"from x.y import z". Expects only a single binding.
"""
# Acquire handles to the Code objects in each Go package and call
# ImportModule to initialize all modules.
with self.block.alloc_temp() as mod, \
self.block.alloc_temp('[]*πg.Object') as mod_slice:
self.writer.write_checked_call2(
mod_slice, 'πg.ImportModule(πF, {})', util.go_str(imp.name))
# Bind the imported modules or members to variables in the current scope.
for binding in imp.bindings:
if binding.bind_type == imputil.Import.MODULE:
self.writer.write('{} = {}[{}]'.format(
mod.name, mod_slice.expr, binding.value))
self.block.bind_var(self.writer, binding.alias, mod.expr)
else:
self.writer.write('{} = {}[{}]'.format(
mod.name, mod_slice.expr, imp.name.count('.')))
# Binding a member of the imported module.
with self.block.alloc_temp() as member:
self.writer.write_checked_call2(
member, 'πg.GetAttr(πF, {}, {}, nil)',
mod.expr, self.block.root.intern(binding.value))
self.block.bind_var(self.writer, binding.alias, member.expr)
def _tie_target(self, target, value):
if isinstance(target, ast.Name):
self._assign_target(target, value)
return
assigns = []
self.writer.write_checked_call1(
'πg.Tie(πF, {}, {})',
self._build_assign_target(target, assigns), value)
for t, temp in assigns:
self._assign_target(t, temp.expr)
self.block.free_temp(temp)
def _visit_each(self, nodes):
for node in nodes:
self.visit(node)
def _visit_loop(self, testfunc, node):
start_label = self.block.genlabel(is_checkpoint=True)
else_label = self.block.genlabel(is_checkpoint=True)
end_label = self.block.genlabel()
with self.block.alloc_temp('bool') as breakvar:
self.block.push_loop(breakvar)
self.writer.write('πF.PushCheckpoint({})'.format(else_label))
self.writer.write('{} = false'.format(breakvar.name))
self.writer.write_label(start_label)
self.writer.write_tmpl(textwrap.dedent("""\
if πE != nil || πR != nil {
\tcontinue
}
if $breakvar {
\tπF.PopCheckpoint()
\tgoto Label$end_label
}"""), breakvar=breakvar.expr, end_label=end_label)
with self.block.alloc_temp('bool') as testvar:
testfunc(testvar)
self.writer.write_tmpl(textwrap.dedent("""\
if πE != nil || !$testvar {
\tcontinue
}
πF.PushCheckpoint($start_label)\
"""), testvar=testvar.name, start_label=start_label)
self._visit_each(node.body)
self.writer.write('continue')
# End the loop so that break applies to an outer loop if present.
self.block.pop_loop()
self.writer.write_label(else_label)
self.writer.write(textwrap.dedent("""\
if πE != nil || πR != nil {
\tcontinue
}"""))
if node.orelse:
self._visit_each(node.orelse)
self.writer.write_label(end_label)
def _write_except_block(self, label, exc, except_node):
self._write_py_context(except_node.lineno)
self.writer.write_label(label)
if except_node.name:
self.block.bind_var(self.writer, except_node.name.id,
'{}.ToObject()'.format(exc))
self._visit_each(except_node.body)
self.writer.write('πF.RestoreExc(nil, nil)')
def _write_except_dispatcher(self, exc, tb, handlers):
"""Outputs a Go code that jumps to the appropriate except handler.
Args:
exc: Go variable holding the current exception.
tb: Go variable holding the current exception's traceback.
handlers: A list of ast.ExceptHandler nodes.
Returns:
A list of Go labels indexes corresponding to the exception handlers.
Raises:
ParseError: Except handlers are in an invalid order.
"""
handler_labels = []
for i, except_node in enumerate(handlers):
handler_labels.append(self.block.genlabel())
if except_node.type:
with self.visit_expr(except_node.type) as type_,\
self.block.alloc_temp('bool') as is_inst:
self.writer.write_checked_call2(
is_inst, 'πg.IsInstance(πF, {}.ToObject(), {})', exc, type_.expr)
self.writer.write_tmpl(textwrap.dedent("""\
if $is_inst {
\tgoto Label$label
}"""), is_inst=is_inst.expr, label=handler_labels[-1])
else:
# This is a bare except. It should be the last handler.
if i != len(handlers) - 1:
msg = "default 'except:' must be last"
raise util.ParseError(except_node, msg)
self.writer.write('goto Label{}'.format(handler_labels[-1]))
if handlers[-1].type:
# There's no bare except, so the fallback is to re-raise.
self.writer.write(
'πE = πF.Raise({}.ToObject(), nil, {}.ToObject())'.format(exc, tb))
self.writer.write('continue')
return handler_labels
def _write_py_context(self, lineno):
if lineno:
line = self.block.root.buffer.source_line(lineno).strip()
self.writer.write('// line {}: {}'.format(lineno, line))
self.writer.write('πF.SetLineno({})'.format(lineno))
================================================
FILE: compiler/stmt_test.py
================================================
# coding=utf-8
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for StatementVisitor."""
from __future__ import unicode_literals
import re
import subprocess
import textwrap
import unittest
from grumpy.compiler import block
from grumpy.compiler import imputil
from grumpy.compiler import shard_test
from grumpy.compiler import stmt
from grumpy.compiler import util
from grumpy import pythonparser
from grumpy.pythonparser import ast
class StatementVisitorTest(unittest.TestCase):
def testAssertNoMsg(self):
self.assertEqual((0, 'AssertionError()\n'), _GrumpRun(textwrap.dedent("""\
try:
assert False
except AssertionError as e:
print repr(e)""")))
def testAssertMsg(self):
want = (0, "AssertionError('foo',)\n")
self.assertEqual(want, _GrumpRun(textwrap.dedent("""\
try:
assert False, 'foo'
except AssertionError as e:
print repr(e)""")))
def testBareAssert(self):
# Assertion errors at the top level of a block should raise:
# https://github.com/google/grumpy/issues/18
want = (0, 'ok\n')
self.assertEqual(want, _GrumpRun(textwrap.dedent("""\
def foo():
assert False
try:
foo()
except AssertionError:
print 'ok'
else:
print 'bad'""")))
def testAssignAttribute(self):
self.assertEqual((0, '123\n'), _GrumpRun(textwrap.dedent("""\
e = Exception()
e.foo = 123
print e.foo""")))
def testAssignName(self):
self.assertEqual((0, 'bar\n'), _GrumpRun(textwrap.dedent("""\
foo = 'bar'
print foo""")))
def testAssignMultiple(self):
self.assertEqual((0, 'baz baz\n'), _GrumpRun(textwrap.dedent("""\
foo = bar = 'baz'
print foo, bar""")))
def testAssignSubscript(self):
self.assertEqual((0, "{'bar': None}\n"), _GrumpRun(textwrap.dedent("""\
foo = {}
foo['bar'] = None
print foo""")))
def testAssignTuple(self):
self.assertEqual((0, 'a b\n'), _GrumpRun(textwrap.dedent("""\
baz = ('a', 'b')
foo, bar = baz
print foo, bar""")))
def testAugAssign(self):
self.assertEqual((0, '42\n'), _GrumpRun(textwrap.dedent("""\
foo = 41
foo += 1
print foo""")))
def testAugAssignBitAnd(self):
self.assertEqual((0, '3\n'), _GrumpRun(textwrap.dedent("""\
foo = 7
foo &= 3
print foo""")))
def testAugAssignPow(self):
self.assertEqual((0, '64\n'), _GrumpRun(textwrap.dedent("""\
foo = 8
foo **= 2
print foo""")))
def testClassDef(self):
self.assertEqual((0, "<type 'type'>\n"), _GrumpRun(textwrap.dedent("""\
class Foo(object):
pass
print type(Foo)""")))
def testClassDefWithVar(self):
self.assertEqual((0, 'abc\n'), _GrumpRun(textwrap.dedent("""\
class Foo(object):
bar = 'abc'
print Foo.bar""")))
def testDeleteAttribute(self):
self.assertEqual((0, 'False\n'), _GrumpRun(textwrap.dedent("""\
class Foo(object):
bar = 42
del Foo.bar
print hasattr(Foo, 'bar')""")))
def testDeleteClassLocal(self):
self.assertEqual((0, 'False\n'), _GrumpRun(textwrap.dedent("""\
class Foo(object):
bar = 'baz'
del bar
print hasattr(Foo, 'bar')""")))
def testDeleteGlobal(self):
self.assertEqual((0, 'False\n'), _GrumpRun(textwrap.dedent("""\
foo = 42
del foo
print 'foo' in globals()""")))
def testDeleteLocal(self):
self.assertEqual((0, 'ok\n'), _GrumpRun(textwrap.dedent("""\
def foo():
bar = 123
del bar
try:
print bar
raise AssertionError
except UnboundLocalError:
print 'ok'
foo()""")))
def testDeleteNonexistentLocal(self):
self.assertRaisesRegexp(
util.ParseError, 'cannot delete nonexistent local',
_ParseAndVisit, 'def foo():\n del bar')
def testDeleteSubscript(self):
self.assertEqual((0, '{}\n'), _GrumpRun(textwrap.dedent("""\
foo = {'bar': 'baz'}
del foo['bar']
print foo""")))
def testExprCall(self):
self.assertEqual((0, 'bar\n'), _GrumpRun(textwrap.dedent("""\
def foo():
print 'bar'
foo()""")))
def testExprNameGlobal(self):
self.assertEqual((0, ''), _GrumpRun(textwrap.dedent("""\
foo = 42
foo""")))
def testExprNameLocal(self):
self.assertEqual((0, ''), _GrumpRun(textwrap.dedent("""\
foo = 42
def bar():
foo
bar()""")))
def testFor(self):
self.assertEqual((0, '1\n2\n3\n'), _GrumpRun(textwrap.dedent("""\
for i in (1, 2, 3):
print i""")))
def testForBreak(self):
self.assertEqual((0, '1\n'), _GrumpRun(textwrap.dedent("""\
for i in (1, 2, 3):
print i
break""")))
def testForContinue(self):
self.assertEqual((0, '1\n2\n3\n'), _GrumpRun(textwrap.dedent("""\
for i in (1, 2, 3):
print i
continue
raise AssertionError""")))
def testForElse(self):
self.assertEqual((0, 'foo\nbar\n'), _GrumpRun(textwrap.dedent("""\
for i in (1,):
print 'foo'
else:
print 'bar'""")))
def testForElseBreakNotNested(self):
self.assertRaisesRegexp(
util.ParseError, "'continue' not in loop",
_ParseAndVisit, 'for i in (1,):\n pass\nelse:\n continue')
def testForElseContinueNotNested(self):
self.assertRaisesRegexp(
util.ParseError, "'continue' not in loop",
_ParseAndVisit, 'for i in (1,):\n pass\nelse:\n continue')
def testFunctionDecorator(self):
self.assertEqual((0, '<b>foo</b>\n'), _GrumpRun(textwrap.dedent("""\
def bold(fn):
return lambda: '<b>' + fn() + '</b>'
@bold
def foo():
return 'foo'
print foo()""")))
def testFunctionDecoratorWithArg(self):
self.assertEqual((0, '<b id=red>foo</b>\n'), _GrumpRun(textwrap.dedent("""\
def tag(name):
def bold(fn):
return lambda: '<b id=' + name + '>' + fn() + '</b>'
return bold
@tag('red')
def foo():
return 'foo'
print foo()""")))
def testFunctionDef(self):
self.assertEqual((0, 'bar baz\n'), _GrumpRun(textwrap.dedent("""\
def foo(a, b):
print a, b
foo('bar', 'baz')""")))
def testFunctionDefGenerator(self):
self.assertEqual((0, "['foo', 'bar']\n"), _GrumpRun(textwrap.dedent("""\
def gen():
yield 'foo'
yield 'bar'
print list(gen())""")))
def testFunctionDefGeneratorReturnValue(self):
self.assertRaisesRegexp(
util.ParseError, 'returning a value in a generator function',
_ParseAndVisit, 'def foo():\n yield 1\n return 2')
def testFunctionDefLocal(self):
self.assertEqual((0, 'baz\n'), _GrumpRun(textwrap.dedent("""\
def foo():
def bar():
print 'baz'
bar()
foo()""")))
def testIf(self):
self.assertEqual((0, 'foo\n'), _GrumpRun(textwrap.dedent("""\
if 123:
print 'foo'
if '':
print 'bar'""")))
def testIfElif(self):
self.assertEqual((0, 'foo\nbar\n'), _GrumpRun(textwrap.dedent("""\
if True:
print 'foo'
elif False:
print 'bar'
if False:
print 'foo'
elif True:
print 'bar'""")))
def testIfElse(self):
self.assertEqual((0, 'foo\nbar\n'), _GrumpRun(textwrap.dedent("""\
if True:
print 'foo'
else:
print 'bar'
if False:
print 'foo'
else:
print 'bar'""")))
def testImport(self):
self.assertEqual((0, "<type 'dict'>\n"), _GrumpRun(textwrap.dedent("""\
import sys
print type(sys.modules)""")))
def testImportFutureLateRaises(self):
regexp = 'from __future__ imports must occur at the beginning of the file'
self.assertRaisesRegexp(util.ImportError, regexp, _ParseAndVisit,
'foo = bar\nfrom __future__ import print_function')
def testFutureUnicodeLiterals(self):
want = "u'foo'\n"
self.assertEqual((0, want), _GrumpRun(textwrap.dedent("""\
from __future__ import unicode_literals
print repr('foo')""")))
def testImportMember(self):
self.assertEqual((0, "<type 'dict'>\n"), _GrumpRun(textwrap.dedent("""\
from sys import modules
print type(modules)""")))
def testImportConflictingPackage(self):
self.assertEqual((0, ''), _GrumpRun(textwrap.dedent("""\
import time
from "__go__/time" import Now""")))
def testImportNative(self):
self.assertEqual((0, '1 1000000000\n'), _GrumpRun(textwrap.dedent("""\
from "__go__/time" import Nanosecond, Second
print Nanosecond, Second""")))
def testImportGrumpy(self):
self.assertEqual((0, ''), _GrumpRun(textwrap.dedent("""\
from "__go__/grumpy" import Assert
Assert(__frame__(), True, 'bad')""")))
def testImportNativeType(self):
self.assertEqual((0, "<type 'Duration'>\n"), _GrumpRun(textwrap.dedent("""\
from "__go__/time" import Duration
print Duration""")))
def testImportWildcardMemberRaises(self):
regexp = 'wildcard member import is not implemented'
self.assertRaisesRegexp(util.ImportError, regexp, _ParseAndVisit,
'from foo import *')
self.assertRaisesRegexp(util.ImportError, regexp, _ParseAndVisit,
'from "__go__/foo" import *')
def testPrintStatement(self):
self.assertEqual((0, 'abc 123\nfoo bar\n'), _GrumpRun(textwrap.dedent("""\
print 'abc',
print '123'
print 'foo', 'bar'""")))
def testPrintFunction(self):
want = "abc\n123\nabc 123\nabcx123\nabc 123 "
self.assertEqual((0, want), _GrumpRun(textwrap.dedent("""\
"module docstring is ok to proceed __future__"
from __future__ import print_function
print('abc')
print(123)
print('abc', 123)
print('abc', 123, sep='x')
print('abc', 123, end=' ')""")))
def testRaiseExitStatus(self):
self.assertEqual(1, _GrumpRun('raise Exception')[0])
def testRaiseInstance(self):
self.assertEqual((0, 'foo\n'), _GrumpRun(textwrap.dedent("""\
try:
raise RuntimeError('foo')
print 'bad'
except RuntimeError as e:
print e""")))
def testRaiseTypeAndArg(self):
self.assertEqual((0, 'foo\n'), _GrumpRun(textwrap.dedent("""\
try:
raise KeyError('foo')
print 'bad'
except KeyError as e:
print e""")))
def testRaiseAgain(self):
self.assertEqual((0, 'foo\n'), _GrumpRun(textwrap.dedent("""\
try:
try:
raise AssertionError('foo')
except AssertionError:
raise
except Exception as e:
print e""")))
def testRaiseTraceback(self):
self.assertEqual((0, ''), _GrumpRun(textwrap.dedent("""\
import sys
try:
try:
raise Exception
except:
e, _, tb = sys.exc_info()
raise e, None, tb
except:
e2, _, tb2 = sys.exc_info()
assert e is e2
assert tb is tb2""")))
def testReturn(self):
self.assertEqual((0, 'bar\n'), _GrumpRun(textwrap.dedent("""\
def foo():
return 'bar'
print foo()""")))
def testTryBareExcept(self):
self.assertEqual((0, ''), _GrumpRun(textwrap.dedent("""\
try:
raise AssertionError
except:
pass""")))
def testTryElse(self):
self.assertEqual((0, 'foo baz\n'), _GrumpRun(textwrap.dedent("""\
try:
print 'foo',
except:
print 'bar'
else:
print 'baz'""")))
def testTryMultipleExcept(self):
self.assertEqual((0, 'bar\n'), _GrumpRun(textwrap.dedent("""\
try:
raise AssertionError
except RuntimeError:
print 'foo'
except AssertionError:
print 'bar'
except:
print 'baz'""")))
def testTryFinally(self):
result = _GrumpRun(textwrap.dedent("""\
try:
print 'foo',
finally:
print 'bar'
try:
print 'foo',
raise Exception
finally:
print 'bar'"""))
self.assertEqual(1, result[0])
self.assertIn('foo bar\nfoo bar\n', result[1])
self.assertIn('Exception\n', result[1])
def testWhile(self):
self.assertEqual((0, '2\n1\n'), _GrumpRun(textwrap.dedent("""\
i = 2
while i:
print i
i -= 1""")))
def testWhileElse(self):
self.assertEqual((0, 'bar\n'), _GrumpRun(textwrap.dedent("""\
while False:
print 'foo'
else:
print 'bar'""")))
def testWith(self):
self.assertEqual((0, 'enter\n1\nexit\nenter\n2\nexit\n3\n'),
_GrumpRun(textwrap.dedent("""\
class ContextManager(object):
def __enter__(self):
print "enter"
def __exit__(self, exc_type, value, traceback):
print "exit"
a = ContextManager()
with a:
print 1
try:
with a:
print 2
raise RuntimeError
except RuntimeError:
print 3
""")))
def testWithAs(self):
self.assertEqual((0, '1 2 3\n'),
_GrumpRun(textwrap.dedent("""\
class ContextManager(object):
def __enter__(self):
return (1, (2, 3))
def __exit__(self, *args):
pass
with ContextManager() as [x, (y, z)]:
print x, y, z
""")))
def testWriteExceptDispatcherBareExcept(self):
visitor = stmt.StatementVisitor(_MakeModuleBlock())
handlers = [ast.ExceptHandler(type=ast.Name(id='foo')),
ast.ExceptHandler(type=None)]
self.assertEqual(visitor._write_except_dispatcher( # pylint: disable=protected-access
'exc', 'tb', handlers), [1, 2])
expected = re.compile(r'ResolveGlobal\(.*foo.*\bIsInstance\(.*'
r'goto Label1.*goto Label2', re.DOTALL)
self.assertRegexpMatches(visitor.writer.getvalue(), expected)
def testWriteExceptDispatcherBareExceptionNotLast(self):
visitor = stmt.StatementVisitor(_MakeModuleBlock())
handlers = [ast.ExceptHandler(type=None),
ast.ExceptHandler(type=ast.Name(id='foo'))]
self.assertRaisesRegexp(util.ParseError, r"default 'except:' must be last",
visitor._write_except_dispatcher, # pylint: disable=protected-access
'exc', 'tb', handlers)
def testWriteExceptDispatcherMultipleExcept(self):
visitor = stmt.StatementVisitor(_MakeModuleBlock())
handlers = [ast.ExceptHandler(type=ast.Name(id='foo')),
ast.ExceptHandler(type=ast.Name(id='bar'))]
self.assertEqual(visitor._write_except_dispatcher( # pylint: disable=protected-access
'exc', 'tb', handlers), [1, 2])
expected = re.compile(
r'ResolveGlobal\(.*foo.*\bif .*\bIsInstance\(.*\{.*goto Label1.*'
r'ResolveGlobal\(.*bar.*\bif .*\bIsInstance\(.*\{.*goto Label2.*'
r'\bRaise\(exc\.ToObject\(\), nil, tb\.ToObject\(\)\)', re.DOTALL)
self.assertRegexpMatches(visitor.writer.getvalue(), expected)
def _MakeModuleBlock():
return block.ModuleBlock(None, '__main__', '<test>', '',
imputil.FutureFeatures())
def _ParseAndVisit(source):
mod = pythonparser.parse(source)
_, future_features = imputil.parse_future_features(mod)
importer = imputil.Importer(None, 'foo', 'foo.py', False)
b = block.ModuleBlock(importer, '__main__', '<test>',
source, future_features)
visitor = stmt.StatementVisitor(b)
visitor.visit(mod)
return visitor
def _GrumpRun(cmd):
p = subprocess.Popen(['grumprun'], stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
out, _ = p.communicate(cmd)
return p.returncode, out
if __name__ == '__main__':
shard_test.main()
================================================
FILE: compiler/util.py
================================================
# coding=utf-8
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utilities for generating Go code."""
from __future__ import unicode_literals
import codecs
import contextlib
import cStringIO
import string
import StringIO
import textwrap
_SIMPLE_CHARS = set(string.digits + string.letters + string.punctuation + " ")
_ESCAPES = {'\t': r'\t', '\r': r'\r', '\n': r'\n', '"': r'\"', '\\': r'\\'}
# This is the max length of a direct allocation tuple supported by the runtime.
# This should match the number of specializations found in tuple.go.
MAX_DIRECT_TUPLE = 6
class CompileError(Exception):
def __init__(self, node, msg):
if hasattr(node, 'lineno'):
msg = 'line {}: {}'.format(node.lineno, msg)
super(CompileError, self).__init__(msg)
class ParseError(CompileError):
pass
class ImportError(CompileError): # pylint: disable=redefined-builtin
pass
class LateFutureError(ImportError):
def __init__(self, node):
msg = 'from __future__ imports must occur at the beginning of the file'
super(LateFutureError, self).__init__(node, msg)
class Writer(object):
"""Utility class for writing blocks of Go code to a file-like object."""
def __init__(self, out=None):
self.out = codecs.getwriter('utf8')(out or cStringIO.StringIO())
self.indent_level = 0
def getvalue(self):
return self.out.getvalue().decode('utf8')
@contextlib.contextmanager
def indent_block(self, n=1):
"""A context manager that indents by n on entry and dedents on exit."""
self.indent(n)
yield
self.dedent(n)
def write(self, output):
for line in output.split('\n'):
if line:
self.out.write(''.join(('\t' * self.indent_level, line, '\n')))
def write_block(self, block_, body):
"""Outputs the boilerplate necessary for code blocks like functions.
Args:
block_: The Block object representing the code block.
body: String containing Go code making up the body of the code block.
"""
self.write('for ; πF.State() >= 0; πF.PopCheckpoint() {')
with self.indent_block():
self.write('switch πF.State() {')
self.write('case 0:')
for checkpoint in block_.checkpoints:
self.write_tmpl('case $state: goto Label$state', state=checkpoint)
self.write('default: panic("unexpected function state")')
self.write('}')
# Assume that body is aligned with goto labels.
with self.indent_block(-1):
self.write(body)
self.write('}')
def write_label(self, label):
with self.indent_block(-1):
self.write('Label{}:'.format(label))
def write_py_context(self, lineno, line):
self.write_tmpl('// line $lineno: $line', lineno=lineno, line=line)
def write_tmpl(self, tmpl, **kwargs):
self.write(string.Template(tmpl).substitute(kwargs))
def write_checked_call2(self, result, call, *args, **kwargs):
return self.write_tmpl(textwrap.dedent("""\
if $result, πE = $call; πE != nil {
\tcontinue
}"""), result=result.name, call=call.format(*args, **kwargs))
def write_checked_call1(self, call, *args, **kwargs):
return self.write_tmpl(textwrap.dedent("""\
if πE = $call; πE != nil {
\tcontinue
}"""), call=call.format(*args, **kwargs))
def write_temp_decls(self, block_):
all_temps = block_.free_temps | block_.used_temps
for temp in sorted(all_temps, key=lambda t: t.name):
self.write('var {0} {1}\n_ = {0}'.format(temp.name, temp.type_))
def indent(self, n=1):
self.indent_level += n
def dedent(self, n=1):
self.indent_level -= n
def go_str(value):
"""Returns value as a valid Go string literal."""
io = StringIO.StringIO()
io.write('"')
for c in value:
if c in _ESCAPES:
io.write(_ESCAPES[c])
elif c in _SIMPLE_CHARS:
io.write(c)
else:
io.write(r'\x{:02x}'.format(ord(c)))
io.write('"')
return io.getvalue()
def adjust_local_name(name):
"""Returns a Go identifier for the given Python variable name."""
return 'µ' + name
================================================
FILE: compiler/util_test.py
================================================
# coding=utf-8
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests Writer and other utils."""
from __future__ import unicode_literals
import unittest
from grumpy.compiler import block
from grumpy.compiler import imputil
from grumpy.compiler import util
class WriterTest(unittest.TestCase):
def testIndentBlock(self):
writer = util.Writer()
writer.write('foo')
with writer.indent_block(n=2):
writer.write('bar')
writer.write('baz')
self.assertEqual(writer.getvalue(), 'foo\n\t\tbar\nbaz\n')
def testWriteBlock(self):
writer = util.Writer()
mod_block = block.ModuleBlock(None, '__main__', '<test>', '',
imputil.FutureFeatures())
writer.write_block(mod_block, 'BODY')
output = writer.getvalue()
dispatch = 'switch πF.State() {\n\tcase 0:\n\tdefault: panic'
self.assertIn(dispatch, output)
def testWriteMultiline(self):
writer = util.Writer()
writer.indent(2)
writer.write('foo\nbar\nbaz\n')
self.assertEqual(writer.getvalue(), '\t\tfoo\n\t\tbar\n\t\tbaz\n')
def testWritePyContext(self):
writer = util.Writer()
writer.write_py_context(12, 'print "foo"')
self.assertEqual(writer.getvalue(), '// line 12: print "foo"\n')
def testWriteSkipBlankLine(self):
writer = util.Writer()
writer.write('foo\n\nbar')
self.assertEqual(writer.getvalue(), 'foo\nbar\n')
def testWriteTmpl(self):
writer = util.Writer()
writer.write_tmpl('$foo, $bar\n$baz', foo=1, bar=2, baz=3)
self.assertEqual(writer.getvalue(), '1, 2\n3\n')
def testIndent(self):
writer = util.Writer()
writer.indent(2)
writer.write('foo')
self.assertEqual(writer.getvalue(), '\t\tfoo\n')
def testDedent(self):
writer = util.Writer()
writer.indent(4)
writer.dedent(3)
writer.write('foo')
self.assertEqual(writer.getvalue(), '\tfoo\n')
if __name__ == '__main__':
unittest.main()
================================================
FILE: lib/README.md
================================================
This directory contains Grumpy Python standard library code. It is only expected
to run under Grumpy, not CPython.
================================================
FILE: lib/__builtin__.py
================================================
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Built-in Python identifiers."""
# pylint: disable=invalid-name
from '__go__/grumpy' import Builtins
for k, v in Builtins.iteritems():
globals()[k] = v
================================================
FILE: lib/_random.py
================================================
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Generate pseudo random numbers. Should not be used for security purposes."""
from '__go__/math/rand' import Uint32, Seed
from '__go__/math' import Pow
from '__go__/time' import Now
BPF = 53 # Number of bits in a float
RECIP_BPF = Pow(2, -BPF)
# TODO: The random byte generator currently uses math.rand.Uint32 to generate
# 4 bytes at a time. We should use math.rand.Read to generate the correct
# number of bytes needed. This can be changed once there is a way to
# allocate the needed []byte for Read from python and cast it to a list of
# integers once it is filled.
def _gorandom(nbytes):
byte_arr = []
while len(byte_arr) < nbytes:
i = Uint32()
byte_arr.append(i & 0xff)
byte_arr.append(i >> 8 & 0xff)
byte_arr.append(i >> 16 & 0xff)
byte_arr.append(i >> 24 & 0xff)
byte_arr = byte_arr[0:nbytes]
return byte_arr
# This is a slow replacement for int.bit_length.
# We should stop using this if it is implemented.
def _int_bit_length(n):
bits = 0
while n: # 1 bit steps
n = n / 2
bits += 1
return bits
# Replacement for int.from_bytes (big endian)
def _int_from_bytes(bytes):
i = 0
n = len(bytes) - 1
while n >= 0:
i += bytes[n] << (8 * n)
n -= 1
return i
class GrumpyRandom(object):
"""Random generator replacement for Grumpy.
Alternate random number generator using golangs math.rand as a replacement
for the CPython implementation.
"""
def random(self):
"""Get the next random number in the range [0.0, 1.0)."""
return (_int_from_bytes(_gorandom(7)) >> 3) * RECIP_BPF
def getrandbits(self, k):
"""getrandbits(k) -> x. Generates an int with k random bits."""
if k <= 0:
raise ValueError('number of bits must be greater than zero')
if k != int(k):
raise TypeError('number of bits should be an integer')
numbytes = (k + 7) // 8 # bits / 8 and rounded up
x = _int_from_bytes(_gorandom(numbytes))
return x >> (numbytes * 8 - k) # trim excess bits
def seed(self, a=None):
"""Seed the golang.math.rand generator."""
if a is None:
a = Now().UnixNano()
Seed(a)
def _randbelow(self, n):
"""Return a random int in the range [0,n)."""
# TODO
# change once int.bit_length is implemented.
# k = n.bit_length()
k = _int_bit_length(n)
r = self.getrandbits(k)
while r >= n:
r = self.getrandbits(k)
return r
def getstate(self, *args, **kwargs):
raise NotImplementedError('Entropy source does not have state.')
def setstate(self, *args, **kwargs):
raise NotImplementedError('Entropy source does not have state.')
def jumpahead(self, *args, **kwargs):
raise NotImplementedError('Entropy source does not have state.')
================================================
FILE: lib/_syscall.py
================================================
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from '__go__/syscall' import EINTR
def invoke(func, *args):
while True:
result = func(*args)
if isinstance(result, tuple):
err = result[-1]
result = result[:-1]
else:
err = result
result = ()
if err:
if err == EINTR:
continue
raise OSError(err.Error())
return result
================================================
FILE: lib/errno.py
================================================
EINVAL = 22
================================================
FILE: lib/exceptions.py
================================================
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Built-in exception classes."""
from '__go__/grumpy' import ExceptionTypes
g = globals()
for t in ExceptionTypes:
g[t.__name__] = t
================================================
FILE: lib/itertools.py
================================================
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utilities for iterating over containers."""
import _collections
import sys
class chain(object):
def from_iterable(cls, iterables):
for it in iterables:
for element in it:
yield element
from_iterable = classmethod(from_iterable)
def __init__(self, *iterables):
if not iterables:
self.iterables = iter([[]])
else:
self.iterables = iter(iterables)
self.curriter = iter(next(self.iterables))
def __iter__(self):
return self
def next(self):
flag = True
while flag:
try:
ret = next(self.curriter)
flag = False
except StopIteration:
self.curriter = iter(next(self.iterables))
return ret
def compress(data, selectors):
return (d for d,s in izip(data, selectors) if s)
def count(start=0, step=1):
n = start
while True:
yield n
n += step
def cycle(iterable):
saved = []
for element in iterable:
yield element
saved.append(element)
while saved:
for element in saved:
yield element
def dropwhile(predicate, iterable):
iterable = iter(iterable)
for x in iterable:
if not predicate(x):
yield x
break
for x in iterable:
yield x
class groupby(object):
# [k for k, g in groupby('AAAABBBCCDAABBB')] --> A B C D A B
# [list(g) for k, g in groupby('AAAABBBCCD')] --> AAAA BBB CC D
def __init__(self, iterable, key=None):
if key is None:
key = lambda x: x
self.keyfunc = key
self.it = iter(iterable)
self.tgtkey = self.currkey = self.currvalue = object()
def __iter__(self):
return self
def next(self):
while self.currkey == self.tgtkey:
self.currvalue = next(self.it) # Exit on StopIteration
self.currkey = self.keyfunc(self.currvalue)
self.tgtkey = self.currkey
return (self.currkey, self._grouper(self.tgtkey))
def _grouper(self, tgtkey):
while self.currkey == tgtkey:
yield self.currvalue
self.currvalue = next(self.it) # Exit on StopIteration
self.currkey = self.keyfunc(self.currvalue)
def ifilter(predicate, iterable):
if predicate is None:
predicate = bool
for x in iterable:
if predicate(x):
yield x
def ifilterfalse(predicate, iterable):
if predicate is None:
predicate = bool
for x in iterable:
if not predicate(x):
yield x
def imap(function, *iterables):
iterables = map(iter, iterables)
while True:
args = [next(it) for it in iterables]
if function is None:
yield tuple(args)
else:
yield function(*args)
def islice(iterable, *args):
s = slice(*args)
it = iter(xrange(s.start or 0, s.stop or sys.maxint, s.step or 1))
nexti = next(it)
for i, element in enumerate(iterable):
if i == nexti:
yield element
nexti = next(it)
def izip(*iterables):
iterators = map(iter, iterables)
while iterators:
yield tuple(map(next, iterators))
class ZipExhausted(Exception):
pass
def izip_longest(*args, **kwds):
# izip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-
fillvalue = kwds.get('fillvalue')
counter = [len(args) - 1]
def sentinel():
if not counter[0]:
raise ZipExhausted
counter[0] -= 1
yield fillvalue
fillers = repeat(fillvalue)
iterators = [chain(it, sentinel(), fillers) for it in args]
try:
while iterators:
yield tuple(map(next, iterators))
except ZipExhausted:
pass
def product(*args, **kwds):
# product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
# product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
pools = map(tuple, args) * kwds.get('repeat', 1)
result = [[]]
for pool in pools:
result = [x+[y] for x in result for y in pool]
for prod in result:
yield tuple(prod)
def permutations(iterable, r=None):
pool = tuple(iterable)
n = len(pool)
r = n if r is None else r
for indices in product(range(n), repeat=r)
gitextract_ey0d_gsm/
├── .gitignore
├── .pylintrc
├── .travis.yml
├── AUTHORS.md
├── CONTRIBUTING.md
├── LICENSE
├── Makefile
├── README.md
├── __init__.py
├── benchmarks/
│ ├── bm_call_method.py
│ ├── bm_call_simple.py
│ ├── call.py
│ ├── comprehension.py
│ ├── concurrent.py
│ ├── dict.py
│ ├── generator.py
│ ├── list.py
│ ├── loop.py
│ └── tuple.py
├── compiler/
│ ├── __init__.py
│ ├── block.py
│ ├── block_test.py
│ ├── expr.py
│ ├── expr_visitor.py
│ ├── expr_visitor_test.py
│ ├── imputil.py
│ ├── imputil_test.py
│ ├── shard_test.py
│ ├── stmt.py
│ ├── stmt_test.py
│ ├── util.py
│ └── util_test.py
├── lib/
│ ├── README.md
│ ├── __builtin__.py
│ ├── _random.py
│ ├── _syscall.py
│ ├── errno.py
│ ├── exceptions.py
│ ├── itertools.py
│ ├── itertools_test.py
│ ├── math.py
│ ├── math_test.py
│ ├── os/
│ │ ├── __init__.py
│ │ ├── path.py
│ │ └── path_test.py
│ ├── os_test.py
│ ├── random_test.py
│ ├── select_.py
│ ├── stat.py
│ ├── sys.py
│ ├── sys_test.py
│ ├── tempfile.py
│ ├── tempfile_test.py
│ ├── thread.py
│ ├── time.py
│ ├── time_test.py
│ ├── types_test.py
│ ├── weetest.py
│ └── weetest_test.py
├── runtime/
│ ├── baseexception.go
│ ├── baseexception_test.go
│ ├── basestring.go
│ ├── basestring_test.go
│ ├── bool.go
│ ├── bool_test.go
│ ├── builtin_types.go
│ ├── builtin_types_test.go
│ ├── bytearray.go
│ ├── bytearray_test.go
│ ├── code.go
│ ├── code_test.go
│ ├── complex.go
│ ├── complex_test.go
│ ├── core.go
│ ├── core_test.go
│ ├── descriptor.go
│ ├── descriptor_test.go
│ ├── dict.go
│ ├── dict_test.go
│ ├── doc.go
│ ├── exceptions.go
│ ├── file.go
│ ├── file_test.go
│ ├── float.go
│ ├── float_test.go
│ ├── frame.go
│ ├── frame_test.go
│ ├── function.go
│ ├── function_test.go
│ ├── generator.go
│ ├── generator_test.go
│ ├── int.go
│ ├── int_test.go
│ ├── list.go
│ ├── list_test.go
│ ├── long.go
│ ├── long_test.go
│ ├── method.go
│ ├── method_test.go
│ ├── module.go
│ ├── module_test.go
│ ├── native.go
│ ├── native_test.go
│ ├── numeric.go
│ ├── object.go
│ ├── object_test.go
│ ├── param.go
│ ├── param_test.go
│ ├── range.go
│ ├── range_test.go
│ ├── seq.go
│ ├── seq_test.go
│ ├── set.go
│ ├── set_test.go
│ ├── slice.go
│ ├── slice_test.go
│ ├── slots.go
│ ├── slots_test.go
│ ├── str.go
│ ├── str_test.go
│ ├── super.go
│ ├── super_test.go
│ ├── threading.go
│ ├── threading_test.go
│ ├── traceback.go
│ ├── tuple.go
│ ├── tuple_test.go
│ ├── type.go
│ ├── type_test.go
│ ├── unicode.go
│ ├── unicode_test.go
│ ├── weakref.go
│ └── weakref_test.go
├── testing/
│ ├── assert_test.py
│ ├── assign_test.py
│ ├── builtin_test.py
│ ├── class_test.py
│ ├── compare_test.py
│ ├── complex_test.py
│ ├── comprehension_test.py
│ ├── dict_test.py
│ ├── file_test.py
│ ├── float_test.py
│ ├── for_test.py
│ ├── function_test.py
│ ├── generator_test.py
│ ├── getopt_test.py
│ ├── global_test.py
│ ├── if_test.py
│ ├── import_test.py
│ ├── list_test.py
│ ├── native_test.py
│ ├── op_test.py
│ ├── pow_test.py
│ ├── scope_test.py
│ ├── str_test.py
│ ├── struct_test.py
│ ├── try_test.py
│ ├── tuple_test.py
│ ├── while_test.py
│ └── with_test.py
├── third_party/
│ ├── ouroboros/
│ │ ├── AUTHORS
│ │ ├── LICENSE
│ │ ├── READEME.md
│ │ ├── operator.py
│ │ └── test/
│ │ └── test_operator.py
│ ├── pypy/
│ │ ├── LICENSE
│ │ ├── README.md
│ │ ├── _collections.py
│ │ ├── _csv.py
│ │ ├── _functools.py
│ │ ├── _md5.py
│ │ ├── _sha.py
│ │ ├── _sha256.py
│ │ ├── _sha512.py
│ │ ├── _sre.py
│ │ ├── _struct.py
│ │ ├── binascii.py
│ │ └── datetime.py
│ ├── pythonparser/
│ │ ├── LICENSE.txt
│ │ ├── README.md
│ │ ├── __init__.py
│ │ ├── algorithm.py
│ │ ├── ast.py
│ │ ├── diagnostic.py
│ │ ├── lexer.py
│ │ ├── parser.py
│ │ └── source.py
│ └── stdlib/
│ ├── LICENSE
│ ├── Queue.py
│ ├── README.md
│ ├── StringIO.py
│ ├── UserDict.py
│ ├── UserList.py
│ ├── UserString.py
│ ├── _abcoll.py
│ ├── _weakrefset.py
│ ├── abc.py
│ ├── argparse.py
│ ├── base64.py
│ ├── bisect.py
│ ├── collections.py
│ ├── colorsys.py
│ ├── contextlib.py
│ ├── copy.py
│ ├── copy_reg.py
│ ├── csv.py
│ ├── difflib.py
│ ├── dircache.py
│ ├── dummy_thread.py
│ ├── fnmatch.py
│ ├── fpformat.py
│ ├── functools.py
│ ├── genericpath.py
│ ├── getopt.py
│ ├── glob.py
│ ├── heapq.py
│ ├── json/
│ │ ├── __init__.py
│ │ ├── decoder.py
│ │ └── encoder.py
│ ├── json_scanner.py
│ ├── keyword.py
│ ├── linecache.py
│ ├── md5.py
│ ├── mimetools.py
│ ├── mutex.py
│ ├── optparse.py
│ ├── pprint.py
│ ├── quopri.py
│ ├── random.py
│ ├── re.py
│ ├── re_tests.py
│ ├── repr.py
│ ├── rfc822.py
│ ├── sched.py
│ ├── sha.py
│ ├── sre_compile.py
│ ├── sre_constants.py
│ ├── sre_parse.py
│ ├── string.py
│ ├── test/
│ │ ├── __init__.py
│ │ ├── list_tests.py
│ │ ├── lock_tests.py
│ │ ├── mapping_tests.py
│ │ ├── seq_tests.py
│ │ ├── string_tests.py
│ │ ├── test_argparse.py
│ │ ├── test_bisect.py
│ │ ├── test_colorsys.py
│ │ ├── test_datetime.py
│ │ ├── test_dict.py
│ │ ├── test_dircache.py
│ │ ├── test_dummy_thread.py
│ │ ├── test_fpformat.py
│ │ ├── test_genericpath.py
│ │ ├── test_list.py
│ │ ├── test_md5.py
│ │ ├── test_mimetools.py
│ │ ├── test_mutex.py
│ │ ├── test_queue.py
│ │ ├── test_quopri.py
│ │ ├── test_rfc822.py
│ │ ├── test_sched.py
│ │ ├── test_select.py
│ │ ├── test_slice.py
│ │ ├── test_stat.py
│ │ ├── test_string.py
│ │ ├── test_support.py
│ │ ├── test_threading.py
│ │ ├── test_tuple.py
│ │ └── test_uu.py
│ ├── textwrap.py
│ ├── threading.py
│ ├── traceback.py
│ ├── types.py
│ ├── unittest/
│ │ └── __init__.py
│ ├── unittest_case.py
│ ├── unittest_loader.py
│ ├── unittest_result.py
│ ├── unittest_runner.py
│ ├── unittest_signals.py
│ ├── unittest_suite.py
│ ├── unittest_util.py
│ ├── urlparse.py
│ ├── uu.py
│ ├── warnings.py
│ └── weakref.py
└── tools/
├── benchcmp
├── coverparse
├── diffrange
├── genmake
├── grumpc
├── grumprun
├── pkgc.go
└── pydeps
Showing preview only (447K chars total). Download the full file or copy to clipboard to get everything.
SYMBOL INDEX (6017 symbols across 241 files)
FILE: benchmarks/bm_call_method.py
class Foo (line 13) | class Foo(object):
method foo (line 15) | def foo(self, a, b, c, d):
method bar (line 38) | def bar(self, a, b, c):
method baz (line 61) | def baz(self, a, b):
method quux (line 84) | def quux(self, a):
method qux (line 107) | def qux(self):
function BenchmarkCallMethod (line 111) | def BenchmarkCallMethod(b):
FILE: benchmarks/bm_call_simple.py
function foo (line 13) | def foo(a, b, c, d):
function bar (line 37) | def bar(a, b, c):
function baz (line 61) | def baz(a, b):
function quux (line 85) | def quux(a):
function qux (line 109) | def qux():
function BenchmarkCallSimple (line 113) | def BenchmarkCallSimple(b):
FILE: benchmarks/call.py
function BenchmarkCallNoArgs (line 22) | def BenchmarkCallNoArgs(b):
function BenchmarkCallPositionalArgs (line 29) | def BenchmarkCallPositionalArgs(b):
function BenchmarkCallKeywords (line 36) | def BenchmarkCallKeywords(b):
function BenchmarkCallDefaults (line 43) | def BenchmarkCallDefaults(b):
function BenchmarkCallVarArgs (line 50) | def BenchmarkCallVarArgs(b):
function BenchmarkCallKwargs (line 57) | def BenchmarkCallKwargs(b):
FILE: benchmarks/comprehension.py
function BenchmarkGeneratorExpCreate (line 22) | def BenchmarkGeneratorExpCreate(b):
function BenchmarkGeneratorExpIterate (line 28) | def BenchmarkGeneratorExpIterate(b):
function BenchmarkListCompCreate (line 33) | def BenchmarkListCompCreate(b):
function BenchmarkDictCompCreate (line 38) | def BenchmarkDictCompCreate(b):
FILE: benchmarks/concurrent.py
function Arithmetic (line 22) | def Arithmetic(n):
function Fib (line 26) | def Fib(n):
function _MakeParallelBenchmark (line 38) | def _MakeParallelBenchmark(p, work_func, *args):
function _RegisterBenchmarks (line 58) | def _RegisterBenchmarks():
FILE: benchmarks/dict.py
function BenchmarkDictCreate (line 22) | def BenchmarkDictCreate(b):
function BenchmarkDictCreateFunc (line 27) | def BenchmarkDictCreateFunc(b):
function BenchmarkDictGetItem (line 32) | def BenchmarkDictGetItem(b):
function BenchmarkDictStringOnlyGetItem (line 38) | def BenchmarkDictStringOnlyGetItem(b):
function BenchmarkDictSetItem (line 44) | def BenchmarkDictSetItem(b):
function BenchmarkDictStringOnlySetItem (line 50) | def BenchmarkDictStringOnlySetItem(b):
function BenchmarkHashStrCached (line 56) | def BenchmarkHashStrCached(b):
FILE: benchmarks/generator.py
function BenchmarkGeneratorIterate (line 20) | def BenchmarkGeneratorIterate(b):
function BenchmarkGeneratorCreate (line 28) | def BenchmarkGeneratorCreate(b):
FILE: benchmarks/list.py
function BenchmarkListGetItem (line 22) | def BenchmarkListGetItem(b):
function BenchmarkListContains3 (line 28) | def BenchmarkListContains3(b):
function BenchmarkListContains10 (line 34) | def BenchmarkListContains10(b):
FILE: benchmarks/loop.py
function BenchmarkForXRange (line 20) | def BenchmarkForXRange(b):
function BenchmarkWhileCounter (line 25) | def BenchmarkWhileCounter(b):
function BenchmarkWhileXRange (line 31) | def BenchmarkWhileXRange(b):
FILE: benchmarks/tuple.py
function BenchmarkTupleGetItem (line 22) | def BenchmarkTupleGetItem(b):
function BenchmarkTupleContains3 (line 28) | def BenchmarkTupleContains3(b):
function BenchmarkTupleContains10 (line 34) | def BenchmarkTupleContains10(b):
FILE: compiler/block.py
class Package (line 35) | class Package(object):
method __init__ (line 38) | def __init__(self, name, alias=None):
class Loop (line 45) | class Loop(object):
method __init__ (line 48) | def __init__(self, breakvar):
class Block (line 52) | class Block(object):
method __init__ (line 57) | def __init__(self, parent, name):
method bind_var (line 70) | def bind_var(self, writer, name, value):
method del_var (line 85) | def del_var(self, writer, name):
method resolve_name (line 89) | def resolve_name(self, writer, name):
method genlabel (line 102) | def genlabel(self, is_checkpoint=False):
method alloc_temp (line 108) | def alloc_temp(self, type_='*πg.Object'):
method free_temp (line 121) | def free_temp(self, v):
method push_loop (line 126) | def push_loop(self, breakvar):
method pop_loop (line 131) | def pop_loop(self):
method top_loop (line 134) | def top_loop(self):
method _resolve_global (line 137) | def _resolve_global(self, writer, name):
class ModuleBlock (line 144) | class ModuleBlock(Block):
method __init__ (line 147) | def __init__(self, importer, full_package_name,
method bind_var (line 157) | def bind_var(self, writer, name, value):
method del_var (line 162) | def del_var(self, writer, name):
method resolve_name (line 166) | def resolve_name(self, writer, name):
method intern (line 169) | def intern(self, s):
class ClassBlock (line 176) | class ClassBlock(Block):
method __init__ (line 179) | def __init__(self, parent, name, global_vars):
method bind_var (line 183) | def bind_var(self, writer, name, value):
method del_var (line 189) | def del_var(self, writer, name):
method resolve_name (line 195) | def resolve_name(self, writer, name):
class FunctionBlock (line 217) | class FunctionBlock(Block):
method __init__ (line 220) | def __init__(self, parent, name, block_vars, is_generator):
method bind_var (line 226) | def bind_var(self, writer, name, value):
method del_var (line 231) | def del_var(self, writer, name):
method resolve_name (line 244) | def resolve_name(self, writer, name):
class Var (line 260) | class Var(object):
method __init__ (line 267) | def __init__(self, name, var_type, arg_index=None):
class BlockVisitor (line 281) | class BlockVisitor(algorithm.Visitor):
method __init__ (line 286) | def __init__(self):
method visit_Assign (line 289) | def visit_Assign(self, node):
method visit_AugAssign (line 294) | def visit_AugAssign(self, node):
method visit_ClassDef (line 298) | def visit_ClassDef(self, node):
method visit_ExceptHandler (line 301) | def visit_ExceptHandler(self, node):
method visit_For (line 306) | def visit_For(self, node):
method visit_FunctionDef (line 310) | def visit_FunctionDef(self, node):
method visit_Global (line 316) | def visit_Global(self, node):
method visit_Import (line 320) | def visit_Import(self, node):
method visit_ImportFrom (line 324) | def visit_ImportFrom(self, node):
method visit_With (line 328) | def visit_With(self, node):
method _assign_target (line 334) | def _assign_target(self, target):
method _register_global (line 341) | def _register_global(self, node, name):
method _register_local (line 353) | def _register_local(self, name):
class FunctionBlockVisitor (line 358) | class FunctionBlockVisitor(BlockVisitor):
method __init__ (line 363) | def __init__(self, node):
method visit_Yield (line 378) | def visit_Yield(self, unused_node): # pylint: disable=unused-argument
FILE: compiler/block_test.py
class PackageTest (line 29) | class PackageTest(unittest.TestCase):
method testCreate (line 31) | def testCreate(self):
method testCreateGrump (line 36) | def testCreateGrump(self):
class BlockTest (line 42) | class BlockTest(unittest.TestCase):
method testLoop (line 44) | def testLoop(self):
method testResolveName (line 53) | def testResolveName(self):
method _ResolveName (line 89) | def _ResolveName(self, b, name):
class BlockVisitorTest (line 95) | class BlockVisitorTest(unittest.TestCase):
method testAssignSingle (line 97) | def testAssignSingle(self):
method testAssignMultiple (line 103) | def testAssignMultiple(self):
method testAssignTuple (line 110) | def testAssignTuple(self):
method testAssignNested (line 117) | def testAssignNested(self):
method testAugAssignSingle (line 125) | def testAugAssignSingle(self):
method testVisitClassDef (line 131) | def testVisitClassDef(self):
method testExceptHandler (line 137) | def testExceptHandler(self):
method testFor (line 150) | def testFor(self):
method testFunctionDef (line 156) | def testFunctionDef(self):
method testImport (line 162) | def testImport(self):
method testImportFrom (line 169) | def testImportFrom(self):
method testGlobal (line 176) | def testGlobal(self):
method testGlobalIsParam (line 183) | def testGlobalIsParam(self):
method testGlobalUsedPriorToDeclaration (line 189) | def testGlobalUsedPriorToDeclaration(self):
class FunctionBlockVisitorTest (line 196) | class FunctionBlockVisitorTest(unittest.TestCase):
method testArgs (line 198) | def testArgs(self):
method testArgsDuplicate (line 210) | def testArgsDuplicate(self):
method testYield (line 215) | def testYield(self):
method testYieldExpr (line 220) | def testYieldExpr(self):
function _MakeModuleBlock (line 228) | def _MakeModuleBlock():
function _ParseStmt (line 234) | def _ParseStmt(stmt_str):
FILE: compiler/expr.py
class GeneratedExpr (line 26) | class GeneratedExpr(object):
method __enter__ (line 31) | def __enter__(self):
method __exit__ (line 34) | def __exit__(self, unused_type, unused_value, unused_traceback):
method expr (line 38) | def expr(self):
method free (line 41) | def free(self):
class GeneratedTempVar (line 45) | class GeneratedTempVar(GeneratedExpr):
method __init__ (line 48) | def __init__(self, block_, name, type_):
method expr (line 54) | def expr(self):
method free (line 57) | def free(self):
class GeneratedLocalVar (line 61) | class GeneratedLocalVar(GeneratedExpr):
method __init__ (line 64) | def __init__(self, name):
method expr (line 68) | def expr(self):
class GeneratedLiteral (line 72) | class GeneratedLiteral(GeneratedExpr):
method __init__ (line 75) | def __init__(self, expr):
method expr (line 79) | def expr(self):
class BlankVar (line 86) | class BlankVar(GeneratedExpr):
method __init__ (line 87) | def __init__(self):
method expr (line 91) | def expr(self):
FILE: compiler/expr_visitor.py
class ExprVisitor (line 30) | class ExprVisitor(algorithm.Visitor):
method __init__ (line 35) | def __init__(self, stmt_visitor):
method generic_visit (line 40) | def generic_visit(self, node):
method visit_Attribute (line 44) | def visit_Attribute(self, node):
method visit_BinOp (line 52) | def visit_BinOp(self, node):
method visit_BoolOp (line 65) | def visit_BoolOp(self, node):
method visit_Call (line 87) | def visit_Call(self, node):
method visit_Compare (line 131) | def visit_Compare(self, node):
method visit_Dict (line 174) | def visit_Dict(self, node):
method visit_Set (line 185) | def visit_Set(self, node):
method visit_DictComp (line 196) | def visit_DictComp(self, node):
method visit_ExtSlice (line 206) | def visit_ExtSlice(self, node):
method visit_GeneratorExp (line 223) | def visit_GeneratorExp(self, node):
method visit_IfExp (line 239) | def visit_IfExp(self, node):
method visit_Index (line 258) | def visit_Index(self, node):
method visit_Lambda (line 264) | def visit_Lambda(self, node):
method visit_List (line 270) | def visit_List(self, node):
method visit_ListComp (line 277) | def visit_ListComp(self, node):
method visit_Name (line 286) | def visit_Name(self, node):
method visit_Num (line 289) | def visit_Num(self, node):
method visit_Slice (line 310) | def visit_Slice(self, node):
method visit_Subscript (line 325) | def visit_Subscript(self, node):
method visit_Str (line 333) | def visit_Str(self, node):
method visit_Tuple (line 341) | def visit_Tuple(self, node):
method visit_UnaryOp (line 353) | def visit_UnaryOp(self, node):
method visit_Yield (line 372) | def visit_Yield(self, node):
method _visit_seq_elts (line 416) | def _visit_seq_elts(self, elts):
method _node_not_implemented (line 425) | def _node_not_implemented(self, node):
FILE: compiler/expr_visitor_test.py
function _MakeExprTest (line 32) | def _MakeExprTest(expr):
function _MakeLiteralTest (line 39) | def _MakeLiteralTest(lit, expected=None):
function _MakeSliceTest (line 49) | def _MakeSliceTest(subscript, want):
class ExprVisitorTest (line 63) | class ExprVisitorTest(unittest.TestCase):
method testAttribute (line 67) | def testAttribute(self):
method testCall (line 93) | def testCall(self):
method testCallKeywords (line 100) | def testCallKeywords(self):
method testCallVarArgs (line 107) | def testCallVarArgs(self):
method testCallKwargs (line 114) | def testCallKwargs(self):
method testNameGlobal (line 171) | def testNameGlobal(self):
method testNameLocal (line 177) | def testNameLocal(self):
function _MakeModuleBlock (line 224) | def _MakeModuleBlock():
function _ParseExpr (line 229) | def _ParseExpr(expr):
function _ParseAndVisitExpr (line 233) | def _ParseAndVisitExpr(expr):
function _GrumpRun (line 239) | def _GrumpRun(cmd):
FILE: compiler/imputil.py
class Import (line 36) | class Import(object):
method __init__ (line 49) | def __init__(self, name, script=None, is_native=False):
method add_binding (line 55) | def add_binding(self, bind_type, alias, value):
class Importer (line 59) | class Importer(algorithm.Visitor):
method __init__ (line 64) | def __init__(self, gopath, modname, script, absolute_import):
method generic_visit (line 82) | def generic_visit(self, node):
method visit_Import (line 85) | def visit_Import(self, node):
method visit_ImportFrom (line 103) | def visit_ImportFrom(self, node):
method _resolve_import (line 149) | def _resolve_import(self, node, modname):
method _resolve_relative_import (line 160) | def _resolve_relative_import(self, level, node, modname):
class _ImportCollector (line 176) | class _ImportCollector(algorithm.Visitor):
method __init__ (line 180) | def __init__(self, importer, future_node):
method visit_Import (line 185) | def visit_Import(self, node):
method visit_ImportFrom (line 188) | def visit_ImportFrom(self, node):
function collect_imports (line 196) | def collect_imports(modname, script, gopath):
function calculate_transitive_deps (line 207) | def calculate_transitive_deps(modname, script, gopath):
function find_script (line 236) | def find_script(dirname, name):
class FutureFeatures (line 265) | class FutureFeatures(object):
method __init__ (line 268) | def __init__(self, absolute_import=False, division=False,
function _make_future_features (line 276) | def _make_future_features(node):
function parse_future_features (line 296) | def parse_future_features(mod):
FILE: compiler/imputil_test.py
class ImportVisitorTest (line 33) | class ImportVisitorTest(unittest.TestCase):
method setUp (line 50) | def setUp(self):
method tearDown (line 81) | def tearDown(self):
method testImportEmptyPath (line 84) | def testImportEmptyPath(self):
method testImportTopLevelModule (line 89) | def testImportTopLevelModule(self):
method testImportTopLevelPackage (line 94) | def testImportTopLevelPackage(self):
method testImportPackageModuleAbsolute (line 99) | def testImportPackageModuleAbsolute(self):
method testImportFromSubModule (line 104) | def testImportFromSubModule(self):
method testImportPackageModuleRelative (line 109) | def testImportPackageModuleRelative(self):
method testImportPackageModuleRelativeFromSubModule (line 115) | def testImportPackageModuleRelativeFromSubModule(self):
method testImportPackageModuleAbsoluteImport (line 123) | def testImportPackageModuleAbsoluteImport(self):
method testImportMultiple (line 131) | def testImportMultiple(self):
method testImportAs (line 138) | def testImportAs(self):
method testImportFrom (line 143) | def testImportFrom(self):
method testImportFromMember (line 148) | def testImportFromMember(self):
method testImportFromMultiple (line 153) | def testImportFromMultiple(self):
method testImportFromMixedMembers (line 160) | def testImportFromMixedMembers(self):
method testImportFromAs (line 167) | def testImportFromAs(self):
method testImportFromAsMembers (line 172) | def testImportFromAsMembers(self):
method testImportFromWildcardRaises (line 177) | def testImportFromWildcardRaises(self):
method testImportFromFuture (line 181) | def testImportFromFuture(self):
method testImportFromNative (line 184) | def testImportFromNative(self):
method testImportFromNativeMultiple (line 189) | def testImportFromNativeMultiple(self):
method testImportFromNativeAs (line 195) | def testImportFromNativeAs(self):
method testRelativeImportNonPackage (line 200) | def testRelativeImportNonPackage(self):
method testRelativeImportBeyondTopLevel (line 204) | def testRelativeImportBeyondTopLevel(self):
method testRelativeModuleNoExist (line 208) | def testRelativeModuleNoExist(self):
method testRelativeModule (line 212) | def testRelativeModule(self):
method testRelativeModuleFromSubModule (line 218) | def testRelativeModuleFromSubModule(self):
method testRelativeModuleMember (line 226) | def testRelativeModuleMember(self):
method testRelativeModuleMemberMixed (line 232) | def testRelativeModuleMemberMixed(self):
method testRelativeUpLevel (line 240) | def testRelativeUpLevel(self):
method testRelativeUpLevelMember (line 246) | def testRelativeUpLevelMember(self):
method _check_imports (line 252) | def _check_imports(self, stmt, want):
method _assert_imports_equal (line 256) | def _assert_imports_equal(self, want, got):
method _materialize_tree (line 260) | def _materialize_tree(self, dirname, spec):
class MakeFutureFeaturesTest (line 271) | class MakeFutureFeaturesTest(unittest.TestCase):
method testImportFromFuture (line 273) | def testImportFromFuture(self):
method testImportFromFutureParseError (line 289) | def testImportFromFutureParseError(self):
class ParseFutureFeaturesTest (line 308) | class ParseFutureFeaturesTest(unittest.TestCase):
method testFutureFeatures (line 310) | def testFutureFeatures(self):
method testUnimplementedFutureRaises (line 341) | def testUnimplementedFutureRaises(self):
method testUndefinedFutureRaises (line 347) | def testUndefinedFutureRaises(self):
FILE: compiler/shard_test.py
class _ShardAction (line 26) | class _ShardAction(argparse.Action):
method __call__ (line 28) | def __call__(self, parser, args, values, option_string=None):
class _ShardTestLoader (line 39) | class _ShardTestLoader(unittest.TestLoader):
method __init__ (line 41) | def __init__(self, shard, count):
method getTestCaseNames (line 46) | def getTestCaseNames(self, test_case_cls):
class _ShardTestRunner (line 57) | class _ShardTestRunner(object):
method run (line 59) | def run(self, test):
function main (line 69) | def main():
FILE: compiler/stmt.py
class StatementVisitor (line 46) | class StatementVisitor(algorithm.Visitor):
method __init__ (line 51) | def __init__(self, block_, future_node=None):
method generic_visit (line 57) | def generic_visit(self, node):
method visit_expr (line 61) | def visit_expr(self, node):
method visit_Assert (line 64) | def visit_Assert(self, node):
method visit_AugAssign (line 72) | def visit_AugAssign(self, node):
method visit_Assign (line 86) | def visit_Assign(self, node):
method visit_Break (line 92) | def visit_Break(self, node):
method visit_ClassDef (line 100) | def visit_ClassDef(self, node):
method visit_Continue (line 167) | def visit_Continue(self, node):
method visit_Delete (line 173) | def visit_Delete(self, node):
method visit_Expr (line 192) | def visit_Expr(self, node):
method visit_For (line 196) | def visit_For(self, node):
method visit_FunctionDef (line 219) | def visit_FunctionDef(self, node):
method visit_Global (line 231) | def visit_Global(self, node):
method visit_If (line 234) | def visit_If(self, node):
method visit_Import (line 275) | def visit_Import(self, node):
method visit_ImportFrom (line 280) | def visit_ImportFrom(self, node):
method visit_Module (line 289) | def visit_Module(self, node):
method visit_Pass (line 292) | def visit_Pass(self, node):
method visit_Print (line 295) | def visit_Print(self, node):
method visit_Raise (line 308) | def visit_Raise(self, node):
method visit_Return (line 321) | def visit_Return(self, node):
method visit_Try (line 333) | def visit_Try(self, node):
method visit_While (line 412) | def visit_While(self, node):
method visit_With (line 420) | def visit_With(self, node):
method visit_function_inline (line 496) | def visit_function_inline(self, node):
method _assign_target (line 583) | def _assign_target(self, target, value):
method _build_assign_target (line 600) | def _build_assign_target(self, target, assigns):
method _import_and_bind (line 612) | def _import_and_bind(self, imp):
method _tie_target (line 642) | def _tie_target(self, target, value):
method _visit_each (line 655) | def _visit_each(self, nodes):
method _visit_loop (line 659) | def _visit_loop(self, testfunc, node):
method _write_except_block (line 697) | def _write_except_block(self, label, exc, except_node):
method _write_except_dispatcher (line 706) | def _write_except_dispatcher(self, exc, tb, handlers):
method _write_py_context (line 745) | def _write_py_context(self, lineno):
FILE: compiler/stmt_test.py
class StatementVisitorTest (line 35) | class StatementVisitorTest(unittest.TestCase):
method testAssertNoMsg (line 37) | def testAssertNoMsg(self):
method testAssertMsg (line 44) | def testAssertMsg(self):
method testBareAssert (line 52) | def testBareAssert(self):
method testAssignAttribute (line 66) | def testAssignAttribute(self):
method testAssignName (line 72) | def testAssignName(self):
method testAssignMultiple (line 77) | def testAssignMultiple(self):
method testAssignSubscript (line 82) | def testAssignSubscript(self):
method testAssignTuple (line 88) | def testAssignTuple(self):
method testAugAssign (line 94) | def testAugAssign(self):
method testAugAssignBitAnd (line 100) | def testAugAssignBitAnd(self):
method testAugAssignPow (line 106) | def testAugAssignPow(self):
method testClassDef (line 112) | def testClassDef(self):
method testClassDefWithVar (line 118) | def testClassDefWithVar(self):
method testDeleteAttribute (line 124) | def testDeleteAttribute(self):
method testDeleteClassLocal (line 131) | def testDeleteClassLocal(self):
method testDeleteGlobal (line 138) | def testDeleteGlobal(self):
method testDeleteLocal (line 144) | def testDeleteLocal(self):
method testDeleteNonexistentLocal (line 156) | def testDeleteNonexistentLocal(self):
method testDeleteSubscript (line 161) | def testDeleteSubscript(self):
method testExprCall (line 167) | def testExprCall(self):
method testExprNameGlobal (line 173) | def testExprNameGlobal(self):
method testExprNameLocal (line 178) | def testExprNameLocal(self):
method testFor (line 185) | def testFor(self):
method testForBreak (line 190) | def testForBreak(self):
method testForContinue (line 196) | def testForContinue(self):
method testForElse (line 203) | def testForElse(self):
method testForElseBreakNotNested (line 210) | def testForElseBreakNotNested(self):
method testForElseContinueNotNested (line 215) | def testForElseContinueNotNested(self):
method testFunctionDecorator (line 220) | def testFunctionDecorator(self):
method testFunctionDecoratorWithArg (line 229) | def testFunctionDecoratorWithArg(self):
method testFunctionDef (line 240) | def testFunctionDef(self):
method testFunctionDefGenerator (line 246) | def testFunctionDefGenerator(self):
method testFunctionDefGeneratorReturnValue (line 253) | def testFunctionDefGeneratorReturnValue(self):
method testFunctionDefLocal (line 258) | def testFunctionDefLocal(self):
method testIf (line 266) | def testIf(self):
method testIfElif (line 273) | def testIfElif(self):
method testIfElse (line 284) | def testIfElse(self):
method testImport (line 295) | def testImport(self):
method testImportFutureLateRaises (line 300) | def testImportFutureLateRaises(self):
method testFutureUnicodeLiterals (line 305) | def testFutureUnicodeLiterals(self):
method testImportMember (line 311) | def testImportMember(self):
method testImportConflictingPackage (line 316) | def testImportConflictingPackage(self):
method testImportNative (line 321) | def testImportNative(self):
method testImportGrumpy (line 326) | def testImportGrumpy(self):
method testImportNativeType (line 331) | def testImportNativeType(self):
method testImportWildcardMemberRaises (line 336) | def testImportWildcardMemberRaises(self):
method testPrintStatement (line 343) | def testPrintStatement(self):
method testPrintFunction (line 349) | def testPrintFunction(self):
method testRaiseExitStatus (line 360) | def testRaiseExitStatus(self):
method testRaiseInstance (line 363) | def testRaiseInstance(self):
method testRaiseTypeAndArg (line 371) | def testRaiseTypeAndArg(self):
method testRaiseAgain (line 379) | def testRaiseAgain(self):
method testRaiseTraceback (line 389) | def testRaiseTraceback(self):
method testReturn (line 403) | def testReturn(self):
method testTryBareExcept (line 409) | def testTryBareExcept(self):
method testTryElse (line 416) | def testTryElse(self):
method testTryMultipleExcept (line 425) | def testTryMultipleExcept(self):
method testTryFinally (line 436) | def testTryFinally(self):
method testWhile (line 451) | def testWhile(self):
method testWhileElse (line 458) | def testWhileElse(self):
method testWith (line 465) | def testWith(self):
method testWithAs (line 488) | def testWithAs(self):
method testWriteExceptDispatcherBareExcept (line 500) | def testWriteExceptDispatcherBareExcept(self):
method testWriteExceptDispatcherBareExceptionNotLast (line 510) | def testWriteExceptDispatcherBareExceptionNotLast(self):
method testWriteExceptDispatcherMultipleExcept (line 518) | def testWriteExceptDispatcherMultipleExcept(self):
function _MakeModuleBlock (line 531) | def _MakeModuleBlock():
function _ParseAndVisit (line 536) | def _ParseAndVisit(source):
function _GrumpRun (line 547) | def _GrumpRun(cmd):
FILE: compiler/util.py
class CompileError (line 38) | class CompileError(Exception):
method __init__ (line 40) | def __init__(self, node, msg):
class ParseError (line 46) | class ParseError(CompileError):
class ImportError (line 50) | class ImportError(CompileError): # pylint: disable=redefined-builtin
class LateFutureError (line 54) | class LateFutureError(ImportError):
method __init__ (line 56) | def __init__(self, node):
class Writer (line 61) | class Writer(object):
method __init__ (line 64) | def __init__(self, out=None):
method getvalue (line 68) | def getvalue(self):
method indent_block (line 72) | def indent_block(self, n=1):
method write (line 78) | def write(self, output):
method write_block (line 83) | def write_block(self, block_, body):
method write_label (line 103) | def write_label(self, label):
method write_py_context (line 107) | def write_py_context(self, lineno, line):
method write_tmpl (line 110) | def write_tmpl(self, tmpl, **kwargs):
method write_checked_call2 (line 113) | def write_checked_call2(self, result, call, *args, **kwargs):
method write_checked_call1 (line 119) | def write_checked_call1(self, call, *args, **kwargs):
method write_temp_decls (line 125) | def write_temp_decls(self, block_):
method indent (line 130) | def indent(self, n=1):
method dedent (line 133) | def dedent(self, n=1):
function go_str (line 137) | def go_str(value):
function adjust_local_name (line 152) | def adjust_local_name(name):
FILE: compiler/util_test.py
class WriterTest (line 28) | class WriterTest(unittest.TestCase):
method testIndentBlock (line 30) | def testIndentBlock(self):
method testWriteBlock (line 38) | def testWriteBlock(self):
method testWriteMultiline (line 47) | def testWriteMultiline(self):
method testWritePyContext (line 53) | def testWritePyContext(self):
method testWriteSkipBlankLine (line 58) | def testWriteSkipBlankLine(self):
method testWriteTmpl (line 63) | def testWriteTmpl(self):
method testIndent (line 68) | def testIndent(self):
method testDedent (line 74) | def testDedent(self):
FILE: lib/_random.py
function _gorandom (line 31) | def _gorandom(nbytes):
function _int_bit_length (line 45) | def _int_bit_length(n):
function _int_from_bytes (line 54) | def _int_from_bytes(bytes):
class GrumpyRandom (line 63) | class GrumpyRandom(object):
method random (line 70) | def random(self):
method getrandbits (line 74) | def getrandbits(self, k):
method seed (line 84) | def seed(self, a=None):
method _randbelow (line 90) | def _randbelow(self, n):
method getstate (line 101) | def getstate(self, *args, **kwargs):
method setstate (line 104) | def setstate(self, *args, **kwargs):
method jumpahead (line 107) | def jumpahead(self, *args, **kwargs):
FILE: lib/_syscall.py
function invoke (line 18) | def invoke(func, *args):
FILE: lib/itertools.py
class chain (line 20) | class chain(object):
method from_iterable (line 22) | def from_iterable(cls, iterables):
method __init__ (line 29) | def __init__(self, *iterables):
method __iter__ (line 36) | def __iter__(self):
method next (line 39) | def next(self):
function compress (line 50) | def compress(data, selectors):
function count (line 54) | def count(start=0, step=1):
function cycle (line 61) | def cycle(iterable):
function dropwhile (line 71) | def dropwhile(predicate, iterable):
class groupby (line 81) | class groupby(object):
method __init__ (line 84) | def __init__(self, iterable, key=None):
method __iter__ (line 91) | def __iter__(self):
method next (line 94) | def next(self):
method _grouper (line 101) | def _grouper(self, tgtkey):
function ifilter (line 108) | def ifilter(predicate, iterable):
function ifilterfalse (line 116) | def ifilterfalse(predicate, iterable):
function imap (line 124) | def imap(function, *iterables):
function islice (line 134) | def islice(iterable, *args):
function izip (line 144) | def izip(*iterables):
class ZipExhausted (line 150) | class ZipExhausted(Exception):
function izip_longest (line 154) | def izip_longest(*args, **kwds):
function product (line 172) | def product(*args, **kwds):
function permutations (line 183) | def permutations(iterable, r=None):
function combinations (line 192) | def combinations(iterable, r):
function combinations_with_replacement (line 200) | def combinations_with_replacement(iterable, r):
function repeat (line 208) | def repeat(object, times=None):
function starmap (line 217) | def starmap(function, iterable):
function takewhile (line 222) | def takewhile(predicate, iterable):
function tee (line 230) | def tee(iterable, n=2):
FILE: lib/itertools_test.py
function TestCycle (line 19) | def TestCycle():
function TestDropwhile (line 39) | def TestDropwhile():
function TestChain (line 51) | def TestChain():
function TestFromIterable (line 63) | def TestFromIterable():
function TestIFilter (line 75) | def TestIFilter():
function TestIFilterFalse (line 88) | def TestIFilterFalse():
function TestISlice (line 101) | def TestISlice():
function TestIZipLongest (line 113) | def TestIZipLongest():
function TestProduct (line 124) | def TestProduct():
function TestPermutations (line 135) | def TestPermutations():
function TestCombinations (line 149) | def TestCombinations():
function TestCombinationsWithReplacement (line 158) | def TestCombinationsWithReplacement():
function TestGroupBy (line 170) | def TestGroupBy():
function TestTakewhile (line 180) | def TestTakewhile():
FILE: lib/math.py
function ceil (line 30) | def ceil(x):
function copysign (line 34) | def copysign(x, y):
function fabs (line 38) | def fabs(x):
function factorial (line 42) | def factorial(x):
function floor (line 77) | def floor(x):
function fmod (line 81) | def fmod(x):
function frexp (line 85) | def frexp(x):
function isinf (line 94) | def isinf(x):
function isnan (line 98) | def isnan(x):
function ldexp (line 102) | def ldexp(x, i):
function modf (line 106) | def modf(x):
function trunc (line 112) | def trunc(x):
function exp (line 118) | def exp(x):
function expm1 (line 122) | def expm1(x):
function log (line 126) | def log(x, b=None):
function log1p (line 135) | def log1p(x):
function log10 (line 139) | def log10(x):
function pow (line 143) | def pow(x, y):
function sqrt (line 147) | def sqrt(x):
function acos (line 153) | def acos(x):
function asin (line 157) | def asin(x):
function atan (line 161) | def atan(x):
function atan2 (line 165) | def atan2(y, x):
function cos (line 169) | def cos(x):
function hypot (line 173) | def hypot(x, y):
function sin (line 177) | def sin(x):
function tan (line 181) | def tan(x):
function degrees (line 187) | def degrees(x):
function radians (line 191) | def radians(x):
function acosh (line 197) | def acosh(x):
function asinh (line 201) | def asinh(x):
function atanh (line 205) | def atanh(x):
function cosh (line 209) | def cosh(x):
function sinh (line 213) | def sinh(x):
function tanh (line 217) | def tanh(x):
function erf (line 223) | def erf(x):
function erfc (line 227) | def erfc(x):
function gamma (line 231) | def gamma(x):
function lgamma (line 235) | def lgamma(x):
FILE: lib/math_test.py
function TestFactorial (line 23) | def TestFactorial():
function TestFactorialError (line 32) | def TestFactorialError():
function TestLdexp (line 48) | def TestLdexp():
function TestLog (line 55) | def TestLog():
function TestRadians (line 62) | def TestRadians():
function TestDegrees (line 67) | def TestDegrees():
FILE: lib/os/__init__.py
function mkdir (line 48) | def mkdir(path, mode=0o777):
function chdir (line 54) | def chdir(path):
function chmod (line 60) | def chmod(filepath, mode):
function close (line 67) | def close(fd):
function fdopen (line 73) | def fdopen(fd, mode='r'): # pylint: disable=unused-argument
function listdir (line 81) | def listdir(p):
function getcwd (line 88) | def getcwd():
class _Popen (line 95) | class _Popen(object):
method __init__ (line 97) | def __init__(self, command, mode):
method _thread_func (line 132) | def _thread_func(self):
method close (line 138) | def close(self, _):
function popen (line 148) | def popen(command, mode='r'):
function remove (line 152) | def remove(filepath):
function rmdir (line 160) | def rmdir(filepath):
class StatResult (line 168) | class StatResult(object):
method __init__ (line 170) | def __init__(self, info):
method st_mode (line 173) | def st_mode(self):
method st_mtime (line 179) | def st_mtime(self):
method st_size (line 184) | def st_size(self):
function stat (line 190) | def stat(filepath):
function waitpid (line 200) | def waitpid(pid, options):
function _encode_wait_result (line 206) | def _encode_wait_result(status):
FILE: lib/os/path.py
function abspath (line 21) | def abspath(path):
function basename (line 32) | def basename(path):
function exists (line 36) | def exists(path):
function isdir (line 41) | def isdir(path):
function isfile (line 48) | def isfile(path):
function join (line 60) | def join(*paths):
function normpath (line 75) | def normpath(path):
function split (line 82) | def split(path):
FILE: lib/os/path_test.py
function _AssertEqual (line 25) | def _AssertEqual(a, b):
function TestAbspath (line 30) | def TestAbspath():
function TestBasename (line 38) | def TestBasename():
function TestDirname (line 43) | def TestDirname():
function TestExists (line 48) | def TestExists():
function TestIsAbs (line 60) | def TestIsAbs():
function TestIsDir (line 65) | def TestIsDir():
function TestIsFile (line 77) | def TestIsFile():
function TestJoin (line 89) | def TestJoin():
function TestNormPath (line 105) | def TestNormPath():
function TestSplit (line 118) | def TestSplit():
FILE: lib/os_test.py
function TestChdirAndGetCwd (line 23) | def TestChdirAndGetCwd():
function TestChmod (line 37) | def TestChmod():
function TestChmodOSError (line 46) | def TestChmodOSError():
function TestClose (line 56) | def TestClose():
function TestCloseOSError (line 67) | def TestCloseOSError():
function TestEnviron (line 78) | def TestEnviron():
function TestFDOpen (line 82) | def TestFDOpen():
function TestFDOpenOSError (line 93) | def TestFDOpenOSError():
function TestMkdir (line 104) | def TestMkdir():
function TestPopenRead (line 121) | def TestPopenRead():
function TestPopenWrite (line 131) | def TestPopenWrite():
function TestRemove (line 139) | def TestRemove():
function TestRemoveNoExist (line 152) | def TestRemoveNoExist():
function TestRemoveDir (line 164) | def TestRemoveDir():
function TestRmDir (line 176) | def TestRmDir():
function TestRmDirNoExist (line 188) | def TestRmDirNoExist():
function TestRmDirFile (line 200) | def TestRmDirFile():
function TestStatFile (line 213) | def TestStatFile():
function TestStatDir (line 226) | def TestStatDir():
function TestStatNoExist (line 234) | def TestStatNoExist():
function TestWaitPid (line 246) | def TestWaitPid():
FILE: lib/random_test.py
function TestGrumpyRandom (line 21) | def TestGrumpyRandom():
function TestSeed (line 46) | def TestSeed():
function TestRandom (line 56) | def TestRandom():
function TestRandomUniform (line 65) | def TestRandomUniform():
function TestRandomInt (line 72) | def TestRandomInt():
function TestRandomChoice (line 96) | def TestRandomChoice():
FILE: lib/select_.py
class error (line 25) | class error(Exception):
function select (line 29) | def select(rlist, wlist, xlist, timeout=None):
function _fdset_set (line 56) | def _fdset_set(fd, fds):
function _fdset_isset (line 62) | def _fdset_isset(fd, fds):
function _make_fdset (line 68) | def _make_fdset(fd_list):
function _normalize_fd_list (line 75) | def _normalize_fd_list(fds):
FILE: lib/stat.py
function S_ISDIR (line 21) | def S_ISDIR(mode): # pylint: disable=invalid-name
function S_IMODE (line 25) | def S_IMODE(mode): # pylint: disable=invalid-name
FILE: lib/sys.py
class _Flags (line 37) | class _Flags(object):
function exc_clear (line 60) | def exc_clear():
function exc_info (line 64) | def exc_info():
function exit (line 72) | def exit(code=None): # pylint: disable=redefined-builtin
function _getframe (line 76) | def _getframe(depth=0):
FILE: lib/sys_test.py
function TestArgv (line 23) | def TestArgv():
function TestMaxInt (line 27) | def TestMaxInt():
function TestSysModules (line 31) | def TestSysModules():
function TestExcClear (line 35) | def TestExcClear():
function TestExcInfoNoException (line 46) | def TestExcInfoNoException():
function TestExcInfoWithException (line 50) | def TestExcInfoWithException():
function TestExitEmpty (line 62) | def TestExitEmpty():
function TestExitCode (line 71) | def TestExitCode():
function TestExitInvalidArgs (line 80) | def TestExitInvalidArgs():
function TestGetFrame (line 89) | def TestGetFrame():
FILE: lib/tempfile.py
function mkdtemp (line 23) | def mkdtemp(suffix='', prefix='tmp', dir=None):
function mkstemp (line 33) | def mkstemp(suffix='', prefix='tmp', dir=None, text=False):
FILE: lib/tempfile_test.py
function TestMkdTemp (line 22) | def TestMkdTemp():
function TestMkdTempDir (line 30) | def TestMkdTempDir():
function TestMkdTempOSError (line 38) | def TestMkdTempOSError():
function TestMkdTempPrefixSuffix (line 50) | def TestMkdTempPrefixSuffix():
function TestMksTemp (line 58) | def TestMksTemp():
function TestMksTempDir (line 70) | def TestMksTempDir():
function TestMksTempOSError (line 79) | def TestMksTempOSError():
function TestMksTempPerms (line 91) | def TestMksTempPerms():
function TestMksTempPrefixSuffix (line 99) | def TestMksTempPrefixSuffix():
FILE: lib/thread.py
class error (line 4) | class error(Exception):
function get_ident (line 8) | def get_ident():
class LockType (line 15) | class LockType(object):
method __init__ (line 16) | def __init__(self):
method acquire (line 19) | def acquire(self, waitflag=1):
method release (line 25) | def release(self):
method __enter__ (line 28) | def __enter__(self):
method __exit__ (line 31) | def __exit__(self, *args):
function allocate_lock (line 35) | def allocate_lock():
function start_new_thread (line 40) | def start_new_thread(func, args, kwargs=None):
function stack_size (line 55) | def stack_size(n=0):
function _count (line 61) | def _count():
FILE: lib/time.py
class struct_time (line 48) | class struct_time(tuple): #pylint: disable=invalid-name,missing-docstring
method __init__ (line 50) | def __init__(self, args):
method __repr__ (line 62) | def __repr__(self):
method __str__ (line 67) | def __str__(self):
function gmtime (line 71) | def gmtime(seconds=None):
function localtime (line 77) | def localtime(seconds=None):
function mktime (line 83) | def mktime(t):
function sleep (line 87) | def sleep(secs):
function time (line 91) | def time():
function strftime (line 95) | def strftime(format, tt=None): # pylint: disable=missing-docstring,rede...
FILE: lib/weetest.py
class _Benchmark (line 45) | class _Benchmark(object):
method __init__ (line 48) | def __init__(self, bench_func, target_duration):
method Run (line 55) | def Run(self):
method _RunOnce (line 75) | def _RunOnce(self):
method ResetTimer (line 80) | def ResetTimer(self):
class _TestResult (line 85) | class _TestResult(object):
method __init__ (line 88) | def __init__(self, name):
function _RunOneBenchmark (line 95) | def _RunOneBenchmark(name, test_func):
function _RunOneTest (line 117) | def _RunOneTest(name, test_func):
function _WriteXmlFile (line 138) | def _WriteXmlFile(filename, suite_duration, results):
function _RunAll (line 164) | def _RunAll(test_prefix, runner):
function RunBenchmarks (line 183) | def RunBenchmarks():
function RunTests (line 188) | def RunTests():
FILE: lib/weetest_test.py
class _Timer (line 23) | class _Timer(object):
method __init__ (line 25) | def __init__(self):
method Reset (line 28) | def Reset(self):
method time (line 31) | def time(self): # pylint: disable=invalid-name
function TestBenchmark (line 40) | def TestBenchmark():
function TestBenchmarkResetTimer (line 54) | def TestBenchmarkResetTimer():
function TestRunOneBenchmark (line 70) | def TestRunOneBenchmark():
function TestRunOneBenchmarkError (line 85) | def TestRunOneBenchmarkError():
function TestRunOneTest (line 92) | def TestRunOneTest():
function TestWriteXmlFile (line 109) | def TestWriteXmlFile():
function TestRunAll (line 134) | def TestRunAll():
FILE: runtime/baseexception.go
type BaseException (line 22) | type BaseException struct
method ToObject (line 32) | func (e *BaseException) ToObject() *Object {
function toBaseExceptionUnsafe (line 27) | func toBaseExceptionUnsafe(o *Object) *BaseException {
function baseExceptionInit (line 39) | func baseExceptionInit(f *Frame, o *Object, args Args, kwargs KWArgs) (*...
function baseExceptionRepr (line 45) | func baseExceptionRepr(f *Frame, o *Object) (*Object, *BaseException) {
function baseExceptionStr (line 58) | func baseExceptionStr(f *Frame, o *Object) (*Object, *BaseException) {
function initBaseExceptionType (line 71) | func initBaseExceptionType(map[string]*Object) {
FILE: runtime/baseexception_test.go
function TestBaseExceptionCreate (line 21) | func TestBaseExceptionCreate(t *testing.T) {
function TestBaseExceptionInitRaise (line 42) | func TestBaseExceptionInitRaise(t *testing.T) {
function TestBaseExceptionRepr (line 52) | func TestBaseExceptionRepr(t *testing.T) {
function TestBaseExceptionStr (line 69) | func TestBaseExceptionStr(t *testing.T) {
FILE: runtime/basestring.go
constant EncodeDefault (line 23) | EncodeDefault = "utf8"
constant EncodeStrict (line 29) | EncodeStrict = "strict"
constant EncodeReplace (line 31) | EncodeReplace = "replace"
constant EncodeIgnore (line 33) | EncodeIgnore = "ignore"
function initBaseStringType (line 50) | func initBaseStringType(map[string]*Object) {
function normalizeEncoding (line 54) | func normalizeEncoding(encoding string) string {
function escapeRune (line 58) | func escapeRune(r rune) []byte {
FILE: runtime/basestring_test.go
function TestNormalizeEncoding (line 21) | func TestNormalizeEncoding(t *testing.T) {
function BenchmarkEscapeRune (line 39) | func BenchmarkEscapeRune(b *testing.B) {
FILE: runtime/bool.go
function GetBool (line 23) | func GetBool(v bool) *Int {
function boolNative (line 33) | func boolNative(_ *Frame, o *Object) (reflect.Value, *BaseException) {
function boolNew (line 37) | func boolNew(f *Frame, _ *Type, args Args, _ KWArgs) (*Object, *BaseExce...
function boolRepr (line 52) | func boolRepr(_ *Frame, o *Object) (*Object, *BaseException) {
function initBoolType (line 60) | func initBoolType(map[string]*Object) {
FILE: runtime/bool_test.go
function TestBoolCompare (line 21) | func TestBoolCompare(t *testing.T) {
function TestBoolCreate (line 37) | func TestBoolCreate(t *testing.T) {
function TestBoolStrRepr (line 55) | func TestBoolStrRepr(t *testing.T) {
FILE: runtime/builtin_types.go
function ellipsisRepr (line 53) | func ellipsisRepr(*Frame, *Object) (*Object, *BaseException) {
function noneRepr (line 57) | func noneRepr(*Frame, *Object) (*Object, *BaseException) {
function notImplementedRepr (line 61) | func notImplementedRepr(*Frame, *Object) (*Object, *BaseException) {
function initEllipsisType (line 65) | func initEllipsisType(map[string]*Object) {
function initNoneType (line 70) | func initNoneType(map[string]*Object) {
function initNotImplementedType (line 75) | func initNotImplementedType(map[string]*Object) {
function initUnboundLocalType (line 80) | func initUnboundLocalType(map[string]*Object) {
type typeState (line 84) | type typeState
constant typeStateNotReady (line 87) | typeStateNotReady typeState = iota
constant typeStateInitializing (line 88) | typeStateInitializing
constant typeStateReady (line 89) | typeStateReady
type builtinTypeInit (line 92) | type builtinTypeInit
type builtinTypeInfo (line 94) | type builtinTypeInfo struct
function initBuiltinType (line 193) | func initBuiltinType(typ *Type, info *builtinTypeInfo) {
function builtinAbs (line 215) | func builtinAbs(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
function builtinMapFn (line 222) | func builtinMapFn(f *Frame, args Args, _ KWArgs) (*Object, *BaseExceptio...
function builtinAll (line 251) | func builtinAll(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
function builtinAny (line 269) | func builtinAny(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
function builtinBin (line 287) | func builtinBin(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
function builtinCallable (line 302) | func builtinCallable(f *Frame, args Args, _ KWArgs) (*Object, *BaseExcep...
function builtinChr (line 313) | func builtinChr(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
function builtinCmp (line 324) | func builtinCmp(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
function builtinDelAttr (line 331) | func builtinDelAttr(f *Frame, args Args, _ KWArgs) (*Object, *BaseExcept...
function builtinDir (line 338) | func builtinDir(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseExcep...
function builtinDivMod (line 374) | func builtinDivMod(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseEx...
function builtinFrame (line 381) | func builtinFrame(f *Frame, args Args, _ KWArgs) (*Object, *BaseExceptio...
function builtinGetAttr (line 389) | func builtinGetAttr(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseE...
function builtinGlobals (line 405) | func builtinGlobals(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseE...
function builtinHasAttr (line 412) | func builtinHasAttr(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseE...
function builtinHash (line 426) | func builtinHash(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseExce...
function builtinHex (line 437) | func builtinHex(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
function builtinID (line 445) | func builtinID(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseExcept...
function builtinIsInstance (line 452) | func builtinIsInstance(f *Frame, args Args, kwargs KWArgs) (*Object, *Ba...
function builtinIsSubclass (line 463) | func builtinIsSubclass(f *Frame, args Args, kwargs KWArgs) (*Object, *Ba...
function builtinIter (line 474) | func builtinIter(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseExce...
function builtinLen (line 481) | func builtinLen(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseExcep...
function builtinMax (line 492) | func builtinMax(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseExcep...
function builtinMin (line 496) | func builtinMin(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseExcep...
function builtinNext (line 500) | func builtinNext(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseExce...
function builtinOct (line 514) | func builtinOct(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
function builtinOpen (line 522) | func builtinOpen(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseExce...
function builtinOrd (line 526) | func builtinOrd(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
function builtinPrint (line 549) | func builtinPrint(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseExc...
function builtinRange (line 576) | func builtinRange(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseExc...
function builtinRawInput (line 584) | func builtinRawInput(f *Frame, args Args, kwargs KWArgs) (*Object, *Base...
function builtinRepr (line 615) | func builtinRepr(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseExce...
function builtinRound (line 626) | func builtinRound(f *Frame, args Args, _ KWArgs) (*Object, *BaseExceptio...
function builtinSetAttr (line 665) | func builtinSetAttr(f *Frame, args Args, _ KWArgs) (*Object, *BaseExcept...
function builtinSorted (line 672) | func builtinSorted(f *Frame, args Args, _ KWArgs) (*Object, *BaseExcepti...
function builtinSum (line 685) | func builtinSum(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
function builtinUniChr (line 714) | func builtinUniChr(f *Frame, args Args, _ KWArgs) (*Object, *BaseExcepti...
function builtinZip (line 725) | func builtinZip(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
function init (line 755) | func init() {
function builtinMinMax (line 822) | func builtinMinMax(f *Frame, doMax bool, args Args, kwargs KWArgs) (*Obj...
function numberToBase (line 885) | func numberToBase(prefix string, base int, o *Object) string {
function initIters (line 905) | func initIters(f *Frame, items []*Object) ([]*Object, *BaseException) {
function zipLongest (line 921) | func zipLongest(f *Frame, args Args) ([][]*Object, *BaseException) {
FILE: runtime/builtin_types_test.go
function TestBuiltinDelAttr (line 26) | func TestBuiltinDelAttr(t *testing.T) {
function TestBuiltinFuncs (line 54) | func TestBuiltinFuncs(t *testing.T) {
function TestBuiltinGlobals (line 367) | func TestBuiltinGlobals(t *testing.T) {
function TestEllipsisRepr (line 381) | func TestEllipsisRepr(t *testing.T) {
function TestNoneRepr (line 388) | func TestNoneRepr(t *testing.T) {
function TestNotImplementedRepr (line 395) | func TestNotImplementedRepr(t *testing.T) {
function captureStdout (line 404) | func captureStdout(f *Frame, fn func() *BaseException) (string, *BaseExc...
function TestBuiltinSetAttr (line 455) | func TestBuiltinSetAttr(t *testing.T) {
function newTestIndexObject (line 540) | func newTestIndexObject(index int) *Object {
FILE: runtime/bytearray.go
type ByteArray (line 30) | type ByteArray struct
method ToObject (line 41) | func (a *ByteArray) ToObject() *Object {
method Value (line 46) | func (a *ByteArray) Value() []byte {
function toByteArrayUnsafe (line 36) | func toByteArrayUnsafe(o *Object) *ByteArray {
function byteArrayEq (line 50) | func byteArrayEq(f *Frame, v, w *Object) (*Object, *BaseException) {
function byteArrayGE (line 54) | func byteArrayGE(f *Frame, v, w *Object) (*Object, *BaseException) {
function byteArrayGetItem (line 58) | func byteArrayGetItem(f *Frame, o, key *Object) (result *Object, raised ...
function byteArrayGT (line 96) | func byteArrayGT(f *Frame, v, w *Object) (*Object, *BaseException) {
function byteArrayInit (line 100) | func byteArrayInit(f *Frame, o *Object, args Args, _ KWArgs) (*Object, *...
function byteArrayLE (line 111) | func byteArrayLE(f *Frame, v, w *Object) (*Object, *BaseException) {
function byteArrayLT (line 115) | func byteArrayLT(f *Frame, v, w *Object) (*Object, *BaseException) {
function byteArrayNative (line 119) | func byteArrayNative(f *Frame, o *Object) (reflect.Value, *BaseException) {
function byteArrayNE (line 127) | func byteArrayNE(f *Frame, v, w *Object) (*Object, *BaseException) {
function byteArrayRepr (line 131) | func byteArrayRepr(f *Frame, o *Object) (*Object, *BaseException) {
function byteArrayStr (line 142) | func byteArrayStr(f *Frame, o *Object) (*Object, *BaseException) {
function initByteArrayType (line 150) | func initByteArrayType(dict map[string]*Object) {
function byteArrayCompare (line 164) | func byteArrayCompare(v, w *Object, ltResult, eqResult, gtResult *Int) *...
FILE: runtime/bytearray_test.go
function TestByteArrayCompare (line 21) | func TestByteArrayCompare(t *testing.T) {
function TestByteArrayGetItem (line 41) | func TestByteArrayGetItem(t *testing.T) {
function TestByteArrayInit (line 69) | func TestByteArrayInit(t *testing.T) {
function TestByteArrayNative (line 81) | func TestByteArrayNative(t *testing.T) {
function TestByteArrayRepr (line 92) | func TestByteArrayRepr(t *testing.T) {
function TestByteArrayStr (line 104) | func TestByteArrayStr(t *testing.T) {
function newTestByteArray (line 116) | func newTestByteArray(s string) *ByteArray {
FILE: runtime/code.go
type CodeFlag (line 25) | type CodeFlag
constant CodeFlagVarArg (line 29) | CodeFlagVarArg CodeFlag = 4
constant CodeFlagKWArg (line 31) | CodeFlagKWArg CodeFlag = 8
type Code (line 35) | type Code struct
method Eval (line 57) | func (c *Code) Eval(f *Frame, globals *Dict, args Args, kwargs KWArgs)...
function NewCode (line 47) | func NewCode(name, filename string, params []Param, flags CodeFlag, fn f...
function toCodeUnsafe (line 52) | func toCodeUnsafe(o *Object) *Code {
FILE: runtime/code_test.go
function TestXxx (line 21) | func TestXxx(t *testing.T) {
function TestNewCodeKeywordsCheck (line 24) | func TestNewCodeKeywordsCheck(t *testing.T) {
function TestNewCode (line 37) | func TestNewCode(t *testing.T) {
function TestCodeEvalRestoreExc (line 78) | func TestCodeEvalRestoreExc(t *testing.T) {
FILE: runtime/complex.go
type Complex (line 32) | type Complex struct
method ToObject (line 47) | func (c *Complex) ToObject() *Object {
method Value (line 52) | func (c *Complex) Value() complex128 {
function NewComplex (line 38) | func NewComplex(value complex128) *Complex {
function toComplexUnsafe (line 42) | func toComplexUnsafe(o *Object) *Complex {
function complexAbs (line 56) | func complexAbs(f *Frame, o *Object) (*Object, *BaseException) {
function complexAdd (line 61) | func complexAdd(f *Frame, v, w *Object) (*Object, *BaseException) {
function complexCompareNotSupported (line 67) | func complexCompareNotSupported(f *Frame, v, w *Object) (*Object, *BaseE...
function complexComplex (line 74) | func complexComplex(f *Frame, o *Object) (*Object, *BaseException) {
function complexDiv (line 78) | func complexDiv(f *Frame, v, w *Object) (*Object, *BaseException) {
function complexDivMod (line 87) | func complexDivMod(f *Frame, v, w *Object) (*Object, *BaseException) {
function complexEq (line 96) | func complexEq(f *Frame, v, w *Object) (*Object, *BaseException) {
function complexFloorDiv (line 104) | func complexFloorDiv(f *Frame, v, w *Object) (*Object, *BaseException) {
function complexHash (line 113) | func complexHash(f *Frame, o *Object) (*Object, *BaseException) {
function complexMod (line 122) | func complexMod(f *Frame, v, w *Object) (*Object, *BaseException) {
function complexMul (line 131) | func complexMul(f *Frame, v, w *Object) (*Object, *BaseException) {
function complexNE (line 137) | func complexNE(f *Frame, v, w *Object) (*Object, *BaseException) {
function complexNeg (line 145) | func complexNeg(f *Frame, o *Object) (*Object, *BaseException) {
function complexNew (line 150) | func complexNew(f *Frame, t *Type, args Args, _ KWArgs) (*Object, *BaseE...
function complexNonZero (line 212) | func complexNonZero(f *Frame, o *Object) (*Object, *BaseException) {
function complexPos (line 216) | func complexPos(f *Frame, o *Object) (*Object, *BaseException) {
function complexPow (line 220) | func complexPow(f *Frame, v, w *Object) (*Object, *BaseException) {
function complexRAdd (line 226) | func complexRAdd(f *Frame, v, w *Object) (*Object, *BaseException) {
function complexRDiv (line 232) | func complexRDiv(f *Frame, v, w *Object) (*Object, *BaseException) {
function complexRDivMod (line 241) | func complexRDivMod(f *Frame, v, w *Object) (*Object, *BaseException) {
function complexRepr (line 250) | func complexRepr(f *Frame, o *Object) (*Object, *BaseException) {
function complexRFloorDiv (line 271) | func complexRFloorDiv(f *Frame, v, w *Object) (*Object, *BaseException) {
function complexRMod (line 280) | func complexRMod(f *Frame, v, w *Object) (*Object, *BaseException) {
function complexRMul (line 289) | func complexRMul(f *Frame, v, w *Object) (*Object, *BaseException) {
function complexRPow (line 295) | func complexRPow(f *Frame, v, w *Object) (*Object, *BaseException) {
function complexRSub (line 301) | func complexRSub(f *Frame, v, w *Object) (*Object, *BaseException) {
function complexSub (line 307) | func complexSub(f *Frame, v, w *Object) (*Object, *BaseException) {
function initComplexType (line 313) | func initComplexType(dict map[string]*Object) {
function complex128Convert (line 346) | func complex128Convert(f *Frame, o *Object) (complex128, *BaseException) {
function complexArithmeticOp (line 364) | func complexArithmeticOp(f *Frame, method string, v, w *Object, fun func...
function complexCoerce (line 386) | func complexCoerce(o *Object) (complex128, bool) {
function complexCompare (line 400) | func complexCompare(v *Complex, w *Object) (bool, bool) {
function complexConvert (line 409) | func complexConvert(complexSlot *unaryOpSlot, f *Frame, o *Object) (*Com...
function complexDivModOp (line 421) | func complexDivModOp(f *Frame, method string, v, w *Object, fun func(v, ...
function complexDivAndModOp (line 436) | func complexDivAndModOp(f *Frame, method string, v, w *Object, fun func(...
function complexFloorDivOp (line 451) | func complexFloorDivOp(v, w complex128) complex128 {
function complexModOp (line 455) | func complexModOp(v, w complex128) complex128 {
constant blank (line 460) | blank = iota
constant real1 (line 461) | real1
constant imag1 (line 462) | imag1
constant real2 (line 463) | real2
constant sign2 (line 464) | sign2
constant imag3 (line 465) | imag3
constant real4 (line 466) | real4
constant sign5 (line 467) | sign5
constant onlyJ (line 468) | onlyJ
function parseComplex (line 476) | func parseComplex(s string) (complex128, error) {
function unsignNaN (line 530) | func unsignNaN(s string) string {
FILE: runtime/complex_test.go
function TestComplexAbs (line 25) | func TestComplexAbs(t *testing.T) {
function TestComplexEq (line 55) | func TestComplexEq(t *testing.T) {
function TestComplexBinaryOps (line 82) | func TestComplexBinaryOps(t *testing.T) {
function TestComplexCompareNotSupported (line 216) | func TestComplexCompareNotSupported(t *testing.T) {
function TestComplexDivMod (line 231) | func TestComplexDivMod(t *testing.T) {
function TestComplexNE (line 266) | func TestComplexNE(t *testing.T) {
function TestComplexNew (line 289) | func TestComplexNew(t *testing.T) {
function TestComplexNonZero (line 394) | func TestComplexNonZero(t *testing.T) {
function TestComplexPos (line 411) | func TestComplexPos(t *testing.T) {
function TestComplexRepr (line 430) | func TestComplexRepr(t *testing.T) {
function TestParseComplex (line 447) | func TestParseComplex(t *testing.T) {
function TestComplexHash (line 499) | func TestComplexHash(t *testing.T) {
function floatsAreSame (line 514) | func floatsAreSame(a, b float64) bool {
function complexesAreSame (line 518) | func complexesAreSame(a, b complex128) bool {
function tupleComplexesAreSame (line 522) | func tupleComplexesAreSame(got, want *Object) bool {
FILE: runtime/core.go
function Abs (line 33) | func Abs(f *Frame, o *Object) (*Object, *BaseException) {
function Add (line 43) | func Add(f *Frame, v, w *Object) (*Object, *BaseException) {
function And (line 49) | func And(f *Frame, v, w *Object) (*Object, *BaseException) {
function Assert (line 56) | func Assert(f *Frame, cond *Object, msg *Object) *BaseException {
function Compare (line 79) | func Compare(f *Frame, v, w *Object) (*Object, *BaseException) {
function Contains (line 99) | func Contains(f *Frame, seq, value *Object) (bool, *BaseException) {
function DelAttr (line 132) | func DelAttr(f *Frame, o *Object, name *Str) *BaseException {
function DelVar (line 142) | func DelVar(f *Frame, namespace *Dict, name *Str) *BaseException {
function DelItem (line 154) | func DelItem(f *Frame, o, key *Object) *BaseException {
function Div (line 164) | func Div(f *Frame, v, w *Object) (*Object, *BaseException) {
function DivMod (line 170) | func DivMod(f *Frame, v, w *Object) (*Object, *BaseException) {
function Eq (line 175) | func Eq(f *Frame, v, w *Object) (*Object, *BaseException) {
function FloorDiv (line 187) | func FloorDiv(f *Frame, v, w *Object) (*Object, *BaseException) {
function FormatExc (line 193) | func FormatExc(f *Frame) (s string) {
function GE (line 222) | func GE(f *Frame, v, w *Object) (*Object, *BaseException) {
function GetItem (line 234) | func GetItem(f *Frame, o, key *Object) (*Object, *BaseException) {
function GetAttr (line 244) | func GetAttr(f *Frame, o *Object, name *Str, def *Object) (*Object, *Bas...
function GT (line 260) | func GT(f *Frame, v, w *Object) (*Object, *BaseException) {
function Hash (line 272) | func Hash(f *Frame, o *Object) (*Int, *BaseException) {
function Hex (line 289) | func Hex(f *Frame, o *Object) (*Object, *BaseException) {
function IAdd (line 307) | func IAdd(f *Frame, v, w *Object) (*Object, *BaseException) {
function IAnd (line 313) | func IAnd(f *Frame, v, w *Object) (*Object, *BaseException) {
function IDiv (line 319) | func IDiv(f *Frame, v, w *Object) (*Object, *BaseException) {
function IFloorDiv (line 325) | func IFloorDiv(f *Frame, v, w *Object) (*Object, *BaseException) {
function ILShift (line 331) | func ILShift(f *Frame, v, w *Object) (*Object, *BaseException) {
function IMod (line 337) | func IMod(f *Frame, v, w *Object) (*Object, *BaseException) {
function IMul (line 343) | func IMul(f *Frame, v, w *Object) (*Object, *BaseException) {
function Invert (line 349) | func Invert(f *Frame, o *Object) (*Object, *BaseException) {
function IOr (line 358) | func IOr(f *Frame, v, w *Object) (*Object, *BaseException) {
function IPow (line 363) | func IPow(f *Frame, v, w *Object) (*Object, *BaseException) {
function IRShift (line 369) | func IRShift(f *Frame, v, w *Object) (*Object, *BaseException) {
function IsInstance (line 377) | func IsInstance(f *Frame, o *Object, classinfo *Object) (bool, *BaseExce...
function IsSubclass (line 385) | func IsSubclass(f *Frame, o *Object, classinfo *Object) (bool, *BaseExce...
function IsTrue (line 409) | func IsTrue(f *Frame, o *Object) (bool, *BaseException) {
function ISub (line 440) | func ISub(f *Frame, v, w *Object) (*Object, *BaseException) {
function Iter (line 450) | func Iter(f *Frame, o *Object) (*Object, *BaseException) {
function IXor (line 464) | func IXor(f *Frame, v, w *Object) (*Object, *BaseException) {
function LE (line 469) | func LE(f *Frame, v, w *Object) (*Object, *BaseException) {
function Len (line 481) | func Len(f *Frame, o *Object) (*Int, *BaseException) {
function LShift (line 498) | func LShift(f *Frame, v, w *Object) (*Object, *BaseException) {
function LT (line 503) | func LT(f *Frame, v, w *Object) (*Object, *BaseException) {
function Mod (line 516) | func Mod(f *Frame, v, w *Object) (*Object, *BaseException) {
function Mul (line 522) | func Mul(f *Frame, v, w *Object) (*Object, *BaseException) {
function Pow (line 528) | func Pow(f *Frame, v, w *Object) (*Object, *BaseException) {
function Or (line 534) | func Or(f *Frame, v, w *Object) (*Object, *BaseException) {
function Index (line 540) | func Index(f *Frame, o *Object) (*Object, *BaseException) {
function IndexInt (line 562) | func IndexInt(f *Frame, o *Object) (i int, raised *BaseException) {
function Invoke (line 588) | func Invoke(f *Frame, callable *Object, args Args, varargs *Object, keyw...
function NE (line 648) | func NE(f *Frame, v, w *Object) (*Object, *BaseException) {
function Next (line 662) | func Next(f *Frame, iter *Object) (*Object, *BaseException) {
function Oct (line 672) | func Oct(f *Frame, o *Object) (*Object, *BaseException) {
function Pos (line 690) | func Pos(f *Frame, o *Object) (*Object, *BaseException) {
function Print (line 701) | func Print(f *Frame, args Args, nl bool) *BaseException {
function Repr (line 714) | func Repr(f *Frame, o *Object) (*Str, *BaseException) {
function ResolveClass (line 739) | func ResolveClass(f *Frame, class *Dict, local *Object, name *Str) (*Obj...
function ResolveGlobal (line 754) | func ResolveGlobal(f *Frame, name *Str) (*Object, *BaseException) {
function RShift (line 770) | func RShift(f *Frame, v, w *Object) (*Object, *BaseException) {
function CheckLocal (line 776) | func CheckLocal(f *Frame, value *Object, name string) *BaseException {
function SetAttr (line 786) | func SetAttr(f *Frame, o *Object, name *Str, value *Object) *BaseExcepti...
function SetItem (line 795) | func SetItem(f *Frame, o, key, value *Object) *BaseException {
function StartThread (line 804) | func StartThread(callable *Object) {
function Sub (line 818) | func Sub(f *Frame, v, w *Object) (*Object, *BaseException) {
type TieTarget (line 832) | type TieTarget struct
function Tie (line 845) | func Tie(f *Frame, t TieTarget, o *Object) *BaseException {
function ToInt (line 878) | func ToInt(f *Frame, o *Object) (*Object, *BaseException) {
function ToIntValue (line 899) | func ToIntValue(f *Frame, o *Object) (int, *BaseException) {
function ToNative (line 912) | func ToNative(f *Frame, o *Object) (reflect.Value, *BaseException) {
function ToStr (line 920) | func ToStr(f *Frame, o *Object) (*Str, *BaseException) {
function Neg (line 933) | func Neg(f *Frame, o *Object) (*Object, *BaseException) {
function Xor (line 943) | func Xor(f *Frame, v, w *Object) (*Object, *BaseException) {
constant errResultTooLarge (line 948) | errResultTooLarge = "result too large"
constant errUnsupportedOperand (line 949) | errUnsupportedOperand = "unsupported operand type(s) for %s: '%s' and '%s'"
function binaryOp (line 955) | func binaryOp(f *Frame, v, w *Object, op, vrop, wrop *binaryOpSlot, opNa...
function inplaceOp (line 990) | func inplaceOp(f *Frame, v, w *Object, slot *binaryOpSlot, fallback bina...
type compareOp (line 997) | type compareOp
method swapped (line 1017) | func (op compareOp) swapped() compareOp {
method slot (line 1021) | func (op compareOp) slot(t *Type) *binaryOpSlot {
constant compareOpLT (line 1000) | compareOpLT compareOp = iota
constant compareOpLE (line 1001) | compareOpLE
constant compareOpEq (line 1002) | compareOpEq
constant compareOpNE (line 1003) | compareOpNE
constant compareOpGE (line 1004) | compareOpGE
constant compareOpGT (line 1005) | compareOpGT
function compareRich (line 1039) | func compareRich(f *Frame, op compareOp, v, w *Object) (*Object, *BaseEx...
function convert3wayToObject (line 1053) | func convert3wayToObject(op compareOp, c int) *Object {
function try3wayToRichCompare (line 1075) | func try3wayToRichCompare(f *Frame, op compareOp, v, w *Object) (*Object...
function tryRichCompare (line 1092) | func tryRichCompare(f *Frame, op compareOp, v, w *Object) (*Object, *Bas...
function compareDefault (line 1126) | func compareDefault(f *Frame, v, w *Object) int {
function tryRichCompareBool (line 1161) | func tryRichCompareBool(f *Frame, op compareOp, v, w *Object) (bool, *Ba...
function halfCompare (line 1179) | func halfCompare(f *Frame, v, w *Object) (*Object, *BaseException) {
function try3wayCompare (line 1195) | func try3wayCompare(f *Frame, v, w *Object) (*Object, *BaseException) {
function tryRichTo3wayCompare (line 1214) | func tryRichTo3wayCompare(f *Frame, v, w *Object) (*Object, *BaseExcepti...
function checkFunctionArgs (line 1235) | func checkFunctionArgs(f *Frame, function string, args Args, types ...*T...
function checkFunctionVarArgs (line 1249) | func checkFunctionVarArgs(f *Frame, function string, args Args, types .....
function checkMethodArgs (line 1256) | func checkMethodArgs(f *Frame, method string, args Args, types ...*Type)...
function checkMethodVarArgs (line 1270) | func checkMethodVarArgs(f *Frame, method string, args Args, types ...*Ty...
function hashNotImplemented (line 1277) | func hashNotImplemented(f *Frame, o *Object) (*Object, *BaseException) {
function pyPrint (line 1282) | func pyPrint(f *Frame, args Args, sep, end string, file *File) *BaseExce...
FILE: runtime/core_test.go
function TestAssert (line 26) | func TestAssert(t *testing.T) {
function TestBinaryOps (line 57) | func TestBinaryOps(t *testing.T) {
function TestCompare (line 164) | func TestCompare(t *testing.T) {
function TestCompareDefault (line 243) | func TestCompareDefault(t *testing.T) {
function TestContains (line 288) | func TestContains(t *testing.T) {
function TestDelItem (line 306) | func TestDelItem(t *testing.T) {
function TestFormatException (line 329) | func TestFormatException(t *testing.T) {
function TestGetAttr (line 353) | func TestGetAttr(t *testing.T) {
function TestGetItem (line 399) | func TestGetItem(t *testing.T) {
function TestHash (line 412) | func TestHash(t *testing.T) {
function TestHex (line 434) | func TestHex(t *testing.T) {
function TestIndex (line 460) | func TestIndex(t *testing.T) {
function TestInvert (line 506) | func TestInvert(t *testing.T) {
function TestIsInstanceIsSubclass (line 520) | func TestIsInstanceIsSubclass(t *testing.T) {
function TestIsTrue (line 560) | func TestIsTrue(t *testing.T) {
function TestIter (line 604) | func TestIter(t *testing.T) {
function TestNeg (line 629) | func TestNeg(t *testing.T) {
function TestNext (line 643) | func TestNext(t *testing.T) {
function TestLen (line 674) | func TestLen(t *testing.T) {
function TestLenRaise (line 695) | func TestLenRaise(t *testing.T) {
function TestInvokePositionalArgs (line 714) | func TestInvokePositionalArgs(t *testing.T) {
function TestInvokeKeywordArgs (line 740) | func TestInvokeKeywordArgs(t *testing.T) {
function TestOct (line 774) | func TestOct(t *testing.T) {
function TestPos (line 800) | func TestPos(t *testing.T) {
function TestPyPrint (line 820) | func TestPyPrint(t *testing.T) {
function TestReprRaise (line 859) | func TestReprRaise(t *testing.T) {
function TestReprMethodReturnsNonStr (line 883) | func TestReprMethodReturnsNonStr(t *testing.T) {
function TestResolveClass (line 898) | func TestResolveClass(t *testing.T) {
function TestResolveGlobal (line 926) | func TestResolveGlobal(t *testing.T) {
function TestRichCompare (line 943) | func TestRichCompare(t *testing.T) {
function TestCheckLocal (line 984) | func TestCheckLocal(t *testing.T) {
function TestSetItem (line 997) | func TestSetItem(t *testing.T) {
function TestStartThread (line 1019) | func TestStartThread(t *testing.T) {
function TestStartThreadRaises (line 1030) | func TestStartThreadRaises(t *testing.T) {
function TestTie (line 1043) | func TestTie(t *testing.T) {
function TestToInt (line 1115) | func TestToInt(t *testing.T) {
function TestToIntValue (line 1134) | func TestToIntValue(t *testing.T) {
function TestToNative (line 1147) | func TestToNative(t *testing.T) {
function BenchmarkGetAttr (line 1169) | func BenchmarkGetAttr(b *testing.B) {
function exceptionsAreEquivalent (line 1185) | func exceptionsAreEquivalent(e1 *BaseException, e2 *BaseException) bool {
function getFuncName (line 1209) | func getFuncName(f interface{}) string {
function wrapFuncForTest (line 1216) | func wrapFuncForTest(fun interface{}) *Object {
function mustCreateException (line 1230) | func mustCreateException(t *Type, msg string) *BaseException {
function mustNotRaise (line 1243) | func mustNotRaise(o *Object, raised *BaseException) *Object {
FILE: runtime/descriptor.go
type fieldDescriptorType (line 22) | type fieldDescriptorType
constant fieldDescriptorRO (line 25) | fieldDescriptorRO fieldDescriptorType = iota
constant fieldDescriptorRW (line 26) | fieldDescriptorRW
type Property (line 30) | type Property struct
method ToObject (line 44) | func (p *Property) ToObject() *Object {
function newProperty (line 35) | func newProperty(get, set, del *Object) *Property {
function toPropertyUnsafe (line 39) | func toPropertyUnsafe(o *Object) *Property {
function initPropertyType (line 51) | func initPropertyType(map[string]*Object) {
function propertyDelete (line 58) | func propertyDelete(f *Frame, desc, inst *Object) *BaseException {
function propertyGet (line 67) | func propertyGet(f *Frame, desc, instance *Object, _ *Type) (*Object, *B...
function propertyInit (line 75) | func propertyInit(f *Frame, o *Object, args Args, _ KWArgs) (*Object, *B...
function propertySet (line 97) | func propertySet(f *Frame, desc, inst, value *Object) *BaseException {
function makeStructFieldDescriptor (line 108) | func makeStructFieldDescriptor(t *Type, fieldName, propertyName string, ...
FILE: runtime/descriptor_test.go
function TestPropertyDelete (line 21) | func TestPropertyDelete(t *testing.T) {
function TestPropertyGet (line 35) | func TestPropertyGet(t *testing.T) {
function TestPropertyInit (line 49) | func TestPropertyInit(t *testing.T) {
function TestPropertySet (line 72) | func TestPropertySet(t *testing.T) {
function TestMakeStructFieldDescriptor (line 86) | func TestMakeStructFieldDescriptor(t *testing.T) {
function TestMakeStructFieldDescriptorRWGet (line 114) | func TestMakeStructFieldDescriptorRWGet(t *testing.T) {
function TestMakeStructFieldDescriptorRWSet (line 138) | func TestMakeStructFieldDescriptorRWSet(t *testing.T) {
FILE: runtime/dict.go
constant maxDictSize (line 38) | maxDictSize = 1 << 30
constant minDictSize (line 39) | minDictSize = 8
type dictEntry (line 44) | type dictEntry struct
type dictTable (line 51) | type dictTable struct
method loadEntry (line 84) | func (t *dictTable) loadEntry(i int) *dictEntry {
method storeEntry (line 90) | func (t *dictTable) storeEntry(i int, entry *dictEntry) {
method loadUsed (line 95) | func (t *dictTable) loadUsed() int {
method incUsed (line 99) | func (t *dictTable) incUsed(n int) {
method insertAbsentEntry (line 106) | func (t *dictTable) insertAbsentEntry(entry *dictEntry) {
method lookupEntry (line 125) | func (t *dictTable) lookupEntry(f *Frame, hash int, key *Object) (int,...
method writeEntry (line 174) | func (t *dictTable) writeEntry(f *Frame, index int, entry *dictEntry) ...
function newDictTable (line 68) | func newDictTable(minCapacity int) *dictTable {
type dictEntryIterator (line 212) | type dictEntryIterator struct
method next (line 226) | func (iter *dictEntryIterator) next() *dictEntry {
function newDictEntryIterator (line 219) | func newDictEntryIterator(d *Dict) dictEntryIterator {
type dictVersionGuard (line 247) | type dictVersionGuard struct
method check (line 258) | func (g *dictVersionGuard) check() bool {
function newDictVersionGuard (line 252) | func newDictVersionGuard(d *Dict) dictVersionGuard {
type Dict (line 264) | type Dict struct
method loadTable (line 297) | func (d *Dict) loadTable() *dictTable {
method storeTable (line 303) | func (d *Dict) storeTable(table *dictTable) {
method loadVersion (line 309) | func (d *Dict) loadVersion() int64 {
method incVersion (line 318) | func (d *Dict) incVersion() {
method DelItem (line 328) | func (d *Dict) DelItem(f *Frame, key *Object) (bool, *BaseException) {
method DelItemString (line 338) | func (d *Dict) DelItemString(f *Frame, key string) (bool, *BaseExcepti...
method GetItem (line 344) | func (d *Dict) GetItem(f *Frame, key *Object) (*Object, *BaseException) {
method GetItemString (line 361) | func (d *Dict) GetItemString(f *Frame, key string) (*Object, *BaseExce...
method Pop (line 367) | func (d *Dict) Pop(f *Frame, key *Object) (*Object, *BaseException) {
method Keys (line 372) | func (d *Dict) Keys(f *Frame) *List {
method Len (line 387) | func (d *Dict) Len() int {
method putItem (line 393) | func (d *Dict) putItem(f *Frame, key, value *Object, overwrite bool) (...
method SetItem (line 437) | func (d *Dict) SetItem(f *Frame, key, value *Object) *BaseException {
method SetItemString (line 443) | func (d *Dict) SetItemString(f *Frame, key string, value *Object) *Bas...
method ToObject (line 448) | func (d *Dict) ToObject() *Object {
method Update (line 453) | func (d *Dict) Update(f *Frame, o *Object) (raised *BaseException) {
function NewDict (line 276) | func NewDict() *Dict {
function newStringDict (line 280) | func newStringDict(items map[string]*Object) *Dict {
function toDictUnsafe (line 292) | func toDictUnsafe(o *Object) *Dict {
function dictsAreEqual (line 482) | func dictsAreEqual(f *Frame, d1, d2 *Dict) (bool, *BaseException) {
function dictClear (line 522) | func dictClear(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
function dictContains (line 534) | func dictContains(f *Frame, seq, value *Object) (*Object, *BaseException) {
function dictCopy (line 542) | func dictCopy(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
function dictDelItem (line 549) | func dictDelItem(f *Frame, o, key *Object) *BaseException {
function dictEq (line 560) | func dictEq(f *Frame, v, w *Object) (*Object, *BaseException) {
function dictGet (line 571) | func dictGet(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseExceptio...
function dictHasKey (line 590) | func dictHasKey(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
function dictItems (line 597) | func dictItems(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseExcept...
function dictIterItems (line 608) | func dictIterItems(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseEx...
function dictIterKeys (line 619) | func dictIterKeys(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseExc...
function dictIterValues (line 626) | func dictIterValues(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseE...
function dictKeys (line 637) | func dictKeys(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseExcepti...
function dictGetItem (line 644) | func dictGetItem(f *Frame, o, key *Object) (*Object, *BaseException) {
function dictInit (line 655) | func dictInit(f *Frame, o *Object, args Args, kwargs KWArgs) (*Object, *...
function dictIter (line 678) | func dictIter(f *Frame, o *Object) (*Object, *BaseException) {
function dictLen (line 686) | func dictLen(f *Frame, o *Object) (*Object, *BaseException) {
function dictNE (line 692) | func dictNE(f *Frame, v, w *Object) (*Object, *BaseException) {
function dictNew (line 703) | func dictNew(f *Frame, t *Type, _ Args, _ KWArgs) (*Object, *BaseExcepti...
function dictPop (line 709) | func dictPop(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
function dictPopItem (line 731) | func dictPopItem(f *Frame, args Args, _ KWArgs) (item *Object, raised *B...
function dictRepr (line 751) | func dictRepr(f *Frame, o *Object) (*Object, *BaseException) {
function dictSetDefault (line 785) | func dictSetDefault(f *Frame, args Args, _ KWArgs) (*Object, *BaseExcept...
function dictSetItem (line 815) | func dictSetItem(f *Frame, o, key, value *Object) *BaseException {
function dictUpdate (line 819) | func dictUpdate(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseExcep...
function dictValues (line 842) | func dictValues(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseExcep...
function initDictType (line 853) | func initDictType(dict map[string]*Object) {
type dictItemIterator (line 882) | type dictItemIterator struct
method ToObject (line 902) | func (iter *dictItemIterator) ToObject() *Object {
function newDictItemIterator (line 890) | func newDictItemIterator(d *Dict) *dictItemIterator {
function toDictItemIteratorUnsafe (line 898) | func toDictItemIteratorUnsafe(o *Object) *dictItemIterator {
function dictItemIteratorIter (line 906) | func dictItemIteratorIter(f *Frame, o *Object) (*Object, *BaseException) {
function dictItemIteratorNext (line 910) | func dictItemIteratorNext(f *Frame, o *Object) (ret *Object, raised *Bas...
function initDictItemIteratorType (line 919) | func initDictItemIteratorType(map[string]*Object) {
type dictKeyIterator (line 925) | type dictKeyIterator struct
method ToObject (line 945) | func (iter *dictKeyIterator) ToObject() *Object {
function newDictKeyIterator (line 933) | func newDictKeyIterator(d *Dict) *dictKeyIterator {
function toDictKeyIteratorUnsafe (line 941) | func toDictKeyIteratorUnsafe(o *Object) *dictKeyIterator {
function dictKeyIteratorIter (line 949) | func dictKeyIteratorIter(f *Frame, o *Object) (*Object, *BaseException) {
function dictKeyIteratorNext (line 953) | func dictKeyIteratorNext(f *Frame, o *Object) (*Object, *BaseException) {
function initDictKeyIteratorType (line 962) | func initDictKeyIteratorType(map[string]*Object) {
type dictValueIterator (line 968) | type dictValueIterator struct
method ToObject (line 988) | func (iter *dictValueIterator) ToObject() *Object {
function newDictValueIterator (line 976) | func newDictValueIterator(d *Dict) *dictValueIterator {
function toDictValueIteratorUnsafe (line 984) | func toDictValueIteratorUnsafe(o *Object) *dictValueIterator {
function dictValueIteratorIter (line 992) | func dictValueIteratorIter(f *Frame, o *Object) (*Object, *BaseException) {
function dictValueIteratorNext (line 996) | func dictValueIteratorNext(f *Frame, o *Object) (*Object, *BaseException) {
function initDictValueIteratorType (line 1005) | func initDictValueIteratorType(map[string]*Object) {
function raiseKeyError (line 1011) | func raiseKeyError(f *Frame, key *Object) *BaseException {
function dictNextIndex (line 1019) | func dictNextIndex(i, perturb uint) (uint, uint) {
function dictIteratorNext (line 1023) | func dictIteratorNext(f *Frame, iter *dictEntryIterator, guard *dictVers...
FILE: runtime/dict_test.go
function TestNewStringDict (line 31) | func TestNewStringDict(t *testing.T) {
function TestDictClear (line 50) | func TestDictClear(t *testing.T) {
function TestDictContains (line 73) | func TestDictContains(t *testing.T) {
function TestDictDelItem (line 86) | func TestDictDelItem(t *testing.T) {
function TestDictDelItemString (line 112) | func TestDictDelItemString(t *testing.T) {
function TestDictEqNE (line 134) | func TestDictEqNE(t *testing.T) {
function TestDictGet (line 185) | func TestDictGet(t *testing.T) {
function TestDictGetItem (line 198) | func TestDictGetItem(t *testing.T) {
function BenchmarkDictGetItem (line 238) | func BenchmarkDictGetItem(b *testing.B) {
function BenchmarkDictIterItems (line 259) | func BenchmarkDictIterItems(b *testing.B) {
function BenchmarkDictIterKeys (line 298) | func BenchmarkDictIterKeys(b *testing.B) {
function BenchmarkDictIterValues (line 337) | func BenchmarkDictIterValues(b *testing.B) {
function TestDictGetItemString (line 376) | func TestDictGetItemString(t *testing.T) {
function TestDictHasKey (line 400) | func TestDictHasKey(t *testing.T) {
function TestDictItemIteratorIter (line 413) | func TestDictItemIteratorIter(t *testing.T) {
function TestDictItemIterModified (line 421) | func TestDictItemIterModified(t *testing.T) {
function TestDictIter (line 438) | func TestDictIter(t *testing.T) {
function TestDictIterKeys (line 465) | func TestDictIterKeys(t *testing.T) {
function TestDictIterValues (line 486) | func TestDictIterValues(t *testing.T) {
function TestDictItems (line 508) | func TestDictItems(t *testing.T) {
function TestDictKeyIteratorIter (line 539) | func TestDictKeyIteratorIter(t *testing.T) {
function TestDictKeyIterModified (line 547) | func TestDictKeyIterModified(t *testing.T) {
function TestDictKeys (line 563) | func TestDictKeys(t *testing.T) {
function TestDictPop (line 575) | func TestDictPop(t *testing.T) {
function TestDictPopItem (line 588) | func TestDictPopItem(t *testing.T) {
function TestDictNewInit (line 619) | func TestDictNewInit(t *testing.T) {
function TestDictNewRaises (line 636) | func TestDictNewRaises(t *testing.T) {
function TestDictSetDefault (line 649) | func TestDictSetDefault(t *testing.T) {
function TestDictSetItem (line 673) | func TestDictSetItem(t *testing.T) {
function TestDictSetItemString (line 716) | func TestDictSetItemString(t *testing.T) {
function TestDictStrRepr (line 741) | func TestDictStrRepr(t *testing.T) {
function TestDictUpdate (line 782) | func TestDictUpdate(t *testing.T) {
function TestDictValues (line 816) | func TestDictValues(t *testing.T) {
function TestParallelDictUpdates (line 829) | func TestParallelDictUpdates(t *testing.T) {
function newTestDict (line 905) | func newTestDict(elems ...interface{}) *Dict {
FILE: runtime/exceptions.go
function systemExitInit (line 106) | func systemExitInit(f *Frame, o *Object, args Args, kwargs KWArgs) (*Obj...
function initSystemExitType (line 118) | func initSystemExitType(map[string]*Object) {
FILE: runtime/file.go
type File (line 30) | type File struct
method name (line 66) | func (f *File) name() string {
method ToObject (line 75) | func (f *File) ToObject() *Object {
method readLine (line 79) | func (f *File) readLine(maxBytes int) (string, error) {
method writeString (line 110) | func (f *File) writeString(s string) error {
function NewFileFromFD (line 47) | func NewFileFromFD(fd uintptr, close *Object) *File {
function toFileUnsafe (line 62) | func toFileUnsafe(o *Object) *File {
function fileInit (line 126) | func fileInit(f *Frame, o *Object, args Args, _ KWArgs) (*Object, *BaseE...
function fileEnter (line 173) | func fileEnter(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
function fileExit (line 180) | func fileExit(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
function fileClose (line 195) | func fileClose(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
function fileClosed (line 220) | func fileClosed(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
function fileFileno (line 231) | func fileFileno(f *Frame, args Args, _ KWArgs) (ret *Object, raised *Bas...
function fileGetName (line 246) | func fileGetName(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
function fileIter (line 257) | func fileIter(f *Frame, o *Object) (*Object, *BaseException) {
function fileNext (line 261) | func fileNext(f *Frame, o *Object) (ret *Object, raised *BaseException) {
function fileRead (line 278) | func fileRead(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
function fileReadLine (line 304) | func fileReadLine(f *Frame, args Args, _ KWArgs) (*Object, *BaseExceptio...
function fileReadLines (line 321) | func fileReadLines(f *Frame, args Args, _ KWArgs) (*Object, *BaseExcepti...
function fileRepr (line 352) | func fileRepr(f *Frame, o *Object) (*Object, *BaseException) {
function fileWrite (line 371) | func fileWrite(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
function initFileType (line 387) | func initFileType(dict map[string]*Object) {
function fileParseReadArgs (line 405) | func fileParseReadArgs(f *Frame, method string, args Args) (*File, int, ...
FILE: runtime/file_test.go
function TestFileInit (line 30) | func TestFileInit(t *testing.T) {
function TestFileClosed (line 46) | func TestFileClosed(t *testing.T) {
function TestFileCloseExit (line 65) | func TestFileCloseExit(t *testing.T) {
function TestFileGetName (line 86) | func TestFileGetName(t *testing.T) {
function TestFileIter (line 103) | func TestFileIter(t *testing.T) {
function TestFileNext (line 130) | func TestFileNext(t *testing.T) {
function TestFileRead (line 158) | func TestFileRead(t *testing.T) {
function TestFileReadLine (line 181) | func TestFileReadLine(t *testing.T) {
function TestFileReadLines (line 224) | func TestFileReadLines(t *testing.T) {
function TestFileStrRepr (line 267) | func TestFileStrRepr(t *testing.T) {
function TestFileWrite (line 305) | func TestFileWrite(t *testing.T) {
type testFile (line 369) | type testFile struct
method cleanup (line 388) | func (f *testFile) cleanup() {
method open (line 395) | func (f *testFile) open(mode string) *File {
function newTestFile (line 374) | func newTestFile(contents string) *testFile {
type testFileSlice (line 406) | type testFileSlice
method cleanup (line 419) | func (files testFileSlice) cleanup() {
function makeTestFiles (line 408) | func makeTestFiles() testFileSlice {
FILE: runtime/float.go
type Float (line 33) | type Float struct
method ToObject (line 49) | func (f *Float) ToObject() *Object {
method Value (line 54) | func (f *Float) Value() float64 {
function NewFloat (line 40) | func NewFloat(value float64) *Float {
function toFloatUnsafe (line 44) | func toFloatUnsafe(o *Object) *Float {
function floatAbs (line 58) | func floatAbs(f *Frame, o *Object) (*Object, *BaseException) {
function floatAdd (line 63) | func floatAdd(f *Frame, v, w *Object) (*Object, *BaseException) {
function floatDiv (line 67) | func floatDiv(f *Frame, v, w *Object) (*Object, *BaseException) {
function floatDivMod (line 76) | func floatDivMod(f *Frame, v, w *Object) (*Object, *BaseException) {
function floatEq (line 86) | func floatEq(f *Frame, v, w *Object) (*Object, *BaseException) {
function floatFloat (line 90) | func floatFloat(f *Frame, o *Object) (*Object, *BaseException) {
function floatFloorDiv (line 94) | func floatFloorDiv(f *Frame, v, w *Object) (*Object, *BaseException) {
function floatGE (line 103) | func floatGE(f *Frame, v, w *Object) (*Object, *BaseException) {
function floatGetNewArgs (line 107) | func floatGetNewArgs(f *Frame, args Args, _ KWArgs) (*Object, *BaseExcep...
function floatGT (line 114) | func floatGT(f *Frame, v, w *Object) (*Object, *BaseException) {
function floatHash (line 118) | func floatHash(f *Frame, o *Object) (*Object, *BaseException) {
function floatInt (line 134) | func floatInt(f *Frame, o *Object) (*Object, *BaseException) {
function floatLong (line 150) | func floatLong(f *Frame, o *Object) (*Object, *BaseException) {
function floatLE (line 162) | func floatLE(f *Frame, v, w *Object) (*Object, *BaseException) {
function floatLT (line 166) | func floatLT(f *Frame, v, w *Object) (*Object, *BaseException) {
function floatMod (line 170) | func floatMod(f *Frame, v, w *Object) (*Object, *BaseException) {
function floatMul (line 174) | func floatMul(f *Frame, v, w *Object) (*Object, *BaseException) {
function floatNative (line 178) | func floatNative(f *Frame, o *Object) (reflect.Value, *BaseException) {
function floatNE (line 182) | func floatNE(f *Frame, v, w *Object) (*Object, *BaseException) {
function floatNeg (line 186) | func floatNeg(f *Frame, o *Object) (*Object, *BaseException) {
function floatNew (line 191) | func floatNew(f *Frame, t *Type, args Args, _ KWArgs) (*Object, *BaseExc...
function floatNonZero (line 229) | func floatNonZero(f *Frame, o *Object) (*Object, *BaseException) {
function floatPos (line 233) | func floatPos(f *Frame, o *Object) (*Object, *BaseException) {
function floatPow (line 237) | func floatPow(f *Frame, v, w *Object) (*Object, *BaseException) {
function floatRAdd (line 241) | func floatRAdd(f *Frame, v, w *Object) (*Object, *BaseException) {
function floatRDiv (line 245) | func floatRDiv(f *Frame, v, w *Object) (*Object, *BaseException) {
function floatRDivMod (line 254) | func floatRDivMod(f *Frame, v, w *Object) (*Object, *BaseException) {
constant floatReprPrecision (line 265) | floatReprPrecision = 16
constant floatStrPrecision (line 266) | floatStrPrecision = 12
function floatRepr (line 269) | func floatRepr(f *Frame, o *Object) (*Object, *BaseException) {
function floatRFloorDiv (line 273) | func floatRFloorDiv(f *Frame, v, w *Object) (*Object, *BaseException) {
function floatRMod (line 282) | func floatRMod(f *Frame, v, w *Object) (*Object, *BaseException) {
function floatRMul (line 288) | func floatRMul(f *Frame, v, w *Object) (*Object, *BaseException) {
function floatRPow (line 292) | func floatRPow(f *Frame, v, w *Object) (*Object, *BaseException) {
function floatRSub (line 296) | func floatRSub(f *Frame, v, w *Object) (*Object, *BaseException) {
function floatStr (line 300) | func floatStr(f *Frame, o *Object) (*Object, *BaseException) {
function floatSub (line 304) | func floatSub(f *Frame, v, w *Object) (*Object, *BaseException) {
function initFloatType (line 308) | func initFloatType(dict map[string]*Object) {
function floatArithmeticOp (line 346) | func floatArithmeticOp(f *Frame, method string, v, w *Object, fun func(v...
function floatCompare (line 357) | func floatCompare(v *Float, w *Object, ltResult, eqResult, gtResult *Int...
function floatCoerce (line 395) | func floatCoerce(o *Object) (float64, bool) {
function floatConvert (line 413) | func floatConvert(floatSlot *unaryOpSlot, f *Frame, o *Object) (*Float, ...
function floatDivModOp (line 425) | func floatDivModOp(f *Frame, method string, v, w *Object, fun func(v, w ...
function floatDivAndModOp (line 440) | func floatDivAndModOp(f *Frame, method string, v, w *Object, fun func(v,...
function hashFloat (line 455) | func hashFloat(v float64) int {
function floatModFunc (line 489) | func floatModFunc(v, w float64) (float64, bool) {
function floatToString (line 506) | func floatToString(f float64, p int) string {
function unsignPositiveInf (line 517) | func unsignPositiveInf(s string) string {
FILE: runtime/float_test.go
function TestFloatArithmeticOps (line 38) | func TestFloatArithmeticOps(t *testing.T) {
function TestFloatDivMod (line 114) | func TestFloatDivMod(t *testing.T) {
function isNaNTupleFloat (line 143) | func isNaNTupleFloat(got, want *Object) bool {
function TestFloatCompare (line 156) | func TestFloatCompare(t *testing.T) {
function TestFloatInt (line 176) | func TestFloatInt(t *testing.T) {
function TestFloatLong (line 191) | func TestFloatLong(t *testing.T) {
function TestFloatHash (line 206) | func TestFloatHash(t *testing.T) {
function TestFloatIsTrue (line 222) | func TestFloatIsTrue(t *testing.T) {
function TestFloatNew (line 235) | func TestFloatNew(t *testing.T) {
function TestFloatRepr (line 301) | func TestFloatRepr(t *testing.T) {
function TestFloatStr (line 323) | func TestFloatStr(t *testing.T) {
FILE: runtime/frame.go
type RunState (line 23) | type RunState
constant notBaseExceptionMsg (line 26) | notBaseExceptionMsg = "exceptions must be derived from BaseException, no...
type Frame (line 30) | type Frame struct
method release (line 68) | func (f *Frame) release() {
method pushFrame (line 82) | func (f *Frame) pushFrame(back *Frame) {
method Globals (line 96) | func (f *Frame) Globals() *Dict {
method ToObject (line 101) | func (f *Frame) ToObject() *Object {
method SetLineno (line 106) | func (f *Frame) SetLineno(lineno int) {
method State (line 111) | func (f *Frame) State() RunState {
method PushCheckpoint (line 116) | func (f *Frame) PushCheckpoint(state RunState) {
method PopCheckpoint (line 122) | func (f *Frame) PopCheckpoint() {
method Raise (line 139) | func (f *Frame) Raise(typ *Object, inst *Object, tb *Object) *BaseExce...
method RaiseType (line 200) | func (f *Frame) RaiseType(t *Type, msg string) *BaseException {
method ExcInfo (line 206) | func (f *Frame) ExcInfo() (*BaseException, *Traceback) {
method RestoreExc (line 212) | func (f *Frame) RestoreExc(e *BaseException, tb *Traceback) (*BaseExce...
method reprEnter (line 218) | func (f *Frame) reprEnter(o *Object) bool {
method reprLeave (line 229) | func (f *Frame) reprLeave(o *Object) {
method MakeArgs (line 235) | func (f *Frame) MakeArgs(n int) Args {
method FreeArgs (line 254) | func (f *Frame) FreeArgs(args Args) {
function NewRootFrame (line 46) | func NewRootFrame() *Frame {
function newChildFrame (line 53) | func newChildFrame(back *Frame) *Frame {
function toFrameUnsafe (line 91) | func toFrameUnsafe(o *Object) *Frame {
function frameExcClear (line 273) | func frameExcClear(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseEx...
function frameExcInfo (line 281) | func frameExcInfo(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseExc...
function initFrameType (line 296) | func initFrameType(dict map[string]*Object) {
FILE: runtime/frame_test.go
constant testRunStateInvalid (line 24) | testRunStateInvalid RunState = -1
constant testRunStateStart (line 25) | testRunStateStart = 0
constant testRunStateDone (line 26) | testRunStateDone = 1
function TestFrameArgsCache (line 29) | func TestFrameArgsCache(t *testing.T) {
function TestFramePopCheckpoint (line 65) | func TestFramePopCheckpoint(t *testing.T) {
function TestFramePushCheckpoint (line 91) | func TestFramePushCheckpoint(t *testing.T) {
function TestFrameRaise (line 104) | func TestFrameRaise(t *testing.T) {
function TestFrameRaiseType (line 155) | func TestFrameRaiseType(t *testing.T) {
function TestReprEnterLeave (line 174) | func TestReprEnterLeave(t *testing.T) {
function TestFrameRoot (line 198) | func TestFrameRoot(t *testing.T) {
function TestFrameExcInfo (line 209) | func TestFrameExcInfo(t *testing.T) {
type checkInvokeResultType (line 225) | type checkInvokeResultType
constant checkInvokeResultOk (line 228) | checkInvokeResultOk checkInvokeResultType = iota
constant checkInvokeResultExceptionMismatch (line 229) | checkInvokeResultExceptionMismatch = iota
constant checkInvokeResultReturnValueMismatch (line 230) | checkInvokeResultReturnValueMismatch = iota
function checkResult (line 233) | func checkResult(got, want *Object, gotExc, wantExc *BaseException) chec...
function checkInvokeResult (line 263) | func checkInvokeResult(callable *Object, args Args, wantRet *Object, wan...
function checkInvokeResultKwargs (line 267) | func checkInvokeResultKwargs(callable *Object, args Args, kwargs KWArgs,...
type invokeTestCase (line 282) | type invokeTestCase struct
function runInvokeTestCase (line 289) | func runInvokeTestCase(callable *Object, cas *invokeTestCase) string {
function runInvokeMethodTestCase (line 311) | func runInvokeMethodTestCase(t *Type, methodName string, cas *invokeTest...
FILE: runtime/function.go
type Args (line 34) | type Args
method makeCopy (line 36) | func (a Args) makeCopy() Args {
type KWArg (line 43) | type KWArg struct
type KWArgs (line 50) | type KWArgs
method String (line 53) | func (k KWArgs) String() string {
method get (line 57) | func (k KWArgs) get(name string, def *Object) *Object {
method makeDict (line 66) | func (k KWArgs) makeDict() *Dict {
type Func (line 75) | type Func
type Function (line 78) | type Function struct
method ToObject (line 106) | func (f *Function) ToObject() *Object {
method Name (line 111) | func (f *Function) Name() string {
function NewFunction (line 91) | func NewFunction(c *Code, globals *Dict) *Function {
function newBuiltinFunction (line 97) | func newBuiltinFunction(name string, fn Func) *Function {
function toFunctionUnsafe (line 101) | func toFunctionUnsafe(o *Object) *Function {
function functionCall (line 115) | func functionCall(f *Frame, callable *Object, args Args, kwargs KWArgs) ...
function functionGet (line 124) | func functionGet(f *Frame, desc, instance *Object, owner *Type) (*Object...
function functionRepr (line 134) | func functionRepr(_ *Frame, o *Object) (*Object, *BaseException) {
function initFunctionType (line 139) | func initFunctionType(map[string]*Object) {
type staticMethod (line 147) | type staticMethod struct
method ToObject (line 161) | func (m *staticMethod) ToObject() *Object {
function newStaticMethod (line 152) | func newStaticMethod(callable *Object) *staticMethod {
function toStaticMethodUnsafe (line 156) | func toStaticMethodUnsafe(o *Object) *staticMethod {
function staticMethodGet (line 165) | func staticMethodGet(f *Frame, desc, _ *Object, _ *Type) (*Object, *Base...
function staticMethodInit (line 173) | func staticMethodInit(f *Frame, o *Object, args Args, _ KWArgs) (*Object...
function initStaticMethodType (line 181) | func initStaticMethodType(map[string]*Object) {
type classMethod (line 187) | type classMethod struct
method ToObject (line 201) | func (m *classMethod) ToObject() *Object {
function newClassMethod (line 192) | func newClassMethod(callable *Object) *classMethod {
function toClassMethodUnsafe (line 196) | func toClassMethodUnsafe(o *Object) *classMethod {
function classMethodGet (line 205) | func classMethodGet(f *Frame, desc, _ *Object, owner *Type) (*Object, *B...
function classMethodInit (line 219) | func classMethodInit(f *Frame, o *Object, args Args, _ KWArgs) (*Object,...
function initClassMethodType (line 227) | func initClassMethodType(map[string]*Object) {
FILE: runtime/function_test.go
function TestFunctionCall (line 22) | func TestFunctionCall(t *testing.T) {
function TestFunctionGet (line 42) | func TestFunctionGet(t *testing.T) {
function TestFunctionName (line 49) | func TestFunctionName(t *testing.T) {
function TestFunctionStrRepr (line 59) | func TestFunctionStrRepr(t *testing.T) {
function TestStaticMethodGet (line 93) | func TestStaticMethodGet(t *testing.T) {
function TestStaticMethodInit (line 105) | func TestStaticMethodInit(t *testing.T) {
function TestClassMethodGet (line 128) | func TestClassMethodGet(t *testing.T) {
function TestClassMethodInit (line 155) | func TestClassMethodInit(t *testing.T) {
FILE: runtime/generator.go
type generatorState (line 27) | type generatorState
constant generatorStateCreated (line 30) | generatorStateCreated generatorState = iota
constant generatorStateReady (line 31) | generatorStateReady
constant generatorStateRunning (line 32) | generatorStateRunning
constant generatorStateDone (line 33) | generatorStateDone
type Generator (line 37) | type Generator struct
method resume (line 60) | func (g *Generator) resume(f *Frame, sendValue *Object) (*Object, *Bas...
method ToObject (line 102) | func (g *Generator) ToObject() *Object {
function NewGenerator (line 46) | func NewGenerator(f *Frame, fn func(*Object) (*Object, *BaseException)) ...
function toGeneratorUnsafe (line 56) | func toGeneratorUnsafe(o *Object) *Generator {
function generatorIter (line 106) | func generatorIter(f *Frame, o *Object) (*Object, *BaseException) {
function generatorNext (line 110) | func generatorNext(f *Frame, o *Object) (*Object, *BaseException) {
function generatorSend (line 114) | func generatorSend(f *Frame, args Args, _ KWArgs) (*Object, *BaseExcepti...
function initGeneratorType (line 121) | func initGeneratorType(dict map[string]*Object) {
FILE: runtime/generator_test.go
function TestGeneratorNext (line 21) | func TestGeneratorNext(t *testing.T) {
function TestGeneratorSend (line 48) | func TestGeneratorSend(t *testing.T) {
function TestGeneratorSimple (line 63) | func TestGeneratorSimple(t *testing.T) {
FILE: runtime/int.go
constant internedIntMin (line 26) | internedIntMin = -2
constant internedIntMax (line 27) | internedIntMax = 300
type Int (line 35) | type Int struct
method ToObject (line 53) | func (i *Int) ToObject() *Object {
method Value (line 58) | func (i *Int) Value() int {
method IsTrue (line 63) | func (i *Int) IsTrue() bool {
function NewInt (line 41) | func NewInt(value int) *Int {
function toIntUnsafe (line 48) | func toIntUnsafe(o *Object) *Int {
function intAbs (line 70) | func intAbs(f *Frame, o *Object) (*Object, *BaseException) {
function intAdd (line 78) | func intAdd(f *Frame, v, w *Object) (*Object, *BaseException) {
function intAnd (line 82) | func intAnd(f *Frame, v, w *Object) (*Object, *BaseException) {
function intDiv (line 89) | func intDiv(f *Frame, v, w *Object) (*Object, *BaseException) {
function intDivMod (line 93) | func intDivMod(f *Frame, v, w *Object) (*Object, *BaseException) {
function intEq (line 97) | func intEq(f *Frame, v, w *Object) (*Object, *BaseException) {
function intGE (line 101) | func intGE(f *Frame, v, w *Object) (*Object, *BaseException) {
function intGetNewArgs (line 105) | func intGetNewArgs(f *Frame, args Args, _ KWArgs) (*Object, *BaseExcepti...
function intGT (line 112) | func intGT(f *Frame, v, w *Object) (*Object, *BaseException) {
function intFloat (line 116) | func intFloat(f *Frame, o *Object) (*Object, *BaseException) {
function intHash (line 121) | func intHash(f *Frame, o *Object) (*Object, *BaseException) {
function intHex (line 125) | func intHex(f *Frame, o *Object) (*Object, *BaseException) {
function intIndex (line 130) | func intIndex(f *Frame, o *Object) (*Object, *BaseException) {
function intInt (line 134) | func intInt(f *Frame, o *Object) (*Object, *BaseException) {
function intInvert (line 141) | func intInvert(f *Frame, o *Object) (*Object, *BaseException) {
function intLE (line 145) | func intLE(f *Frame, v, w *Object) (*Object, *BaseException) {
function intLong (line 149) | func intLong(f *Frame, o *Object) (*Object, *BaseException) {
function intLShift (line 153) | func intLShift(f *Frame, v, w *Object) (*Object, *BaseException) {
function intLT (line 157) | func intLT(f *Frame, v, w *Object) (*Object, *BaseException) {
function intMod (line 161) | func intMod(f *Frame, v, w *Object) (*Object, *BaseException) {
function intMul (line 165) | func intMul(f *Frame, v, w *Object) (*Object, *BaseException) {
function intNative (line 169) | func intNative(f *Frame, o *Object) (reflect.Value, *BaseException) {
function intNE (line 173) | func intNE(f *Frame, v, w *Object) (*Object, *BaseException) {
function intNeg (line 177) | func intNeg(f *Frame, o *Object) (*Object, *BaseException) {
function intNew (line 186) | func intNew(f *Frame, t *Type, args Args, _ KWArgs) (*Object, *BaseExcep...
function intNonZero (line 252) | func intNonZero(f *Frame, o *Object) (*Object, *BaseException) {
function intOct (line 256) | func intOct(f *Frame, o *Object) (*Object, *BaseException) {
function intOr (line 264) | func intOr(f *Frame, v, w *Object) (*Object, *BaseException) {
function intPos (line 271) | func intPos(f *Frame, o *Object) (*Object, *BaseException) {
function intPow (line 275) | func intPow(f *Frame, v, w *Object) (*Object, *BaseException) {
function intRAdd (line 312) | func intRAdd(f *Frame, v, w *Object) (*Object, *BaseException) {
function intRDiv (line 316) | func intRDiv(f *Frame, v, w *Object) (*Object, *BaseException) {
function intRDivMod (line 324) | func intRDivMod(f *Frame, v, w *Object) (*Object, *BaseException) {
function intRepr (line 332) | func intRepr(f *Frame, o *Object) (*Object, *BaseException) {
function intRMod (line 336) | func intRMod(f *Frame, v, w *Object) (*Object, *BaseException) {
function intRMul (line 344) | func intRMul(f *Frame, v, w *Object) (*Object, *BaseException) {
function intRLShift (line 348) | func intRLShift(f *Frame, v, w *Object) (*Object, *BaseException) {
function intRRShift (line 352) | func intRRShift(f *Frame, v, w *Object) (*Object, *BaseException) {
function intRShift (line 356) | func intRShift(f *Frame, v, w *Object) (*Object, *BaseException) {
function intRSub (line 360) | func intRSub(f *Frame, v, w *Object) (*Object, *BaseException) {
function intSub (line 368) | func intSub(f *Frame, v, w *Object) (*Object, *BaseException) {
function intXor (line 372) | func intXor(f *Frame, v, w *Object) (*Object, *BaseException) {
function initIntType (line 379) | func initIntType(dict map[string]*Object) {
type divModResult (line 429) | type divModResult
constant divModOK (line 432) | divModOK divModResult = iota
constant divModOverflow (line 433) | divModOverflow = iota
constant divModZeroDivision (line 434) | divModZeroDivision = iota
function intCompare (line 437) | func intCompare(op compareOp, v *Int, w *Object) *Object {
function intAddMulOp (line 460) | func intAddMulOp(f *Frame, method string, v, w *Object, fun func(v, w in...
function intCheckedDiv (line 471) | func intCheckedDiv(v, w int) (int, divModResult) {
function intCheckedDivMod (line 476) | func intCheckedDivMod(v, w int) (int, int, divModResult) {
function intCheckedAdd (line 502) | func intCheckedAdd(v, w int) (int, bool) {
function intCheckedMod (line 509) | func intCheckedMod(v, w int) (int, divModResult) {
function intCheckedMul (line 514) | func intCheckedMul(v, w int) (int, bool) {
function intCheckedSub (line 534) | func intCheckedSub(v, w int) (int, bool) {
function intDivModOp (line 541) | func intDivModOp(f *Frame, method string, v, w *Object, fun func(v, w in...
function intDivAndModOp (line 555) | func intDivAndModOp(f *Frame, method string, v, w *Object, fun func(v, w...
function intShiftOp (line 569) | func intShiftOp(f *Frame, v, w *Object, fun func(int, int) (int, int, bo...
function intToLong (line 590) | func intToLong(o *Int) *Long {
function makeInternedInts (line 594) | func makeInternedInts() [internedIntMax - internedIntMin + 1]Int {
FILE: runtime/int_test.go
function TestIntBinaryOps (line 23) | func TestIntBinaryOps(t *testing.T) {
function TestIntCompare (line 99) | func TestIntCompare(t *testing.T) {
function TestIntInvert (line 113) | func TestIntInvert(t *testing.T) {
function TestIntNew (line 128) | func TestIntNew(t *testing.T) {
function TestIntNewInterned (line 195) | func TestIntNewInterned(t *testing.T) {
function BenchmarkIntNew (line 217) | func BenchmarkIntNew(b *testing.B) {
function TestIntStrRepr (line 235) | func TestIntStrRepr(t *testing.T) {
function TestIntCheckedAddMul (line 251) | func TestIntCheckedAddMul(t *testing.T) {
function TestIntCheckedDivMod (line 279) | func TestIntCheckedDivMod(t *testing.T) {
function TestIntCheckedSub (line 326) | func TestIntCheckedSub(t *testing.T) {
FILE: runtime/list.go
type List (line 29) | type List struct
method ToObject (line 51) | func (l *List) ToObject() *Object {
method Append (line 56) | func (l *List) Append(o *Object) {
method DelItem (line 65) | func (l *List) DelItem(f *Frame, index int) *BaseException {
method DelSlice (line 78) | func (l *List) DelSlice(f *Frame, s *Slice) *BaseException {
method SetItem (line 105) | func (l *List) SetItem(f *Frame, index int, value *Object) *BaseExcept...
method SetSlice (line 117) | func (l *List) SetSlice(f *Frame, s *Slice, value *Object) *BaseExcept...
method Sort (line 147) | func (l *List) Sort(f *Frame) (raised *BaseException) {
method resize (line 167) | func (l *List) resize(newLen int) {
function NewList (line 36) | func NewList(elems ...*Object) *List {
function toListUnsafe (line 46) | func toListUnsafe(o *Object) *List {
function listAdd (line 184) | func listAdd(f *Frame, v, w *Object) (ret *Object, raised *BaseException) {
function listAppend (line 200) | func listAppend(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseExcep...
function listCount (line 208) | func listCount(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseExcept...
function listDelItem (line 215) | func listDelItem(f *Frame, o *Object, key *Object) *BaseException {
function listRemove (line 231) | func listRemove(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseExcep...
function listExtend (line 253) | func listExtend(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
function listContains (line 261) | func listContains(f *Frame, l, v *Object) (*Object, *BaseException) {
function listEq (line 265) | func listEq(f *Frame, v, w *Object) (*Object, *BaseException) {
function listGE (line 269) | func listGE(f *Frame, v, w *Object) (*Object, *BaseException) {
function listGetItem (line 273) | func listGetItem(f *Frame, o, key *Object) (*Object, *BaseException) {
function listGT (line 290) | func listGT(f *Frame, v, w *Object) (*Object, *BaseException) {
function listIAdd (line 294) | func listIAdd(f *Frame, v, w *Object) (*Object, *BaseException) {
function listIMul (line 306) | func listIMul(f *Frame, v, w *Object) (*Object, *BaseException) {
function listInsert (line 323) | func listInsert(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseExcep...
function listIter (line 341) | func listIter(f *Frame, o *Object) (*Object, *BaseException) {
function listLE (line 345) | func listLE(f *Frame, v, w *Object) (*Object, *BaseException) {
function listLen (line 349) | func listLen(f *Frame, o *Object) (*Object, *BaseException) {
function listNew (line 357) | func listNew(f *Frame, t *Type, args Args, _ KWArgs) (*Object, *BaseExce...
function listLT (line 367) | func listLT(f *Frame, v, w *Object) (*Object, *BaseException) {
function listMul (line 371) | func listMul(f *Frame, v, w *Object) (*Object, *BaseException) {
function listNE (line 385) | func listNE(f *Frame, v, w *Object) (*Object, *BaseException) {
function listIndex (line 389) | func listIndex(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
function listPop (line 433) | func listPop(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
function listRepr (line 468) | func listRepr(f *Frame, o *Object) (*Object, *BaseException) {
function listReverse (line 483) | func listReverse(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
function listSetItem (line 498) | func listSetItem(f *Frame, o, key, value *Object) *BaseException {
function listSort (line 513) | func listSort(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
function initListType (line 523) | func initListType(dict map[string]*Object) {
type listIterator (line 555) | type listIterator struct
function newListIterator (line 562) | func newListIterator(l *List) *Object {
function toListIteratorUnsafe (line 567) | func toListIteratorUnsafe(o *Object) *listIterator {
function listIteratorIter (line 573) | func listIteratorIter(f *Frame, o *Object) (*Object, *BaseException) {
function listIteratorNext (line 577) | func listIteratorNext(f *Frame, o *Object) (ret *Object, raised *BaseExc...
function initListIteratorType (line 596) | func initListIteratorType(map[string]*Object) {
function listCompare (line 602) | func listCompare(f *Frame, v *List, w *Object, cmp binaryOpFunc) (*Objec...
type listSorter (line 616) | type listSorter struct
method Len (line 622) | func (s *listSorter) Len() int {
method Less (line 626) | func (s *listSorter) Less(i, j int) bool {
method Swap (line 640) | func (s *listSorter) Swap(i, j int) {
FILE: runtime/list_test.go
function TestNewList (line 23) | func TestNewList(t *testing.T) {
function TestListBinaryOps (line 37) | func TestListBinaryOps(t *testing.T) {
function TestListCompare (line 65) | func TestListCompare(t *testing.T) {
function TestListCount (line 82) | func TestListCount(t *testing.T) {
function TestListDelItem (line 95) | func TestListDelItem(t *testing.T) {
function TestListIndex (line 133) | func TestListIndex(t *testing.T) {
function TestListRemove (line 165) | func TestListRemove(t *testing.T) {
function BenchmarkListContains (line 189) | func BenchmarkListContains(b *testing.B) {
function TestListGetItem (line 241) | func TestListGetItem(t *testing.T) {
function TestListInplaceOps (line 263) | func TestListInplaceOps(t *testing.T) {
function TestListIsTrue (line 291) | func TestListIsTrue(t *testing.T) {
function TestListAppend (line 303) | func TestListAppend(t *testing.T) {
function TestListExtend (line 330) | func TestListExtend(t *testing.T) {
function TestListLen (line 361) | func TestListLen(t *testing.T) {
function TestListNew (line 373) | func TestListNew(t *testing.T) {
function TestListReverse (line 387) | func TestListReverse(t *testing.T) {
function TestListStrRepr (line 408) | func TestListStrRepr(t *testing.T) {
function TestListInsert (line 427) | func TestListInsert(t *testing.T) {
function TestListIter (line 454) | func TestListIter(t *testing.T) {
function TestListIteratorIter (line 486) | func TestListIteratorIter(t *testing.T) {
function TestListPop (line 494) | func TestListPop(t *testing.T) {
function TestListSetItem (line 523) | func TestListSetItem(t *testing.T) {
function TestListSort (line 561) | func TestListSort(t *testing.T) {
function newTestRange (line 585) | func newTestRange(n int) *List {
function newTestList (line 593) | func newTestList(elems ...interface{}) *List {
FILE: runtime/long.go
type Long (line 37) | type Long struct
method IntValue (line 65) | func (l *Long) IntValue(f *Frame) (int, *BaseException) {
method ToObject (line 73) | func (l *Long) ToObject() *Object {
method Value (line 78) | func (l *Long) Value() *big.Int {
method IsTrue (line 83) | func (l *Long) IsTrue() bool {
method Neg (line 88) | func (l *Long) Neg() *Long {
function NewLong (line 45) | func NewLong(x *big.Int) *Long {
function NewLongFromBytes (line 53) | func NewLongFromBytes(b []byte) *Long {
function toLongUnsafe (line 59) | func toLongUnsafe(o *Object) *Long {
function longAbs (line 98) | func longAbs(z, x *big.Int) {
function longAdd (line 102) | func longAdd(z, x, y *big.Int) {
function longAnd (line 106) | func longAnd(z, x, y *big.Int) {
function longDiv (line 110) | func longDiv(z, x, y *big.Int) {
function longDivAndMod (line 115) | func longDivAndMod(z, m, x, y *big.Int) {
function longEq (line 119) | func longEq(x, y *big.Int) bool {
function longGE (line 123) | func longGE(x, y *big.Int) bool {
function longGetNewArgs (line 127) | func longGetNewArgs(f *Frame, args Args, _ KWArgs) (*Object, *BaseExcept...
function longGT (line 134) | func longGT(x, y *big.Int) bool {
function longFloat (line 138) | func longFloat(f *Frame, o *Object) (*Object, *BaseException) {
function hashBigInt (line 146) | func hashBigInt(x *big.Int) int {
function longHex (line 151) | func longHex(f *Frame, o *Object) (*Object, *BaseException) {
function longHash (line 156) | func longHash(f *Frame, o *Object) (*Object, *BaseException) {
function longIndex (line 168) | func longIndex(_ *Frame, o *Object) (*Object, *BaseException) {
function longInt (line 172) | func longInt(f *Frame, o *Object) (*Object, *BaseException) {
function longInvert (line 179) | func longInvert(z, x *big.Int) {
function longLE (line 183) | func longLE(x, y *big.Int) bool {
function longLShift (line 187) | func longLShift(z, x *big.Int, n uint) {
function longLong (line 191) | func longLong(f *Frame, o *Object) (*Object, *BaseException) {
function longLT (line 200) | func longLT(x, y *big.Int) bool {
function longMul (line 204) | func longMul(z, x, y *big.Int) {
function longMod (line 208) | func longMod(m, x, y *big.Int) {
function longNative (line 213) | func longNative(f *Frame, o *Object) (reflect.Value, *BaseException) {
function longNE (line 217) | func longNE(x, y *big.Int) bool {
function longNeg (line 221) | func longNeg(z, x *big.Int) {
function longNew (line 225) | func longNew(f *Frame, t *Type, args Args, _ KWArgs) (*Object, *BaseExce...
function longNonZero (line 298) | func longNonZero(x *big.Int) bool {
function longOct (line 302) | func longOct(f *Frame, o *Object) (*Object, *BaseException) {
function longOr (line 310) | func longOr(z, x, y *big.Int) {
function longPos (line 314) | func longPos(z, x *big.Int) {
function longRepr (line 318) | func longRepr(f *Frame, o *Object) (*Object, *BaseException) {
function longRShift (line 322) | func longRShift(z, x *big.Int, n uint) {
function longStr (line 326) | func longStr(f *Frame, o *Object) (*Object, *BaseException) {
function longSub (line 330) | func longSub(z, x, y *big.Int) {
function longXor (line 334) | func longXor(z, x, y *big.Int) {
function initLongType (line 338) | func initLongType(dict map[string]*Object) {
function longCallUnary (line 392) | func longCallUnary(fun func(z, x *big.Int), v *Long) *Object {
function longCallUnaryBool (line 398) | func longCallUnaryBool(fun func(x *big.Int) bool, v *Long) *Object {
function longCallBinary (line 402) | func longCallBinary(fun func(z, x, y *big.Int), v, w *Long) *Object {
function longCallBinaryTuple (line 408) | func longCallBinaryTuple(fun func(z, m, x, y *big.Int), v, w *Long) *Obj...
function longCallBinaryBool (line 415) | func longCallBinaryBool(fun func(x, y *big.Int) bool, v, w *Long) *Object {
function longCallShift (line 419) | func longCallShift(fun func(z, x *big.Int, n uint), f *Frame, v, w *Long...
function longCallDivMod (line 431) | func longCallDivMod(fun func(z, x, y *big.Int), f *Frame, v, w *Long) (*...
function longCallDivAndMod (line 438) | func longCallDivAndMod(fun func(z, m, x, y *big.Int), f *Frame, v, w *Lo...
function longUnaryOpSlot (line 445) | func longUnaryOpSlot(fun func(z, x *big.Int)) *unaryOpSlot {
function longUnaryBoolOpSlot (line 452) | func longUnaryBoolOpSlot(fun func(x *big.Int) bool) *unaryOpSlot {
function longBinaryOpSlot (line 459) | func longBinaryOpSlot(fun func(z, x, y *big.Int)) *binaryOpSlot {
function longRBinaryOpSlot (line 471) | func longRBinaryOpSlot(fun func(z, x, y *big.Int)) *binaryOpSlot {
function longDivModOpSlot (line 483) | func longDivModOpSlot(fun func(z, x, y *big.Int)) *binaryOpSlot {
function longRDivModOpSlot (line 495) | func longRDivModOpSlot(fun func(z, x, y *big.Int)) *binaryOpSlot {
function longDivAndModOpSlot (line 507) | func longDivAndModOpSlot(fun func(z, m, x, y *big.Int)) *binaryOpSlot {
function longRDivAndModOpSlot (line 519) | func longRDivAndModOpSlot(fun func(z, m, x, y *big.Int)) *binaryOpSlot {
function longShiftOpSlot (line 531) | func longShiftOpSlot(fun func(z, x *big.Int, n uint)) *binaryOpSlot {
function longRShiftOpSlot (line 543) | func longRShiftOpSlot(fun func(z, x *big.Int, n uint)) *binaryOpSlot {
function longBinaryBoolOpSlot (line 555) | func longBinaryBoolOpSlot(fun func(x, y *big.Int) bool) *binaryOpSlot {
function longRBinaryBoolOpSlot (line 567) | func longRBinaryBoolOpSlot(fun func(x, y *big.Int) bool) *binaryOpSlot {
function longPow (line 579) | func longPow(f *Frame, v, w *Object) (*Object, *BaseException) {
function longRPow (line 618) | func longRPow(f *Frame, v, w *Object) (*Object, *BaseException) {
function longDivMod (line 629) | func longDivMod(x, y, z, m *big.Int) {
FILE: runtime/long_test.go
function TestLongBasis (line 13) | func TestLongBasis(t *testing.T) {
function TestNewLongFromBytes (line 21) | func TestNewLongFromBytes(t *testing.T) {
function TestLongReprStr (line 39) | func TestLongReprStr(t *testing.T) {
function TestLongNew (line 64) | func TestLongNew(t *testing.T) {
function TestLongBinaryOps (line 117) | func TestLongBinaryOps(t *testing.T) {
function TestLongCompare (line 221) | func TestLongCompare(t *testing.T) {
function TestLongInvert (line 255) | func TestLongInvert(t *testing.T) {
function TestLongInt (line 275) | func TestLongInt(t *testing.T) {
function TestLongFloat (line 294) | func TestLongFloat(t *testing.T) {
FILE: runtime/method.go
type Method (line 23) | type Method struct
method ToObject (line 36) | func (m *Method) ToObject() *Object {
function toMethodUnsafe (line 31) | func toMethodUnsafe(o *Object) *Method {
function methodCall (line 43) | func methodCall(f *Frame, callable *Object, args Args, kwargs KWArgs) (*...
function methodGet (line 81) | func methodGet(f *Frame, desc, instance *Object, owner *Type) (*Object, ...
function methodNew (line 100) | func methodNew(f *Frame, t *Type, args Args, _ KWArgs) (*Object, *BaseEx...
function methodRepr (line 130) | func methodRepr(f *Frame, o *Object) (*Object, *BaseException) {
function initMethodType (line 153) | func initMethodType(map[string]*Object) {
function methodGetMemberName (line 161) | func methodGetMemberName(f *Frame, o *Object) (string, *BaseException) {
FILE: runtime/method_test.go
function TestMethodCall (line 21) | func TestMethodCall(t *testing.T) {
function TestMethodGet (line 46) | func TestMethodGet(t *testing.T) {
function TestMethodNew (line 79) | func TestMethodNew(t *testing.T) {
function TestMethodStrRepr (line 92) | func TestMethodStrRepr(t *testing.T) {
function newTestMethod (line 110) | func newTestMethod(function, self, class *Object) *Method {
FILE: runtime/module.go
type moduleState (line 26) | type moduleState
constant moduleStateNew (line 29) | moduleStateNew moduleState = iota
constant moduleStateInitializing (line 30) | moduleStateInitializing
constant moduleStateReady (line 31) | moduleStateReady
type Module (line 44) | type Module struct
method GetFilename (line 197) | func (m *Module) GetFilename(f *Frame) (*Str, *BaseException) {
method GetName (line 210) | func (m *Module) GetName(f *Frame) (*Str, *BaseException) {
method ToObject (line 222) | func (m *Module) ToObject() *Object {
type ModuleInit (line 53) | type ModuleInit
function RegisterModule (line 57) | func RegisterModule(name string, c *Code) {
function ImportModule (line 89) | func ImportModule(f *Frame, name string) ([]*Object, *BaseException) {
function importOne (line 118) | func importOne(f *Frame, name string) (*Object, *BaseException) {
function newModule (line 183) | func newModule(name, filename string) *Module {
function toModuleUnsafe (line 191) | func toModuleUnsafe(o *Object) *Module {
function moduleInit (line 226) | func moduleInit(f *Frame, o *Object, args Args, _ KWArgs) (*Object, *Bas...
function moduleRepr (line 246) | func moduleRepr(f *Frame, o *Object) (*Object, *BaseException) {
function initModuleType (line 265) | func initModuleType(map[string]*Object) {
function RunMain (line 276) | func RunMain(code *Code) int {
FILE: runtime/module_test.go
function TestImportModule (line 23) | func TestImportModule(t *testing.T) {
function TestModuleGetNameAndFilename (line 188) | func TestModuleGetNameAndFilename(t *testing.T) {
function TestModuleInit (line 212) | func TestModuleInit(t *testing.T) {
function TestModuleStrRepr (line 241) | func TestModuleStrRepr(t *testing.T) {
function TestRunMain (line 258) | func TestRunMain(t *testing.T) {
function runMainAndCaptureStderr (line 290) | func runMainAndCaptureStderr(code *Code) (int, string, error) {
function init (line 315) | func init() {
function newTestModule (line 363) | func newTestModule(name, filename string) *Module {
FILE: runtime/native.go
type nativeMetaclass (line 61) | type nativeMetaclass struct
function toNativeMetaclassUnsafe (line 66) | func toNativeMetaclassUnsafe(o *Object) *nativeMetaclass {
function newNativeType (line 70) | func newNativeType(rtype reflect.Type, base *Type) *Type {
function nativeTypedefNative (line 87) | func nativeTypedefNative(f *Frame, o *Object) (reflect.Value, *BaseExcep...
function nativeMetaclassNew (line 100) | func nativeMetaclassNew(f *Frame, args Args, kwargs KWArgs) (*Object, *B...
function initNativeMetaclassType (line 107) | func initNativeMetaclassType(dict map[string]*Object) {
type nativeBoolMetaclass (line 112) | type nativeBoolMetaclass struct
function toNativeBoolMetaclassUnsafe (line 118) | func toNativeBoolMetaclassUnsafe(o *Object) *nativeBoolMetaclass {
function newNativeBoolType (line 122) | func newNativeBoolType(rtype reflect.Type) *Type {
function nativeBoolNative (line 142) | func nativeBoolNative(f *Frame, o *Object) (reflect.Value, *BaseExceptio...
function nativeBoolNew (line 147) | func nativeBoolNew(f *Frame, t *Type, args Args, kwargs KWArgs) (*Object...
function initNativeBoolMetaclassType (line 166) | func initNativeBoolMetaclassType(dict map[string]*Object) {
type native (line 171) | type native struct
method ToObject (line 181) | func (n *native) ToObject() *Object {
function toNativeUnsafe (line 176) | func toNativeUnsafe(o *Object) *native {
function nativeNative (line 185) | func nativeNative(f *Frame, o *Object) (reflect.Value, *BaseException) {
function initNativeType (line 189) | func initNativeType(map[string]*Object) {
function nativeFuncCall (line 194) | func nativeFuncCall(f *Frame, callable *Object, args Args, kwargs KWArgs...
function nativeFuncGetName (line 198) | func nativeFuncGetName(f *Frame, args Args, _ KWArgs) (*Object, *BaseExc...
function nativeFuncRepr (line 206) | func nativeFuncRepr(f *Frame, o *Object) (*Object, *BaseException) {
function initNativeFuncType (line 219) | func initNativeFuncType(dict map[string]*Object) {
function nativeSliceGetItem (line 225) | func nativeSliceGetItem(f *Frame, o, key *Object) (*Object, *BaseExcepti...
function nativeSliceIter (line 255) | func nativeSliceIter(f *Frame, o *Object) (*Object, *BaseException) {
function nativeSliceLen (line 259) | func nativeSliceLen(f *Frame, o *Object) (*Object, *BaseException) {
function nativeSliceRepr (line 263) | func nativeSliceRepr(f *Frame, o *Object) (*Object, *BaseException) {
function nativeSliceSetItem (line 286) | func nativeSliceSetItem(f *Frame, o, key, value *Object) *BaseException {
function initNativeSliceType (line 334) | func initNativeSliceType(map[string]*Object) {
function nativeSliceGetIndex (line 342) | func nativeSliceGetIndex(f *Frame, slice reflect.Value, key *Object) (re...
type sliceIterator (line 354) | type sliceIterator struct
function newSliceIterator (line 362) | func newSliceIterator(slice reflect.Value) *Object {
function toSliceIteratorUnsafe (line 367) | func toSliceIteratorUnsafe(o *Object) *sliceIterator {
function sliceIteratorIter (line 371) | func sliceIteratorIter(f *Frame, o *Object) (*Object, *BaseException) {
function sliceIteratorNext (line 375) | func sliceIteratorNext(f *Frame, o *Object) (ret *Object, raised *BaseEx...
function initSliceIteratorType (line 388) | func initSliceIteratorType(map[string]*Object) {
function WrapNative (line 408) | func WrapNative(f *Frame, v reflect.Value) (*Object, *BaseException) {
function getNativeType (line 512) | func getNativeType(rtype reflect.Type) *Type {
function newNativeField (line 569) | func newNativeField(name string, i int, t *Type) *Object {
function newNativeMethod (line 603) | func newNativeMethod(name string, fun reflect.Value) *Object {
function maybeConvertValue (line 609) | func maybeConvertValue(f *Frame, o *Object, expectedRType reflect.Type) ...
function nativeFuncTypeName (line 647) | func nativeFuncTypeName(rtype reflect.Type) string {
function nativeInvoke (line 675) | func nativeInvoke(f *Frame, fun reflect.Value, args Args) (ret *Object, ...
function nativeTypeName (line 738) | func nativeTypeName(rtype reflect.Type) string {
FILE: runtime/native_test.go
function TestNativeMetaclassNew (line 26) | func TestNativeMetaclassNew(t *testing.T) {
function TestNativeFuncCall (line 60) | func TestNativeFuncCall(t *testing.T) {
function TestNativeFuncName (line 81) | func TestNativeFuncName(t *testing.T) {
function TestNativeFuncStrRepr (line 112) | func TestNativeFuncStrRepr(t *testing.T) {
function TestNativeNew (line 146) | func TestNativeNew(t *testing.T) {
function TestNativeSliceIter (line 179) | func TestNativeSliceIter(t *testing.T) {
function TestSliceIteratorIter (line 200) | func TestSliceIteratorIter(t *testing.T) {
function TestWrapNative (line 208) | func TestWrapNative(t *testing.T) {
function TestWrapNativeFunc (line 249) | func TestWrapNativeFunc(t *testing.T) {
function TestWrapNativeInterface (line 257) | func TestWrapNativeInterface(t *testing.T) {
function TestWrapNativeOpaque (line 279) | func TestWrapNativeOpaque(t *testing.T) {
function TestGetNativeTypeCaches (line 302) | func TestGetNativeTypeCaches(t *testing.T) {
function TestGetNativeTypeFunc (line 310) | func TestGetNativeTypeFunc(t *testing.T) {
type testNativeType (line 318) | type testNativeType struct
method Int64 (line 322) | func (n *testNativeType) Int64() int64 {
function TestGetNativeTypeMethods (line 326) | func TestGetNativeTypeMethods(t *testing.T) {
function TestGetNativeTypeSlice (line 343) | func TestGetNativeTypeSlice(t *testing.T) {
function TestGetNativeTypeTypedefs (line 351) | func TestGetNativeTypeTypedefs(t *testing.T) {
function TestGetNativeTypeBigInts (line 372) | func TestGetNativeTypeBigInts(t *testing.T) {
function TestMaybeConvertValue (line 387) | func TestMaybeConvertValue(t *testing.T) {
function TestNativeTypedefNative (line 426) | func TestNativeTypedefNative(t *testing.T) {
function TestNativeTypeName (line 449) | func TestNativeTypeName(t *testing.T) {
function TestNewNativeFieldChecksInstanceType (line 473) | func TestNewNativeFieldChecksInstanceType(t *testing.T) {
function TestNativeSliceGetItem (line 500) | func TestNativeSliceGetItem(t *testing.T) {
function TestNativeSliceGetItemSlice (line 524) | func TestNativeSliceGetItemSlice(t *testing.T) {
function TestNativeSliceLen (line 559) | func TestNativeSliceLen(t *testing.T) {
function TestNativeSliceStrRepr (line 571) | func TestNativeSliceStrRepr(t *testing.T) {
function TestNativeSliceSetItemSlice (line 591) | func TestNativeSliceSetItemSlice(t *testing.T) {
function TestNativeStructFieldGet (line 632) | func TestNativeStructFieldGet(t *testing.T) {
function TestNativeStructFieldSet (line 652) | func TestNativeStructFieldSet(t *testing.T) {
function wrapArgs (line 676) | func wrapArgs(elems ...interface{}) Args {
function wrapKWArgs (line 689) | func wrapKWArgs(elems ...interface{}) KWArgs {
FILE: runtime/numeric.go
constant _maxuint (line 25) | _maxuint = 1<<(^uint(0)/0xff%15*8) - 1
constant MaxInt (line 28) | MaxInt = _maxuint >> 1
constant MinInt (line 31) | MinInt = -(_maxuint + 1) >> 1
function numParseInteger (line 39) | func numParseInteger(z *big.Int, s string, base int) (*big.Int, bool) {
function numInIntRange (line 68) | func numInIntRange(i *big.Int) bool {
FILE: runtime/object.go
type Object (line 41) | type Object struct
method Call (line 60) | func (o *Object) Call(f *Frame, args Args, kwargs KWArgs) (*Object, *B...
method Dict (line 69) | func (o *Object) Dict() *Dict {
method setDict (line 74) | func (o *Object) setDict(d *Dict) {
method String (line 80) | func (o *Object) String() string {
method Type (line 92) | func (o *Object) Type() *Type {
method toPointer (line 96) | func (o *Object) toPointer() unsafe.Pointer {
method isInstance (line 100) | func (o *Object) isInstance(t *Type) bool {
function newObject (line 47) | func newObject(t *Type) *Object {
function objectBasisFunc (line 104) | func objectBasisFunc(o *Object) reflect.Value {
function objectDelAttr (line 108) | func objectDelAttr(f *Frame, o *Object, name *Str) *BaseException {
function objectGetAttribute (line 135) | func objectGetAttribute(f *Frame, o *Object, name *Str) (*Object, *BaseE...
function objectHash (line 167) | func objectHash(f *Frame, o *Object) (*Object, *BaseException) {
function objectNew (line 171) | func objectNew(f *Frame, t *Type, _ Args, _ KWArgs) (*Object, *BaseExcep...
function objectReduce (line 179) | func objectReduce(f *Frame, args Args, _ KWArgs) (*Object, *BaseExceptio...
function objectReduceEx (line 191) | func objectReduceEx(f *Frame, args Args, _ KWArgs) (*Object, *BaseExcept...
function objectSetAttr (line 211) | func objectSetAttr(f *Frame, o *Object, name *Str, value *Object) *BaseE...
function initObjectType (line 227) | func initObjectType(dict map[string]*Object) {
function objectReconstructor (line 242) | func objectReconstructor(f *Frame, args Args, _ KWArgs) (*Object, *BaseE...
function objectReduceCommon (line 269) | func objectReduceCommon(f *Frame, args Args) (*Object, *BaseException) {
function objectGetDict (line 347) | func objectGetDict(f *Frame, args Args, _ KWArgs) (*Object, *BaseExcepti...
function objectSetDict (line 360) | func objectSetDict(f *Frame, args Args, _ KWArgs) (*Object, *BaseExcepti...
FILE: runtime/object_test.go
function TestObjectCall (line 24) | func TestObjectCall(t *testing.T) {
function TestNewObject (line 65) | func TestNewObject(t *testing.T) {
function TestObjectString (line 74) | func TestObjectString(t *testing.T) {
function TestObjectDelAttr (line 99) | func TestObjectDelAttr(t *testing.T) {
function TestObjectGetAttribute (line 145) | func TestObjectGetAttribute(t *testing.T) {
function TestObjectGetDict (line 208) | func TestObjectGetDict(t *testing.T) {
function TestObjectSetDict (line 229) | func TestObjectSetDict(t *testing.T) {
function TestObjectNew (line 254) | func TestObjectNew(t *testing.T) {
function TestObjectReduce (line 272) | func TestObjectReduce(t *testing.T) {
function TestObjectSetAttr (line 375) | func TestObjectSetAttr(t *testing.T) {
function TestObjectStrRepr (line 415) | func TestObjectStrRepr(t *testing.T) {
FILE: runtime/param.go
type Param (line 22) | type Param struct
type ParamSpec (line 31) | type ParamSpec struct
method Validate (line 71) | func (s *ParamSpec) Validate(f *Frame, validated []*Object, args Args,...
function NewParamSpec (line 42) | func NewParamSpec(name string, params []Param, varArg bool, kwArg bool) ...
FILE: runtime/param_test.go
function TestParamSpecValidate (line 21) | func TestParamSpecValidate(t *testing.T) {
FILE: runtime/range.go
type enumerate (line 32) | type enumerate struct
function toEnumerateUnsafe (line 39) | func toEnumerateUnsafe(o *Object) *enumerate {
function enumerateIter (line 43) | func enumerateIter(f *Frame, o *Object) (*Object, *BaseException) {
function enumerateNew (line 47) | func enumerateNew(f *Frame, t *Type, args Args, _ KWArgs) (*Object, *Bas...
function enumerateNext (line 94) | func enumerateNext(f *Frame, o *Object) (ret *Object, raised *BaseExcept...
function initEnumerateType (line 114) | func initEnumerateType(map[string]*Object) {
type rangeIterator (line 121) | type rangeIterator struct
function toRangeIteratorUnsafe (line 128) | func toRangeIteratorUnsafe(o *Object) *rangeIterator {
function rangeIteratorIter (line 132) | func rangeIteratorIter(f *Frame, o *Object) (*Object, *BaseException) {
function rangeIteratorNext (line 136) | func rangeIteratorNext(f *Frame, o *Object) (*Object, *BaseException) {
function initRangeIteratorType (line 146) | func initRangeIteratorType(map[string]*Object) {
type xrange (line 152) | type xrange struct
function toXRangeUnsafe (line 159) | func toXRangeUnsafe(o *Object) *xrange {
function xrangeGetItem (line 163) | func xrangeGetItem(f *Frame, o, key *Object) (*Object, *BaseException) {
function xrangeIter (line 180) | func xrangeIter(f *Frame, o *Object) (*Object, *BaseException) {
function xrangeLen (line 185) | func xrangeLen(f *Frame, o *Object) (*Object, *BaseException) {
function xrangeNew (line 190) | func xrangeNew(f *Frame, _ *Type, args Args, _ KWArgs) (*Object, *BaseEx...
function xrangeRepr (line 220) | func xrangeRepr(_ *Frame, o *Object) (*Object, *BaseException) {
function initXRangeType (line 233) | func initXRangeType(map[string]*Object) {
FILE: runtime/range_test.go
function TestEnumerate (line 21) | func TestEnumerate(t *testing.T) {
function TestRangeIteratorIter (line 46) | func TestRangeIteratorIter(t *testing.T) {
function TestXRangeGetItem (line 73) | func TestXRangeGetItem(t *testing.T) {
function TestXRangeLen (line 88) | func TestXRangeLen(t *testing.T) {
function TestXRangeNew (line 102) | func TestXRangeNew(t *testing.T) {
function TestXRangeRepr (line 131) | func TestXRangeRepr(t *testing.T) {
function newTestXRange (line 162) | func newTestXRange(args ...interface{}) *Object {
FILE: runtime/seq.go
function seqAdd (line 30) | func seqAdd(f *Frame, elems1, elems2 []*Object) ([]*Object, *BaseExcepti...
function seqCompare (line 38) | func seqCompare(f *Frame, elems1, elems2 []*Object, cmp binaryOpFunc) (*...
function seqApply (line 65) | func seqApply(f *Frame, seq *Object, fun func([]*Object, bool) *BaseExce...
function seqCheckedIndex (line 90) | func seqCheckedIndex(f *Frame, seqLen, index int) (int, *BaseException) {
function seqClampIndex (line 100) | func seqClampIndex(i, seqLen int) int {
function seqContains (line 113) | func seqContains(f *Frame, iterable *Object, v *Object) (*Object, *BaseE...
function seqCount (line 132) | func seqCount(f *Frame, iterable *Object, v *Object) (*Object, *BaseExce...
function seqFindFirst (line 154) | func seqFindFirst(f *Frame, iterable *Object, pred func(*Object) (bool, ...
function seqFindElem (line 176) | func seqFindElem(f *Frame, elems []*Object, o *Object) (int, *BaseExcept...
function seqForEach (line 193) | func seqForEach(f *Frame, iterable *Object, callback func(*Object) *Base...
function seqGetItem (line 214) | func seqGetItem(f *Frame, elems []*Object, index *Object) (*Object, []*O...
function seqMul (line 243) | func seqMul(f *Frame, elems []*Object, n int) ([]*Object, *BaseException) {
function seqNew (line 259) | func seqNew(f *Frame, args Args) ([]*Object, *BaseException) {
type seqRangeResult (line 282) | type seqRangeResult
constant seqRangeOK (line 285) | seqRangeOK seqRangeResult = iota
constant seqRangeOverflow (line 286) | seqRangeOverflow
constant seqRangeZeroStep (line 287) | seqRangeZeroStep
function seqRange (line 300) | func seqRange(start, stop, step int) (int, int, seqRangeResult) {
function seqRepr (line 321) | func seqRepr(f *Frame, elems []*Object) (string, *BaseException) {
function seqWrapEach (line 337) | func seqWrapEach(f *Frame, elems ...interface{}) ([]*Object, *BaseExcept...
type seqIterator (line 348) | type seqIterator struct
function newSeqIterator (line 355) | func newSeqIterator(seq *Object) *Object {
function toSeqIteratorUnsafe (line 360) | func toSeqIteratorUnsafe(o *Object) *seqIterator {
function seqIteratorIter (line 364) | func seqIteratorIter(f *Frame, o *Object) (*Object, *BaseException) {
function seqIteratorNext (line 368) | func seqIteratorNext(f *Frame, o *Object) (item *Object, raised *BaseExc...
function initSeqIteratorType (line 383) | func initSeqIteratorType(map[string]*Object) {
FILE: runtime/seq_test.go
function TestSeqApply (line 21) | func TestSeqApply(t *testing.T) {
function TestSeqCount (line 46) | func TestSeqCount(t *testing.T) {
function TestSeqForEach (line 78) | func TestSeqForEach(t *testing.T) {
function TestSeqIterator (line 102) | func TestSeqIterator(t *testing.T) {
function TestSeqNew (line 120) | func TestSeqNew(t *testing.T) {
FILE: runtime/set.go
type setBase (line 29) | type setBase struct
method contains (line 34) | func (s *setBase) contains(f *Frame, key *Object) (bool, *BaseExceptio...
method isSubset (line 42) | func (s *setBase) isSubset(f *Frame, o *Object) (*Object, *BaseExcepti...
method isSuperset (line 50) | func (s *setBase) isSuperset(f *Frame, o *Object) (*Object, *BaseExcep...
method repr (line 58) | func (s *setBase) repr(f *Frame) (*Object, *BaseException) {
type Set (line 71) | type Set
method Add (line 83) | func (s *Set) Add(f *Frame, key *Object) (bool, *BaseException) {
method Contains (line 92) | func (s *Set) Contains(f *Frame, key *Object) (bool, *BaseException) {
method Remove (line 97) | func (s *Set) Remove(f *Frame, key *Object) (bool, *BaseException) {
method ToObject (line 102) | func (s *Set) ToObject() *Object {
method Update (line 107) | func (s *Set) Update(f *Frame, o *Object) *BaseException {
function NewSet (line 74) | func NewSet() *Set {
function toSetUnsafe (line 78) | func toSetUnsafe(o *Object) *Set {
function setAdd (line 114) | func setAdd(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
function setContains (line 124) | func setContains(f *Frame, seq, value *Object) (*Object, *BaseException) {
function setDiscard (line 132) | func setDiscard(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
function setEq (line 142) | func setEq(f *Frame, v, w *Object) (*Object, *BaseException) {
function setGE (line 146) | func setGE(f *Frame, v, w *Object) (*Object, *BaseException) {
function setGT (line 150) | func setGT(f *Frame, v, w *Object) (*Object, *BaseException) {
function setInit (line 154) | func setInit(f *Frame, o *Object, args Args, _ KWArgs) (*Object, *BaseEx...
function setIsSubset (line 168) | func setIsSubset(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
function setIsSuperset (line 175) | func setIsSuperset(f *Frame, args Args, _ KWArgs) (*Object, *BaseExcepti...
function setIter (line 182) | func setIter(f *Frame, o *Object) (*Object, *BaseException) {
function setLE (line 190) | func setLE(f *Frame, v, w *Object) (*Object, *BaseException) {
function setLen (line 194) | func setLen(f *Frame, o *Object) (*Object, *BaseException) {
function setLT (line 198) | func setLT(f *Frame, v, w *Object) (*Object, *BaseException) {
function setNE (line 202) | func setNE(f *Frame, v, w *Object) (*Object, *BaseException) {
function setNew (line 206) | func setNew(f *Frame, t *Type, _ Args, _ KWArgs) (*Object, *BaseExceptio...
function setRemove (line 212) | func setRemove(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
function setRepr (line 225) | func setRepr(f *Frame, o *Object) (*Object, *BaseException) {
function setUpdate (line 229) | func setUpdate(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
function initSetType (line 239) | func initSetType(dict map[string]*Object) {
type FrozenSet (line 262) | type FrozenSet
method Contains (line 269) | func (s *FrozenSet) Contains(f *Frame, key *Object) (bool, *BaseExcept...
method ToObject (line 274) | func (s *FrozenSet) ToObject() *Object {
function toFrozenSetUnsafe (line 264) | func toFrozenSetUnsafe(o *Object) *FrozenSet {
function frozenSetContains (line 278) | func frozenSetContains(f *Frame, seq, value *Object) (*Object, *BaseExce...
function frozenSetEq (line 286) | func frozenSetEq(f *Frame, v, w *Object) (*Object, *BaseException) {
function frozenSetGE (line 290) | func frozenSetGE(f *Frame, v, w *Object) (*Object, *BaseException) {
function frozenSetGT (line 294) | func frozenSetGT(f *Frame, v, w *Object) (*Object, *BaseException) {
function frozenSetIsSubset (line 298) | func frozenSetIsSubset(f *Frame, args Args, _ KWArgs) (*Object, *BaseExc...
function frozenSetIsSuperset (line 305) | func frozenSetIsSuperset(f *Frame, args Args, _ KWArgs) (*Object, *BaseE...
function frozenSetIter (line 312) | func frozenSetIter(f *Frame, o *Object) (*Object, *BaseException) {
function frozenSetLE (line 320) | func frozenSetLE(f *Frame, v, w *Object) (*Object, *BaseException) {
function frozenSetLen (line 324) | func frozenSetLen(f *Frame, o *Object) (*Object, *BaseException) {
function frozenSetLT (line 328) | func frozenSetLT(f *Frame, v, w *Object) (*Object, *BaseException) {
function frozenSetNE (line 332) | func frozenSetNE(f *Frame, v, w *Object) (*Object, *BaseException) {
function frozenSetNew (line 336) | func frozenSetNew(f *Frame, t *Type, args Args, _ KWArgs) (*Object, *Bas...
function frozenSetRepr (line 355) | func frozenSetRepr(f *Frame, o *Object) (*Object, *BaseException) {
function initFrozenSetType (line 359) | func initFrozenSetType(dict map[string]*Object) {
function setCompare (line 377) | func setCompare(f *Frame, op compareOp, v *setBase, w *Object) (*Object,...
function setFromSeq (line 431) | func setFromSeq(f *Frame, seq *Object) (*setBase, *BaseException) {
FILE: runtime/set_test.go
function TestSetAdd (line 22) | func TestSetAdd(t *testing.T) {
function TestSetContains (line 46) | func TestSetContains(t *testing.T) {
function TestSetDiscard (line 63) | func TestSetDiscard(t *testing.T) {
function TestSetCompare (line 87) | func TestSetCompare(t *testing.T) {
function TestSetIsSubset (line 117) | func TestSetIsSubset(t *testing.T) {
function TestSetIsSuperset (line 138) | func TestSetIsSuperset(t *testing.T) {
function TestSetIsTrue (line 157) | func TestSetIsTrue(t *testing.T) {
function TestSetIter (line 172) | func TestSetIter(t *testing.T) {
function TestSetLen (line 199) | func TestSetLen(t *testing.T) {
function TestSetNewInit (line 214) | func TestSetNewInit(t *testing.T) {
function TestSetRemove (line 232) | func TestSetRemove(t *testing.T) {
function TestSetStrRepr (line 257) | func TestSetStrRepr(t *testing.T) {
function TestSetUpdate (line 276) | func TestSetUpdate(t *testing.T) {
function newTestSet (line 302) | func newTestSet(elems ...interface{}) *Set {
function newTestFrozenSet (line 317) | func newTestFrozenSet(elems ...interface{}) *FrozenSet {
FILE: runtime/slice.go
constant errBadSliceIndex (line 19) | errBadSliceIndex = "slice indices must be integers or None or have an __...
type Slice (line 27) | type Slice struct
method calcSlice (line 43) | func (s *Slice) calcSlice(f *Frame, numElems int) (int, int, int, int,...
method ToObject (line 80) | func (s *Slice) ToObject() *Object {
function toSliceUnsafe (line 34) | func toSliceUnsafe(o *Object) *Slice {
function sliceEq (line 84) | func sliceEq(f *Frame, v, w *Object) (*Object, *BaseException) {
function sliceGE (line 88) | func sliceGE(f *Frame, v, w *Object) (*Object, *BaseException) {
function sliceGT (line 92) | func sliceGT(f *Frame, v, w *Object) (*Object, *BaseException) {
function sliceLE (line 96) | func sliceLE(f *Frame, v, w *Object) (*Object, *BaseException) {
function sliceLT (line 100) | func sliceLT(f *Frame, v, w *Object) (*Object, *BaseException) {
function sliceNE (line 104) | func sliceNE(f *Frame, v, w *Object) (*Object, *BaseException) {
function sliceNew (line 108) | func sliceNew(f *Frame, t *Type, args Args, _ KWArgs) (*Object, *BaseExc...
function sliceRepr (line 130) | func sliceRepr(f *Frame, o *Object) (*Object, *BaseException) {
function initSliceType (line 146) | func initSliceType(map[string]*Object) {
function sliceClampIndex (line 159) | func sliceClampIndex(f *Frame, index *Object, def, seqLen int) (int, *Ba...
function sliceCompare (line 173) | func sliceCompare(f *Frame, v *Slice, w *Object, cmp binaryOpFunc) (*Obj...
FILE: runtime/slice_test.go
function TestSliceCalcSize (line 21) | func TestSliceCalcSize(t *testing.T) {
function TestSliceCompare (line 46) | func TestSliceCompare(t *testing.T) {
function TestSliceNew (line 61) | func TestSliceNew(t *testing.T) {
function TestSliceStrRepr (line 76) | func TestSliceStrRepr(t *testing.T) {
function newTestSlice (line 92) | func newTestSlice(args ...interface{}) *Object {
FILE: runtime/slots.go
type slot (line 29) | type slot interface
type basisSlot (line 40) | type basisSlot struct
method makeCallable (line 44) | func (s *basisSlot) makeCallable(t *Type, slotName string) *Object {
method wrapCallable (line 48) | func (s *basisSlot) wrapCallable(callable *Object) bool {
type binaryOpFunc (line 52) | type binaryOpFunc
type binaryOpSlot (line 54) | type binaryOpSlot struct
method makeCallable (line 58) | func (s *binaryOpSlot) makeCallable(t *Type, slotName string) *Object {
method wrapCallable (line 67) | func (s *binaryOpSlot) wrapCallable(callable *Object) bool {
type callSlot (line 74) | type callSlot struct
method makeCallable (line 78) | func (s *callSlot) makeCallable(t *Type, _ string) *Object {
method wrapCallable (line 87) | func (s *callSlot) wrapCallable(callable *Object) bool {
type delAttrSlot (line 97) | type delAttrSlot struct
method makeCallable (line 101) | func (s *delAttrSlot) makeCallable(t *Type, slotName string) *Object {
method wrapCallable (line 113) | func (s *delAttrSlot) wrapCallable(callable *Object) bool {
type deleteSlot (line 121) | type deleteSlot struct
method makeCallable (line 125) | func (s *deleteSlot) makeCallable(t *Type, slotName string) *Object {
method wrapCallable (line 137) | func (s *deleteSlot) wrapCallable(callable *Object) bool {
type delItemSlot (line 145) | type delItemSlot struct
method makeCallable (line 149) | func (s *delItemSlot) makeCallable(t *Type, slotName string) *Object {
method wrapCallable (line 161) | func (s *delItemSlot) wrapCallable(callable *Object) bool {
type getAttributeSlot (line 169) | type getAttributeSlot struct
method makeCallable (line 173) | func (s *getAttributeSlot) makeCallable(t *Type, slotName string) *Obj...
method wrapCallable (line 182) | func (s *getAttributeSlot) wrapCallable(callable *Object) bool {
type getSlot (line 189) | type getSlot struct
method makeCallable (line 193) | func (s *getSlot) makeCallable(t *Type, slotName string) *Object {
method wrapCallable (line 202) | func (s *getSlot) wrapCallable(callable *Object) bool {
type initSlot (line 209) | type initSlot struct
method makeCallable (line 213) | func (s *initSlot) makeCallable(t *Type, _ string) *Object {
method wrapCallable (line 222) | func (s *initSlot) wrapCallable(callable *Object) bool {
type nativeSlot (line 232) | type nativeSlot struct
method makeCallable (line 236) | func (s *nativeSlot) makeCallable(t *Type, slotName string) *Object {
method wrapCallable (line 240) | func (s *nativeSlot) wrapCallable(callable *Object) bool {
type newSlot (line 244) | type newSlot struct
method makeCallable (line 248) | func (s *newSlot) makeCallable(t *Type, _ string) *Object {
method wrapCallable (line 262) | func (s *newSlot) wrapCallable(callable *Object) bool {
type setAttrSlot (line 272) | type setAttrSlot struct
method makeCallable (line 276) | func (s *setAttrSlot) makeCallable(t *Type, slotName string) *Object {
method wrapCallable (line 288) | func (s *setAttrSlot) wrapCallable(callable *Object) bool {
type setItemSlot (line 296) | type setItemSlot struct
method makeCallable (line 300) | func (s *setItemSlot) makeCallable(t *Type, slotName string) *Object {
method wrapCallable (line 312) | func (s *setItemSlot) wrapCallable(callable *Object) bool {
type setSlot (line 320) | type setSlot struct
method makeCallable (line 324) | func (s *setSlot) makeCallable(t *Type, slotName string) *Object {
method wrapCallable (line 336) | func (s *setSlot) wrapCallable(callable *Object) bool {
type unaryOpSlot (line 344) | type unaryOpSlot struct
method makeCallable (line 348) | func (s *unaryOpSlot) makeCallable(t *Type, slotName string) *Object {
method wrapCallable (line 357) | func (s *unaryOpSlot) wrapCallable(callable *Object) bool {
type typeSlots (line 371) | type typeSlots struct
function calcSlotNames (line 454) | func calcSlotNames() []string {
FILE: runtime/slots_test.go
function TestSlotMakeCallable (line 22) | func TestSlotMakeCallable(t *testing.T) {
function TestSlotWrapCallable (line 81) | func TestSlotWrapCallable(t *testing.T) {
function prepareTestSlot (line 161) | func prepareTestSlot(s slot, gotArgs **Object, ret *Object) {
FILE: runtime/str.go
type stripSide (line 42) | type stripSide
constant stripSideLeft (line 45) | stripSideLeft stripSide = iota
constant stripSideRight (line 46) | stripSideRight
constant stripSideBoth (line 47) | stripSideBoth
function InternStr (line 53) | func InternStr(s string) *Str {
type Str (line 63) | type Str struct
method Decode (line 89) | func (s *Str) Decode(f *Frame, encoding, errors string) (*Unicode, *Ba...
method ToObject (line 116) | func (s *Str) ToObject() *Object {
method Value (line 121) | func (s *Str) Value() string {
function NewStr (line 70) | func NewStr(value string) *Str {
function toStrUnsafe (line 77) | func toStrUnsafe(o *Object) *Str {
function hashString (line 125) | func hashString(s string) int {
function strAdd (line 141) | func strAdd(f *Frame, v, w *Object) (*Object, *BaseException) {
function strCapitalize (line 163) | func strCapitalize(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseEx...
function strCenter (line 180) | func strCenter(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseExcept...
function strContains (line 193) | func strContains(f *Frame, o *Object, value *Object) (*Object, *BaseExce...
function strCount (line 208) | func strCount(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseExcepti...
function strDecode (line 218) | func strDecode(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseExcept...
function strEndsWith (line 243) | func strEndsWith(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
function strEq (line 247) | func strEq(f *Frame, v, w *Object) (*Object, *BaseException) {
function strFind (line 253) | func strFind(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
function strGE (line 259) | func strGE(f *Frame, v, w *Object) (*Object, *BaseException) {
function strGetItem (line 265) | func strGetItem(f *Frame, o, key *Object) (*Object, *BaseException) {
function strGetNewArgs (line 296) | func strGetNewArgs(f *Frame, args Args, _ KWArgs) (*Object, *BaseExcepti...
function strGT (line 303) | func strGT(f *Frame, v, w *Object) (*Object, *BaseException) {
function strHash (line 307) | func strHash(f *Frame, o *Object) (*Object, *BaseException) {
function strIndex (line 318) | func strIndex(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
function strIsAlNum (line 328) | func strIsAlNum(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseExcep...
function strIsAlpha (line 344) | func strIsAlpha(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseExcep...
function strIsDigit (line 360) | func strIsDigit(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseExcep...
function strIsLower (line 376) | func strIsLower(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseExcep...
function strIsSpace (line 392) | func strIsSpace(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseExcep...
function strIsTitle (line 408) | func strIsTitle(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseExcep...
function strIsUpper (line 446) | func strIsUpper(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseExcep...
function strJoin (line 462) | func strJoin(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
function strLE (line 512) | func strLE(f *Frame, v, w *Object) (*Object, *BaseException) {
function strLen (line 516) | func strLen(f *Frame, o *Object) (*Object, *BaseException) {
function strLJust (line 520) | func strLJust(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseExcepti...
function strLower (line 531) | func strLower(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseExcepti...
function strLStrip (line 548) | func strLStrip(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
function strLT (line 552) | func strLT(f *Frame, v, w *Object) (*Object, *BaseException) {
function strMod (line 556) | func strMod(f *Frame, v, w *Object) (*Object, *BaseException) {
function strMul (line 568) | func strMul(f *Frame, v, w *Object) (*Object, *BaseException) {
function strNative (line 580) | func strNative(f *Frame, o *Object) (reflect.Value, *BaseException) {
function strNE (line 584) | func strNE(f *Frame, v, w *Object) (*Object, *BaseException) {
function strNew (line 588) | func strNew(f *Frame, t *Type, args Args, _ KWArgs) (*Object, *BaseExcep...
function strReplace (line 631) | func strReplace(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
function strRepr (line 691) | func strRepr(_ *Frame, o *Object) (*Object, *BaseException) {
function strRFind (line 710) | func strRFind(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
function strRIndex (line 716) | func strRIndex(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
function strRJust (line 726) | func strRJust(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseExcepti...
function strSplit (line 737) | func strSplit(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseExcepti...
function strSplitLines (line 782) | func strSplitLines(f *Frame, args Args, _ KWArgs) (*Object, *BaseExcepti...
function strStrip (line 834) | func strStrip(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
function strRStrip (line 838) | func strRStrip(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
function strStripImpl (line 842) | func strStripImpl(f *Frame, args Args, side stripSide) (*Object, *BaseEx...
function strStartsWith (line 902) | func strStartsWith(f *Frame, args Args, _ KWArgs) (*Object, *BaseExcepti...
function strStr (line 906) | func strStr(_ *Frame, o *Object) (*Object, *BaseException) {
function strSwapCase (line 913) | func strSwapCase(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseExce...
function initStrType (line 935) | func initStrType(dict map[string]*Object) {
function strCompare (line 988) | func strCompare(v, w *Object, ltResult, eqResult, gtResult *Int) *Object {
function strInterpolate (line 1006) | func strInterpolate(f *Frame, format string, values *Tuple) (*Object, *B...
function strRepeatCount (line 1128) | func strRepeatCount(f *Frame, numChars int, mult *Object) (int, bool, *B...
function adjustIndex (line 1151) | func adjustIndex(start, end, length int) (int, int) {
function strStartsEndsWith (line 1169) | func strStartsEndsWith(f *Frame, method string, args Args) (*Object, *Ba...
function strTitle (line 1231) | func strTitle(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseExcepti...
function strUpper (line 1264) | func strUpper(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseExcepti...
function strZFill (line 1281) | func strZFill(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
function init (line 1293) | func init() {
function toLower (line 1300) | func toLower(b byte) byte {
function toUpper (line 1307) | func toUpper(b byte) byte {
function isAlNum (line 1314) | func isAlNum(c byte) bool {
function isAlpha (line 1318) | func isAlpha(c byte) bool {
function isDigit (line 1322) | func isDigit(c byte) bool {
function isLower (line 1326) | func isLower(c byte) bool {
function isSpace (line 1330) | func isSpace(c byte) bool {
function isUpper (line 1339) | func isUpper(c byte) bool {
function pad (line 1343) | func pad(s string, left int, right int, fillchar string) string {
function strLeftPad (line 1369) | func strLeftPad(s string, width int, fillchar string) string {
type indexFunc (line 1388) | type indexFunc
function strFindOrIndex (line 1390) | func strFindOrIndex(f *Frame, args Args, fn indexFunc) (*Object, *BaseEx...
function strJustDecodeArgs (line 1435) | func strJustDecodeArgs(f *Frame, args Args, name string) (string, int, s...
FILE: runtime/str_test.go
function TestNewStr (line 25) | func TestNewStr(t *testing.T) {
function BenchmarkNewStr (line 33) | func BenchmarkNewStr(b *testing.B) {
function TestHashString (line 48) | func TestHashString(t *testing.T) {
function TestStrBinaryOps (line 65) | func TestStrBinaryOps(t *testing.T) {
function TestStrCompare (line 125) | func TestStrCompare(t *testing.T) {
function TestStrContains (line 140) | func TestStrContains(t *testing.T) {
function TestStrDecode (line 155) | func TestStrDecode(t *testing.T) {
function TestStrGetItem (line 177) | func TestStrGetItem(t *testing.T) {
function TestStrNew (line 212) | func TestStrNew(t *testing.T) {
function TestStrRepr (line 261) | func TestStrRepr(t *testing.T) {
function TestStrMethods (line 274) | func TestStrMethods(t *testing.T) {
function TestStrStr (line 700) | func TestStrStr(t *testing.T) {
FILE: runtime/super.go
type super (line 26) | type super struct
function toSuperUnsafe (line 33) | func toSuperUnsafe(o *Object) *super {
function superInit (line 37) | func superInit(f *Frame, o *Object, args Args, _ KWArgs) (*Object, *Base...
function superGetAttribute (line 59) | func superGetAttribute(f *Frame, o *Object, name *Str) (*Object, *BaseEx...
function initSuperType (line 96) | func initSuperType(map[string]*Object) {
FILE: runtime/super_test.go
function TestSuperInitErrors (line 21) | func TestSuperInitErrors(t *testing.T) {
function TestSuperGetAttribute (line 35) | func TestSuperGetAttribute(t *testing.T) {
FILE: runtime/threading.go
constant argsCacheSize (line 24) | argsCacheSize = 16
constant argsCacheArgc (line 25) | argsCacheArgc = 6
type threadState (line 28) | type threadState struct
function newThreadState (line 45) | func newThreadState() *threadState {
type recursiveMutex (line 51) | type recursiveMutex struct
method Lock (line 57) | func (m *recursiveMutex) Lock(f *Frame) {
method Unlock (line 72) | func (m *recursiveMutex) Unlock(f *Frame) {
type TryableMutex (line 89) | type TryableMutex struct
method Lock (line 101) | func (m *TryableMutex) Lock() {
method TryLock (line 107) | func (m *TryableMutex) TryLock() bool {
method Unlock (line 117) | func (m *TryableMutex) Unlock() {
function NewTryableMutex (line 94) | func NewTryableMutex() *TryableMutex {
FILE: runtime/threading_test.go
function TestRecursiveMutex (line 21) | func TestRecursiveMutex(t *testing.T) {
function TestRecursiveMutexUnlockedTooManyTimes (line 30) | func TestRecursiveMutexUnlockedTooManyTimes(t *testing.T) {
function TestRecursiveMutexUnlockFrameMismatch (line 46) | func TestRecursiveMutexUnlockFrameMismatch(t *testing.T) {
FILE: runtime/traceback.go
type Traceback (line 22) | type Traceback struct
method ToObject (line 39) | func (f *Traceback) ToObject() *Object {
function newTraceback (line 29) | func newTraceback(f *Frame, next *Traceback) *Traceback {
function toTracebackUnsafe (line 34) | func toTracebackUnsafe(o *Object) *Traceback {
function initTracebackType (line 46) | func initTracebackType(map[string]*Object) {
FILE: runtime/tuple.go
type Tuple (line 25) | type Tuple struct
method GetItem (line 143) | func (t *Tuple) GetItem(i int) *Object {
method Len (line 148) | func (t *Tuple) Len() int {
method ToObject (line 153) | func (t *Tuple) ToObject() *Object {
function NewTuple (line 31) | func NewTuple(elems ...*Object) *Tuple {
function NewTuple0 (line 57) | func NewTuple0() *Tuple { return emptyTuple }
function NewTuple1 (line 60) | func NewTuple1(elem0 *Object) *Tuple {
function NewTuple2 (line 73) | func NewTuple2(elem0, elem1 *Object) *Tuple {
function NewTuple3 (line 86) | func NewTuple3(elem0, elem1, elem2 *Object) *Tuple {
function NewTuple4 (line 99) | func NewTuple4(elem0, elem1, elem2, elem3 *Object) *Tuple {
function NewTuple5 (line 112) | func NewTuple5(elem0, elem1, elem2, elem3, elem4 *Object) *Tuple {
function NewTuple6 (line 125) | func NewTuple6(elem0, elem1, elem2, elem3, elem4, elem5 *Object) *Tuple {
function toTupleUnsafe (line 137) | func toTupleUnsafe(o *Object) *Tuple {
function tupleAdd (line 162) | func tupleAdd(f *Frame, v, w *Object) (*Object, *BaseException) {
function tupleContains (line 173) | func tupleContains(f *Frame, t, v *Object) (*Object, *BaseException) {
function tupleCount (line 177) | func tupleCount(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseExcep...
function tupleEq (line 184) | func tupleEq(f *Frame, v, w *Object) (*Object, *BaseException) {
function tupleGE (line 188) | func tupleGE(f *Frame, v, w *Object) (*Object, *BaseException) {
function tupleGetItem (line 192) | func tupleGetItem(f *Frame, o, key *Object) (*Object, *BaseException) {
function tupleGetNewArgs (line 204) | func tupleGetNewArgs(f *Frame, args Args, _ KWArgs) (*Object, *BaseExcep...
function tupleGT (line 211) | func tupleGT(f *Frame, v, w *Object) (*Object, *BaseException) {
function tupleIter (line 215) | func tupleIter(f *Frame, o *Object) (*Object, *BaseException) {
function tupleLE (line 219) | func tupleLE(f *Frame, v, w *Object) (*Object, *BaseException) {
function tupleLen (line 223) | func tupleLen(f *Frame, o *Object) (*Object, *BaseException) {
function tupleLT (line 227) | func tupleLT(f *Frame, v, w *Object) (*Object, *BaseException) {
function tupleMul (line 231) | func tupleMul(f *Frame, v, w *Object) (*Object, *BaseException) {
function tupleNE (line 242) | func tupleNE(f *Frame, v, w *Object) (*Object, *BaseException) {
function tupleNew (line 246) | func tupleNew(f *Frame, t *Type, args Args, _ KWArgs) (*Object, *BaseExc...
function tupleRepr (line 260) | func tupleRepr(f *Frame, o *Object) (*Object, *BaseException) {
function tupleRMul (line 278) | func tupleRMul(f *Frame, v, w *Object) (*Object, *BaseException) {
function initTupleType (line 289) | func initTupleType(dict map[string]*Object) {
function tupleCompare (line 309) | func tupleCompare(f *Frame, v *Tuple, w *Object, cmp binaryOpFunc) (*Obj...
FILE: runtime/tuple_test.go
function TestNewTuple (line 22) | func TestNewTuple(t *testing.T) {
function TestTupleBinaryOps (line 36) | func TestTupleBinaryOps(t *testing.T) {
function TestTupleCompare (line 61) | func TestTupleCompare(t *testing.T) {
function TestTupleCompareNotImplemented (line 78) | func TestTupleCompareNotImplemented(t *testing.T) {
function TestTupleContains (line 85) | func TestTupleContains(t *testing.T) {
function TestTupleCount (line 105) | func TestTupleCount(t *testing.T) {
function BenchmarkTupleContains (line 118) | func BenchmarkTupleContains(b *testing.B) {
function TestTupleGetItem (line 170) | func TestTupleGetItem(t *testing.T) {
function TestTupleLen (line 188) | func TestTupleLen(t *testing.T) {
function TestTupleNew (line 195) | func TestTupleNew(t *testing.T) {
function TestTupleStrRepr (line 209) | func TestTupleStrRepr(t *testing.T) {
function TestTupleIter (line 233) | func TestTupleIter(t *testing.T) {
function newTestTuple (line 246) | func newTestTuple(elems ...interface{}) *Tuple {
FILE: runtime/type.go
type typeFlag (line 22) | type typeFlag
constant typeFlagInstantiable (line 29) | typeFlagInstantiable typeFlag = 1 << iota
constant typeFlagBasetype (line 32) | typeFlagBasetype typeFlag = 1 << iota
constant typeFlagDefault (line 33) | typeFlagDefault = typeFlagInstantiable | typeFlagBasetype
type Type (line 37) | type Type struct
method ToObject (line 279) | func (t *Type) ToObject() *Object {
method Name (line 284) | func (t *Type) Name() string {
method FullName (line 289) | func (t *Type) FullName(f *Frame) (string, *BaseException) {
method isSubclass (line 305) | func (t *Type) isSubclass(super *Type) bool {
method mroLookup (line 314) | func (t *Type) mroLookup(f *Frame, name *Str) (*Object, *BaseException) {
function newClass (line 54) | func newClass(f *Frame, meta *Type, name string, bases []*Type, dict *Di...
function newType (line 102) | func newType(meta *Type, name string, basis reflect.Type, bases []*Type,...
function newBasisType (line 112) | func newBasisType(name string, basis reflect.Type, basisFunc interface{}...
function newSimpleType (line 139) | func newSimpleType(name string, base *Type) *Type {
function prepareBuiltinType (line 145) | func prepareBuiltinType(typ *Type, init builtinTypeInit) {
function prepareType (line 183) | func prepareType(typ *Type) string {
function mroMerge (line 214) | func mroMerge(seqs [][]*Type) []*Type {
function mroCalc (line 265) | func mroCalc(t *Type) []*Type {
function toTypeUnsafe (line 274) | func toTypeUnsafe(o *Object) *Type {
function typeBasisFunc (line 326) | func typeBasisFunc(o *Object) reflect.Value {
function typeCall (line 342) | func typeCall(f *Frame, callable *Object, args Args, kwargs KWArgs) (*Ob...
function typeGetAttribute (line 363) | func typeGetAttribute(f *Frame, o *Object, name *Str) (*Object, *BaseExc...
function typeNew (line 401) | func typeNew(f *Frame, t *Type, args Args, kwargs KWArgs) (*Object, *Bas...
function typeRepr (line 443) | func typeRepr(f *Frame, o *Object) (*Object, *BaseException) {
function initTypeType (line 451) | func initTypeType(map[string]*Object) {
function basisParent (line 461) | func basisParent(basis reflect.Type) reflect.Type {
function basisSelect (line 470) | func basisSelect(b1, b2 reflect.Type) reflect.Type {
FILE: runtime/type_test.go
function TestNewClass (line 24) | func TestNewClass(t *testing.T) {
function TestNewBasisType (line 60) | func TestNewBasisType(t *testing.T) {
function TestNewSimpleType (line 90) | func TestNewSimpleType(t *testing.T) {
function TestInvalidBasisType (line 107) | func TestInvalidBasisType(t *testing.T) {
function TestPrepareType (line 137) | func TestPrepareType(t *testing.T) {
function makeTestType (line 163) | func makeTestType(name string, bases ...*Type) *Type {
function TestMroCalc (line 167) | func TestMroCalc(t *testing.T) {
function TestTypeIsSubclass (line 192) | func TestTypeIsSubclass(t *testing.T) {
function TestTypeCall (line 217) | func TestTypeCall(t *testing.T) {
function TestNewWithSubclass (line 236) | func TestNewWithSubclass(t *testing.T) {
function TestTypeGetAttribute (line 291) | func TestTypeGetAttribute(t *testing.T) {
function TestTypeName (line 359) | func TestTypeName(t *testing.T) {
function TestTypeNew (line 370) | func TestTypeNew(t *testing.T) {
function TestTypeNewResult (line 414) | func TestTypeNewResult(t *testing.T) {
function TestTypeStrRepr (line 440) | func TestTypeStrRepr(t *testing.T) {
function TestTypeModule (line 467) | func TestTypeModule(t *testing.T) {
function newTestClass (line 493) | func newTestClass(name string, bases []*Type, dict *Dict) *Type {
function newTestClassStrictEq (line 505) | func newTestClassStrictEq(name string, base *Type) *Type {
FILE: runtime/unicode.go
type Unicode (line 32) | type Unicode struct
method Encode (line 56) | func (s *Unicode) Encode(f *Frame, encoding, errors string) (*Str, *Ba...
method ToObject (line 83) | func (s *Unicode) ToObject() *Object {
method Value (line 88) | func (s *Unicode) Value() []rune {
function NewUnicode (line 39) | func NewUnicode(value string) *Unicode {
function NewUnicodeFromRunes (line 44) | func NewUnicodeFromRunes(value []rune) *Unicode {
function toUnicodeUnsafe (line 48) | func toUnicodeUnsafe(o *Object) *Unicode {
function unicodeAdd (line 92) | func unicodeAdd(f *Frame, v, w *Object) (*Object, *BaseException) {
function unicodeContains (line 109) | func unicodeContains(f *Frame, o *Object, value *Object) (*Object, *Base...
function unicodeEncode (line 126) | func unicodeEncode(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseEx...
function unicodeEq (line 151) | func unicodeEq(f *Frame, v, w *Object) (*Object, *BaseException) {
function unicodeGE (line 155) | func unicodeGE(f *Frame, v, w *Object) (*Object, *BaseException) {
function unicodeGetItem (line 162) | func unicodeGetItem(f *Frame, o, key *Object) (*Object, *BaseException) {
function unicodeGetNewArgs (line 189) | func unicodeGetNewArgs(f *Frame, args Args, _ KWArgs) (*Object, *BaseExc...
function unicodeGT (line 196) | func unicodeGT(f *Frame, v, w *Object) (*Object, *BaseException) {
function unicodeHash (line 200) | func unicodeHash(f *Frame, o *Object) (*Object, *BaseException) {
function unicodeJoin (line 217) | func unicodeJoin(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
function unicodeLE (line 232) | func unicodeLE(f *Frame, v, w *Object) (*Object, *BaseException) {
function unicodeLen (line 236) | func unicodeLen(f *Frame, o *Object) (*Object, *BaseException) {
function unicodeLT (line 240) | func unicodeLT(f *Frame, v, w *Object) (*Object, *BaseException) {
function unicodeMul (line 244) | func unicodeMul(f *Frame, v, w *Object) (*Object, *BaseException) {
function unicodeNative (line 262) | func unicodeNative(f *Frame, o *Object) (reflect.Value, *BaseException) {
function unicodeNE (line 271) | func unicodeNE(f *Frame, v, w *Object) (*Object, *BaseException) {
function unicodeNew (line 275) | func unicodeNew(f *Frame, t *Type, args Args, _ KWArgs) (ret *Object, ra...
function unicodeRepr (line 341) | func unicodeRepr(_ *Frame, o *Object) (*Object, *BaseException) {
function unicodeStr (line 357) | func unicodeStr(f *Frame, o *Object) (*Object, *BaseException) {
function unicodeStrip (line 365) | func unicodeStrip(f *Frame, args Args, _ KWArgs) (*Object, *BaseExceptio...
function initUnicodeType (line 413) | func initUnicodeType(dict map[string]*Object) {
function unicodeCompare (line 437) | func unicodeCompare(f *Frame, v *Unicode, w *Object, ltResult, eqResult,...
function runeSliceCmp (line 460) | func runeSliceCmp(lhs []rune, rhs []rune) int {
function unicodeCompareEq (line 487) | func unicodeCompareEq(f *Frame, v *Unicode, w *Object, eq bool) (*Object...
function unicodeCoerce (line 511) | func unicodeCoerce(f *Frame, o *Object) (*Unicode, *BaseException) {
function unicodeJoinParts (line 523) | func unicodeJoinParts(f *Frame, s *Unicode, parts []*Object) (*Object, *...
FILE: runtime/unicode_test.go
function TestUnicodeNewUnicode (line 24) | func TestUnicodeNewUnicode(t *testing.T) {
function TestUnicodeBinaryOps (line 45) | func TestUnicodeBinaryOps(t *testing.T) {
function TestUnicodeCompare (line 72) | func TestUnicodeCompare(t *testing.T) {
function TestUnicodeContains (line 95) | func TestUnicodeContains(t *testing.T) {
function TestUnicodeEncode (line 109) | func TestUnicodeEncode(t *testing.T) {
function TestUnicodeGetItem (line 128) | func TestUnicodeGetItem(t *testing.T) {
function TestUnicodeHash (line 149) | func TestUnicodeHash(t *testing.T) {
function TestUnicodeLen (line 164) | func TestUnicodeLen(t *testing.T) {
function TestUnicodeMethods (line 177) | func TestUnicodeMethods(t *testing.T) {
function TestUnicodeNative (line 205) | func TestUnicodeNative(t *testing.T) {
function TestUnicodeRepr (line 227) | func TestUnicodeRepr(t *testing.T) {
function TestUnicodeNew (line 242) | func TestUnicodeNew(t *testing.T) {
function TestUnicodeNewNotSubtype (line 273) | func TestUnicodeNewNotSubtype(t *testing.T) {
function TestUnicodeNewSubclass (line 280) | func TestUnicodeNewSubclass(t *testing.T) {
function TestUnicodeStr (line 310) | func TestUnicodeStr(t *testing.T) {
FILE: runtime/weakref.go
type weakRefState (line 31) | type weakRefState
constant weakRefStateNew (line 34) | weakRefStateNew weakRefState = iota
constant weakRefStateUsed (line 35) | weakRefStateUsed
constant weakRefStateDead (line 36) | weakRefStateDead
type WeakRef (line 40) | type WeakRef struct
method get (line 54) | func (r *WeakRef) get() *Object {
method ToObject (line 63) | func (r *WeakRef) ToObject() *Object {
function toWeakRefUnsafe (line 49) | func toWeakRefUnsafe(o *Object) *WeakRef {
function weakRefCall (line 67) | func weakRefCall(f *Frame, callable *Object, args Args, _ KWArgs) (*Obje...
function weakRefHash (line 81) | func weakRefHash(f *Frame, o *Object) (result *Object, raised *BaseExcep...
function weakRefNew (line 106) | func weakRefNew(f *Frame, t *Type, args Args, _ KWArgs) (*Object, *BaseE...
function weakRefRepr (line 141) | func weakRefRepr(f *Frame, o *Object) (*Object, *BaseException) {
function initWeakRefType (line 153) | func initWeakRefType(map[string]*Object) {
function weakRefFinalizeReferent (line 160) | func weakRefFinalizeReferent(o *Object) {
FILE: runtime/weakref_test.go
function TestWeakRefCall (line 24) | func TestWeakRefCall(t *testing.T) {
function TestWeakRefHash (line 41) | func TestWeakRefHash(t *testing.T) {
function TestWeakRefNew (line 67) | func TestWeakRefNew(t *testing.T) {
function TestWeakRefNewCallback (line 83) | func TestWeakRefNewCallback(t *testing.T) {
function TestWeakRefNewCallbackRaises (line 98) | func TestWeakRefNewCallbackRaises(t *testing.T) {
function TestWeakRefStrRepr (line 112) | func TestWeakRefStrRepr(t *testing.T) {
function newTestWeakRef (line 129) | func newTestWeakRef(o, callback *Object) *WeakRef {
function makeWeakRefsForTest (line 137) | func makeWeakRefsForTest() (*WeakRef, *Object, *WeakRef) {
function weakRefMustDie (line 147) | func weakRefMustDie(r *WeakRef) {
FILE: testing/assign_test.py
class Foo (line 18) | class Foo(object):
function foo (line 98) | def foo(): # pylint: disable=function-redefined
FILE: testing/builtin_test.py
function foo (line 103) | def foo(x):
class bar (line 109) | class bar(object):
method __call__ (line 111) | def __call__(self, *args, **kwargs):
class Lt (line 125) | class Lt(object):
method __init__ (line 127) | def __init__(self, x):
method __lt__ (line 131) | def __lt__(self, other):
class Eq (line 136) | class Eq(object):
method __init__ (line 138) | def __init__(self, x):
method __eq__ (line 142) | def __eq__(self, other):
class Gt (line 147) | class Gt(object):
method __init__ (line 149) | def __init__(self, x):
method __gt__ (line 153) | def __gt__(self, other):
class RichCmp (line 158) | class RichCmp(Lt, Eq, Gt):
method __init__ (line 160) | def __init__(self, x):
class Cmp (line 164) | class Cmp(object):
method __init__ (line 166) | def __init__(self, x):
method __cmp__ (line 170) | def __cmp__(self, other):
class NoCmp (line 180) | class NoCmp(object):
method __init__ (line 182) | def __init__(self, x):
class Foo (line 262) | class Foo(object):
FILE: testing/class_test.py
class Foo (line 16) | class Foo(object):
method bar (line 21) | def bar(self):
FILE: testing/compare_test.py
class RichCmp (line 27) | class RichCmp(object):
method __init__ (line 28) | def __init__(self, x):
method __lt__ (line 36) | def __lt__(self, other):
method __le__ (line 40) | def __le__(self, other):
method __eq__ (line 44) | def __eq__(self, other):
method __ge__ (line 48) | def __ge__(self, other):
method __gt__ (line 52) | def __gt__(self, other):
class Cmp (line 56) | class Cmp(object):
method __init__ (line 57) | def __init__(self, x):
method __cmp__ (line 61) | def __cmp__(self, other):
FILE: testing/function_test.py
function foo (line 18) | def foo(a):
function foo (line 43) | def foo(a, b):
function foo (line 62) | def foo(a, b=None):
function foo (line 72) | def foo(a, *args):
function foo (line 80) | def foo(a, **kwargs):
FILE: testing/generator_test.py
function gen1 (line 18) | def gen1():
function gen2 (line 28) | def gen2():
function gen3 (line 37) | def gen3():
function gen4 (line 48) | def gen4():
function gen5 (line 59) | def gen5():
function gen6 (line 70) | def gen6():
FILE: testing/global_test.py
function f1 (line 18) | def f1():
function f2 (line 26) | def f2():
class C1 (line 36) | class C1(object):
function f3 (line 43) | def f3():
function f4 (line 55) | def f4():
function f5 (line 67) | def f5():
FILE: testing/op_test.py
function TestBoolOps (line 22) | def TestBoolOps():
function TestBoolOpsLazyEval (line 31) | def TestBoolOpsLazyEval():
function TestNeg (line 61) | def TestNeg():
function TestPos (line 84) | def TestPos():
FILE: testing/scope_test.py
function f (line 23) | def f():
function g (line 43) | def g():
class Foo (line 69) | class Foo(object):
FILE: testing/str_test.py
class Foo (line 83) | class Foo(object):
method __index__ (line 85) | def __index__(self):
class IntIndexType (line 121) | class IntIndexType(object):
method __index__ (line 122) | def __index__(self):
class LongIndexType (line 125) | class LongIndexType(object):
method __index__ (line 126) | def __index__(self):
class IntIntType (line 129) | class IntIntType(object):
method __int__ (line 130) | def __int__(self):
class LongIntType (line 133) | class LongIntType(object):
method __int__ (line 134) | def __int__(self):
class S (line 272) | class S(str):
class A (line 301) | class A(object):
method __int__ (line 302) | def __int__(self):
method __int__ (line 362) | def __int__(self):
class AL (line 304) | class AL(object):
method __int__ (line 305) | def __int__(self):
class B (line 308) | class B(object):
method __index__ (line 309) | def __index__(self):
class BL (line 311) | class BL(object):
method __index__ (line 312) | def __index__(self):
class A (line 361) | class A(object):
method __int__ (line 302) | def __int__(self):
method __int__ (line 362) | def __int__(self):
FILE: testing/try_test.py
function f (line 108) | def f():
function foo (line 119) | def foo():
function foo (line 226) | def foo():
function foo (line 239) | def foo():
FILE: testing/with_test.py
class ContextManager (line 18) | class ContextManager(object):
method __init__ (line 20) | def __init__(self):
method __enter__ (line 23) | def __enter__(self):
method __exit__ (line 26) | def __exit__(self, exc_type, value, traceback):
class ExceptionSwallower (line 92) | class ExceptionSwallower(object):
method __init__ (line 94) | def __init__(self):
method __enter__ (line 97) | def __enter__(self):
method __exit__ (line 100) | def __exit__(self, exc_type, value, traceback):
class NoExit (line 121) | class NoExit(object):
method __enter__ (line 123) | def __enter__(self):
class NoEnter (line 137) | class NoEnter(object):
method __exit__ (line 139) | def __exit__(self, exc_type, value, traceback):
class EnterResult (line 161) | class EnterResult(object):
method __init__ (line 163) | def __init__(self, value):
method __enter__ (line 166) | def __enter__(self):
method __exit__ (line 169) | def __exit__(self, *args):
class Foo (line 185) | class Foo(object):
method __enter__ (line 187) | def __enter__(self):
method __exit__ (line 189) | def __exit__(self, *args):
function bar (line 207) | def bar():
FILE: third_party/ouroboros/operator.py
function lt (line 25) | def lt(a, b):
function le (line 29) | def le(a, b):
function eq (line 33) | def eq(a, b):
function ne (line 37) | def ne(a, b):
function ge (line 41) | def ge(a, b):
function gt (line 45) | def gt(a, b):
function not_ (line 51) | def not_(a):
function truth (line 55) | def truth(a):
function is_ (line 59) | def is_(a, b):
function is_not (line 63) | def is_not(a, b):
function abs (line 69) | def abs(a):
function add (line 73) | def add(a, b):
function and_ (line 77) | def and_(a, b):
function floordiv (line 81) | def floordiv(a, b):
function index (line 85) | def index(a):
function inv (line 89) | def inv(a):
function lshift (line 94) | def lshift(a, b):
function mod (line 98) | def mod(a, b):
function mul (line 102) | def mul(a, b):
function neg (line 106) | def neg(a):
function or_ (line 110) | def or_(a, b):
function pos (line 114) | def pos(a):
function pow (line 118) | def pow(a, b):
function rshift (line 122) | def rshift(a, b):
function sub (line 126) | def sub(a, b):
function truediv (line 130) | def truediv(a, b):
function xor (line 136) | def xor(a, b):
function concat (line 142) | def concat(a, b):
function contains (line 149) | def contains(a, b):
function countOf (line 153) | def countOf(a, b):
function delitem (line 161) | def delitem(a, b):
function getitem (line 165) | def getitem(a, b):
function indexOf (line 169) | def indexOf(a, b):
function setitem (line 177) | def setitem(a, b, c):
function length_hint (line 181) | def length_hint(obj, default=0):
class attrgetter (line 222) | class attrgetter(object):
method __init__ (line 230) | def __init__(self, attr, *attrs):
method __call__ (line 246) | def __call__(self, obj):
class itemgetter (line 250) | class itemgetter(object):
method __init__ (line 256) | def __init__(self, item, *items):
method __call__ (line 267) | def __call__(self, obj):
class methodcaller (line 271) | class methodcaller(object):
method __init__ (line 279) | def __init__(*args, **kwargs):
method __call__ (line 288) | def __call__(self, obj):
function iadd (line 293) | def iadd(a, b):
function iand (line 298) | def iand(a, b):
function iconcat (line 303) | def iconcat(a, b):
function ifloordiv (line 311) | def ifloordiv(a, b):
function ilshift (line 316) | def ilshift(a, b):
function imod (line 321) | def imod(a, b):
function imul (line 326) | def imul(a, b):
function ior (line 331) | def ior(a, b):
function ipow (line 336) | def ipow(a, b):
function irshift (line 341) | def irshift(a, b):
function isub (line 346) | def isub(a, b):
function itruediv (line 351) | def itruediv(a, b):
function ixor (line 358) | def ixor(a, b):
FILE: third_party/ouroboros/test/test_operator.py
class Seq1 (line 5) | class Seq1(object):
method __init__ (line 6) | def __init__(self, lst):
method __len__ (line 8) | def __len__(self):
method __getitem__ (line 10) | def __getitem__(self, i):
method __add__ (line 12) | def __add__(self, other):
method __mul__ (line 14) | def __mul__(self, other):
method __rmul__ (line 16) | def __rmul__(self, other):
class Seq2 (line 19) | class Seq2(object):
method __init__ (line 20) | def __init__(self, lst):
method __len__ (line 22) | def __len__(self):
method __getitem__ (line 24) | def __getitem__(self, i):
method __add__ (line 26) | def __add__(self, other):
method __mul__ (line 28) | def __mul__(self, other):
method __rmul__ (line 30) | def __rmul__(self, other):
class OperatorTestCase (line 33) | class OperatorTestCase(unittest.TestCase):
method test_lt (line 34) | def test_lt(self):
method test_le (line 44) | def test_le(self):
method test_eq (line 54) | def test_eq(self):
method test_ne (line 68) | def test_ne(self):
method test_ge (line 82) | def test_ge(self):
method test_gt (line 92) | def test_gt(self):
method test_abs (line 102) | def test_abs(self):
method test_add (line 109) | def test_add(self):
method test_bitwise_and (line 115) | def test_bitwise_and(self):
method test_concat (line 121) | def test_concat(self):
method test_countOf (line 131) | def test_countOf(self):
method test_delitem (line 139) | def test_delitem(self):
method test_floordiv (line 147) | def test_floordiv(self):
method test_truediv (line 153) | def test_truediv(self):
method test_getitem (line 159) | def test_getitem(self):
method test_indexOf (line 166) | def test_indexOf(self):
method test_invert (line 173) | def test_invert(self):
method test_lshift (line 179) | def test_lshift(self):
method test_mod (line 187) | def test_mod(self):
method test_mul (line 193) | def test_mul(self):
method test_neg (line 199) | def test_neg(self):
method test_bitwise_or (line 208) | def test_bitwise_or(self):
method test_pos (line 214) | def test_pos(self):
method test_pow (line 223) | def test_pow(self):
method test_rshift (line 231) | def test_rshift(self):
method test_contains (line 239) | def test_contains(self):
method test_setitem (line 246) | def test_setitem(self):
method test_sub (line 255) | def test_sub(self):
method test_truth (line 262) | def test_truth(self):
method test_bitwise_xor (line 274) | def test_bitwise_xor(self):
method test_is (line 280) | def test_is(self):
method test_is_not (line 289) | def test_is_not(self):
method test_attrgetter (line 298) | def test_attrgetter(self):
method test_itemgetter (line 349) | def test_itemgetter(self):
method test_methodcaller (line 384) | def test_methodcaller(self):
method test_inplace (line 408) | def test_inplace(self):
method test_length_hint (line 440) | def test_length_hint(self):
method test_dunder_is_original (line 465) | def test_dunder_is_original(self):
method test_complex_operator (line 475) | def test_complex_operator(self):
function test_main (line 480) | def test_main():
FILE: third_party/pypy/_collections.py
class deque (line 31) | class deque(object):
method __new__ (line 33) | def __new__(cls, iterable=(), *args, **kw):
method __init__ (line 38) | def __init__(self, iterable=(), maxlen=None):
method maxlen (line 49) | def maxlen(self):
method clear (line 53) | def clear(self):
method append (line 60) | def append(self, x):
method appendleft (line 74) | def appendleft(self, x):
method extend (line 88) | def extend(self, iterable):
method extendleft (line 94) | def extendleft(self, iterable):
method pop (line 100) | def pop(self):
method popleft (line 121) | def popleft(self):
method count (line 142) | def count(self, value):
method remove (line 149) | def remove(self, value):
method rotate (line 163) | def rotate(self, n=1):
method reverse (line 181) | def reverse(self):
method __repr__ (line 209) | def __repr__(self):
method __iter__ (line 223) | def __iter__(self):
method _iter_impl (line 226) | def _iter_impl(self, original_state, giveup):
method __reversed__ (line 242) | def __reversed__(self):
method _reversed_impl (line 245) | def _reversed_impl(self, original_state, giveup):
method __len__ (line 261) | def __len__(self):
method __getref (line 270) | def __getref(self, index):
method __getitem__ (line 299) | def __getitem__(self, index):
method __setitem__ (line 303) | def __setitem__(self, index, value):
method __delitem__ (line 307) | def __delitem__(self, index):
method __reduce_ex__ (line 323) | def __reduce_ex__(self, proto):
method __copy__ (line 328) | def __copy__(self):
method __eq__ (line 332) | def __eq__(self, other):
method __ne__ (line 338) | def __ne__(self, other):
method __lt__ (line 344) | def __lt__(self, other):
method __le__ (line 350) | def __le__(self, other):
method __gt__ (line 356) | def __gt__(self, other):
method __ge__ (line 362) | def __ge__(self, other):
method __iadd__ (line 368) | def __iadd__(self, other):
class deque_iterator (line 372) | class deque_iterator(object):
method __init__ (line 374) | def __init__(self, deq, itergen):
method next (line 381) | def next(self):
method __iter__ (line 386) | def __iter__(self):
class defaultdict (line 389) | class defaultdict(dict):
method __init__ (line 391) | def __init__(self, *args, **kwds):
method __missing__ (line 402) | def __missing__(self, key):
method __repr__ (line 409) | def __repr__(self, recurse=set()):
method copy (line 418) | def copy(self):
method __copy__ (line 421) | def __copy__(self):
method __reduce__ (line 424) | def __reduce__(self):
FILE: third_party/pypy/_csv.py
class Error (line 73) | class Error(Exception):
class Dialect (line 76) | class Dialect(object):
method __new__ (line 85) | def __new__(cls, dialect, **kwargs):
function _call_dialect (line 173) | def _call_dialect(dialect_inst, kwargs):
function register_dialect (line 176) | def register_dialect(name, dialect=None, **kwargs):
function unregister_dialect (line 185) | def unregister_dialect(name):
function get_dialect (line 193) | def get_dialect(name):
function list_dialects (line 201) | def list_dialects():
class Reader (line 206) | class Reader(object):
method __init__ (line 217) | def __init__(self, iterator, dialect=None, **kwargs):
method _parse_reset (line 224) | def _parse_reset(self):
method __iter__ (line 230) | def __iter__(self):
method next (line 233) | def next(self):
method _parse_process_char (line 260) | def _parse_process_char(self, line, pos):
method _parse_eol (line 385) | def _parse_eol(self):
method _parse_save_field (line 415) | def _parse_save_field(self):
method _parse_add_char (line 422) | def _parse_add_char(self, c):
class Writer (line 428) | class Writer(object):
method __init__ (line 434) | def __init__(self, file, dialect=None, **kwargs):
method _join_reset (line 440) | def _join_reset(self):
method _join_append (line 444) | def _join_append(self, field, quoted, quote_empty):
method writerow (line 491) | def writerow(self, row):
method writerows (line 526) | def writerows(self, rows):
function reader (line 530) | def reader(*args, **kwargs):
function writer (line 548) | def writer(*args, **kwargs):
function field_size_limit (line 566) | def field_size_limit(limit=undefined):
FILE: third_party/pypy/_functools.py
function reduce (line 6) | def reduce(function, iterable, initializer=None):
class partial (line 18) | class partial(object):
method __init__ (line 26) | def __init__(*args, **keywords):
method __delattr__ (line 37) | def __delattr__(self, key):
method func (line 43) | def func(self):
method args (line 49) | def args(self):
method keywords (line 55) | def keywords(self):
method __call__ (line 60) | def __call__(self, *f
Condensed preview — 295 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (3,610K chars).
[
{
"path": ".gitignore",
"chars": 29,
"preview": "build\nerrors.err\n*.swp\n*.pyc\n"
},
{
"path": ".pylintrc",
"chars": 1165,
"preview": "[BASIC]\nargument-rgx=^[a-z][a-z0-9_]*$\nattr-rgx=^_{0,2}[a-z][a-z0-9_]*$\nconst-rgx=^(_?[A-Z][A-Z0-9_]*|__[a-z0-9_]+__|_?["
},
{
"path": ".travis.yml",
"chars": 294,
"preview": "language: go\nos:\n - linux\n - osx\nbefore_script:\n - rvm get head || true # https://github.com/travis-ci/travis-ci/issu"
},
{
"path": "AUTHORS.md",
"chars": 1201,
"preview": "Contributors in the order of first contribution\n\n* [Dylan Trotter](https://github.com/trotterdylan)\n* [Aaron Tubbs](http"
},
{
"path": "CONTRIBUTING.md",
"chars": 3075,
"preview": "Want to contribute? Great! First, read this page.\n\n### Before you contribute\nBefore we can use your code, you must sign "
},
{
"path": "LICENSE",
"chars": 11411,
"preview": "Copyright 2016 Google Inc. All Rights Reserved.\n\n Apache License\n "
},
{
"path": "Makefile",
"chars": 13563,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "README.md",
"chars": 7740,
"preview": "# Grumpy: Go running Python\n\n[](https://travis-ci."
},
{
"path": "__init__.py",
"chars": 596,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "benchmarks/bm_call_method.py",
"chars": 2535,
"preview": "\"\"\"Microbenchmark for method call overhead.\n\nThis measures simple method calls that are predictable, do not use varargs "
},
{
"path": "benchmarks/bm_call_simple.py",
"chars": 1863,
"preview": "\"\"\"Microbenchmark for function call overhead.\n\nThis measures simple function calls that are not methods, do not use vara"
},
{
"path": "benchmarks/call.py",
"chars": 1349,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "benchmarks/comprehension.py",
"chars": 1219,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "benchmarks/concurrent.py",
"chars": 1696,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "benchmarks/dict.py",
"chars": 1515,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "benchmarks/generator.py",
"chars": 922,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "benchmarks/list.py",
"chars": 994,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "benchmarks/loop.py",
"chars": 972,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "benchmarks/tuple.py",
"chars": 1004,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "compiler/__init__.py",
"chars": 596,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "compiler/block.py",
"chars": 12030,
"preview": "# coding=utf-8\n\n# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (th"
},
{
"path": "compiler/block_test.py",
"chars": 9896,
"preview": "# coding=utf-8\n\n# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (th"
},
{
"path": "compiler/expr.py",
"chars": 2065,
"preview": "# coding=utf-8\n\n# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (th"
},
{
"path": "compiler/expr_visitor.py",
"chars": 16764,
"preview": "# coding=utf-8\n\n# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (th"
},
{
"path": "compiler/expr_visitor_test.py",
"chars": 8714,
"preview": "# coding=utf-8\n\n# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (th"
},
{
"path": "compiler/imputil.py",
"chars": 10446,
"preview": "# coding=utf-8\n\n# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (th"
},
{
"path": "compiler/imputil_test.py",
"chars": 13744,
"preview": "# coding=utf-8\n\n# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (th"
},
{
"path": "compiler/shard_test.py",
"chars": 2490,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "compiler/stmt.py",
"chars": 30936,
"preview": "# coding=utf-8\n\n# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (th"
},
{
"path": "compiler/stmt_test.py",
"chars": 16868,
"preview": "# coding=utf-8\n\n# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (th"
},
{
"path": "compiler/util.py",
"chars": 4574,
"preview": "# coding=utf-8\n\n# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (th"
},
{
"path": "compiler/util_test.py",
"chars": 2486,
"preview": "# coding=utf-8\n\n# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (th"
},
{
"path": "lib/README.md",
"chars": 115,
"preview": "This directory contains Grumpy Python standard library code. It is only expected\nto run under Grumpy, not CPython.\n"
},
{
"path": "lib/__builtin__.py",
"chars": 757,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "lib/_random.py",
"chars": 3352,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "lib/_syscall.py",
"chars": 932,
"preview": "# Copyright 2017 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "lib/errno.py",
"chars": 12,
"preview": "EINVAL = 22\n"
},
{
"path": "lib/exceptions.py",
"chars": 736,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "lib/itertools.py",
"chars": 5643,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "lib/itertools_test.py",
"chars": 5660,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "lib/math.py",
"chars": 3839,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "lib/math_test.py",
"chars": 1713,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "lib/os/__init__.py",
"chars": 5423,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "lib/os/path.py",
"chars": 2409,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "lib/os/path_test.py",
"chars": 3659,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "lib/os_test.py",
"chars": 4620,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "lib/random_test.py",
"chars": 2609,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "lib/select_.py",
"chars": 2475,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "lib/stat.py",
"chars": 871,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "lib/sys.py",
"chars": 2007,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "lib/sys_test.py",
"chars": 2201,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "lib/tempfile.py",
"chars": 1464,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "lib/tempfile_test.py",
"chars": 2419,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "lib/thread.py",
"chars": 1067,
"preview": "from '__go__/grumpy' import NewTryableMutex, StartThread, ThreadCount\n\n\nclass error(Exception):\n pass\n\n\ndef get_ident()"
},
{
"path": "lib/time.py",
"chars": 3240,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "lib/time_test.py",
"chars": 801,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "lib/types_test.py",
"chars": 1105,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "lib/weetest.py",
"chars": 5936,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "lib/weetest_test.py",
"chars": 5110,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "runtime/baseexception.go",
"chars": 2265,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/baseexception_test.go",
"chars": 3075,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/basestring.go",
"chars": 2139,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/basestring_test.go",
"chars": 1403,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/bool.go",
"chars": 2143,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/bool_test.go",
"chars": 2491,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/builtin_types.go",
"chars": 31245,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/builtin_types_test.go",
"chars": 35532,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/bytearray.go",
"chars": 5586,
"preview": "// Copyright 2017 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/bytearray_test.go",
"chars": 5268,
"preview": "// Copyright 2017 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/code.go",
"chars": 2756,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/code_test.go",
"chars": 5888,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/complex.go",
"chars": 16816,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/complex_test.go",
"chars": 39716,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/core.go",
"chars": 39907,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/core_test.go",
"chars": 53651,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/descriptor.go",
"chars": 4858,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/descriptor_test.go",
"chars": 7764,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/dict.go",
"chars": 31550,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/dict_test.go",
"chars": 34050,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/doc.go",
"chars": 10481,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/exceptions.go",
"chars": 6725,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/file.go",
"chars": 11710,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/file_test.go",
"chars": 18015,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/float.go",
"chars": 15929,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/float_test.go",
"chars": 20703,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/frame.go",
"chars": 8632,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/frame_test.go",
"chars": 12191,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/function.go",
"chars": 6737,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/function_test.go",
"chars": 6331,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/generator.go",
"chars": 3736,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/generator_test.go",
"chars": 2892,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/int.go",
"chars": 18206,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/int_test.go",
"chars": 19501,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/list.go",
"chars": 17787,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/list_test.go",
"chars": 27692,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/long.go",
"chars": 18816,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/long_test.go",
"chars": 16422,
"preview": "package grumpy\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"math/big\"\n\t\"reflect\"\n\t\"testing\"\n)\n\nvar overflowLong = big.NewInt(0).Add(maxInt"
},
{
"path": "runtime/method.go",
"chars": 5223,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/method_test.go",
"chars": 5505,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/module.go",
"chars": 9412,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/module_test.go",
"chars": 12059,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/native.go",
"chars": 23942,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/native_test.go",
"chars": 25648,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/numeric.go",
"chars": 1982,
"preview": "package grumpy\n\nimport (\n\t\"math/big\"\n\t\"strings\"\n)\n\nconst (\n\t// Here we calculate the number of bits in a uint and use th"
},
{
"path": "runtime/object.go",
"chars": 11527,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/object_test.go",
"chars": 19356,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/param.go",
"chars": 3759,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/param_test.go",
"chars": 4522,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/range.go",
"chars": 6658,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/range_test.go",
"chars": 6373,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/seq.go",
"chars": 9983,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/seq_test.go",
"chars": 5418,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/set.go",
"chars": 13561,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/set_test.go",
"chars": 14164,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/slice.go",
"chars": 5507,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/slice_test.go",
"chars": 4048,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/slots.go",
"chars": 14190,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/slots_test.go",
"chars": 12530,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/str.go",
"chars": 39599,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/str_test.go",
"chars": 50123,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/super.go",
"chars": 2822,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/super_test.go",
"chars": 4384,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/threading.go",
"chars": 3390,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/threading_test.go",
"chars": 1445,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/traceback.go",
"chars": 1466,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/tuple.go",
"chars": 9441,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/tuple_test.go",
"chars": 9277,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/type.go",
"chars": 14105,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/type_test.go",
"chars": 21544,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/unicode.go",
"chars": 16257,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/unicode_test.go",
"chars": 15544,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/weakref.go",
"chars": 5351,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "runtime/weakref_test.go",
"chars": 5678,
"preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "testing/assert_test.py",
"chars": 691,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "testing/assign_test.py",
"chars": 2082,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "testing/builtin_test.py",
"chars": 9127,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "testing/class_test.py",
"chars": 1056,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "testing/compare_test.py",
"chars": 2366,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "testing/complex_test.py",
"chars": 3248,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "testing/comprehension_test.py",
"chars": 950,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "testing/dict_test.py",
"chars": 1260,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "testing/file_test.py",
"chars": 405,
"preview": "f = open('/tmp/file_test__someunlikelyexistingfile', 'w')\nassert f.softspace == 0\n\nf.softspace = 1\nassert f.softspace =="
},
{
"path": "testing/float_test.py",
"chars": 758,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "testing/for_test.py",
"chars": 1629,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "testing/function_test.py",
"chars": 2328,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "testing/generator_test.py",
"chars": 1637,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "testing/getopt_test.py",
"chars": 522,
"preview": "import getopt\n\nargs = '-a -b -cfoo -d bar a1 a2'.split()\noptlist, args = getopt.getopt(args, 'abc:d:')\nassert optlist =="
},
{
"path": "testing/global_test.py",
"chars": 1316,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "testing/if_test.py",
"chars": 1157,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "testing/import_test.py",
"chars": 626,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "testing/list_test.py",
"chars": 2194,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "testing/native_test.py",
"chars": 1399,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "testing/op_test.py",
"chars": 1996,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "testing/pow_test.py",
"chars": 2492,
"preview": "#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance wit"
},
{
"path": "testing/scope_test.py",
"chars": 1338,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "testing/str_test.py",
"chars": 11106,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "testing/struct_test.py",
"chars": 811,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "testing/try_test.py",
"chars": 3696,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "testing/tuple_test.py",
"chars": 811,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "testing/while_test.py",
"chars": 1019,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "testing/with_test.py",
"chars": 4438,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "third_party/ouroboros/AUTHORS",
"chars": 343,
"preview": "Ouroboros was originally created in Jan 2016.\n\nThe PRIMARY AUTHORS are (and/or have been):\n Russell Keith-Magee\n\nAnd "
},
{
"path": "third_party/ouroboros/LICENSE",
"chars": 4174,
"preview": "Copyright (c) 2016 Russell Keith-Magee.\n\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with o"
},
{
"path": "third_party/ouroboros/READEME.md",
"chars": 165,
"preview": "The source code in this directory is forked from github.com/pybee/ouroboros. There are very light modifications to the s"
},
{
"path": "third_party/ouroboros/operator.py",
"chars": 9481,
"preview": "\"\"\"\nOperator Interface\nThis module exports a set of functions corresponding to the intrinsic\noperators of Python. For e"
},
{
"path": "third_party/ouroboros/test/test_operator.py",
"chars": 18641,
"preview": "import unittest\nimport operator\nfrom test import test_support\n\nclass Seq1(object):\n def __init__(self, lst):\n "
},
{
"path": "third_party/pypy/LICENSE",
"chars": 11155,
"preview": "#encoding utf-8\n\nLicense\n=======\n\nExcept when otherwise stated (look for LICENSE files in directories or\ninformation at "
},
{
"path": "third_party/pypy/README.md",
"chars": 246,
"preview": "Canonical versions of the files in this folder come from the\n[lib-python/2.7](https://bitbucket.org/pypy/pypy/src/23fd29"
},
{
"path": "third_party/pypy/_collections.py",
"chars": 13318,
"preview": "\"\"\"High performance data structures\n\"\"\"\n#\n# Copied and completed from the sandbox of CPython\n# (nondist/sandbox/collec"
},
{
"path": "third_party/pypy/_csv.py",
"chars": 20498,
"preview": "__doc__ = \"\"\"CSV parsing and writing.\n\nThis module provides classes that assist in the reading and writing\nof Comma Sepa"
},
{
"path": "third_party/pypy/_functools.py",
"chars": 3037,
"preview": "\"\"\" Supplies the internal functions for functools.py in the standard library \"\"\"\n\n__all__ = ['reduce', 'partial']\n\n# red"
},
{
"path": "third_party/pypy/_md5.py",
"chars": 11894,
"preview": "#!/usr/bin/env python\n# -*- coding: iso-8859-1 -*-\n\n# Note that PyPy contains also a built-in module 'md5' which will hi"
},
{
"path": "third_party/pypy/_sha.py",
"chars": 9730,
"preview": "#!/usr/bin/env python\n# -*- coding: iso-8859-1 -*-\n\n# Note that PyPy contains also a built-in module 'sha' which will hi"
},
{
"path": "third_party/pypy/_sha256.py",
"chars": 11602,
"preview": "import _struct as struct\n\nSHA_BLOCKSIZE = 64\nSHA_DIGESTSIZE = 32\n\n\ndef new_shaobject():\n return {\n 'digest': ["
},
{
"path": "third_party/pypy/_sha512.py",
"chars": 14150,
"preview": "\"\"\"\nThis code was Ported from CPython's sha512module.c\n\"\"\"\n\nimport _struct as struct\n\nSHA_BLOCKSIZE = 128\nSHA_DIGESTSIZE"
},
{
"path": "third_party/pypy/_sre.py",
"chars": 48591,
"preview": "# NOT_RPYTHON\n\"\"\"\nA pure Python reimplementation of the _sre module from CPython 2.4\nCopyright 2005 Nik Haldimann, licen"
},
{
"path": "third_party/pypy/_struct.py",
"chars": 12831,
"preview": "#\n# This module is a pure Python version of pypy.module.struct.\n# It is only imported if the vastly faster pypy.module.s"
},
{
"path": "third_party/pypy/binascii.py",
"chars": 24270,
"preview": "\"\"\"A pure Python implementation of binascii.\n\nRather slow and buggy in corner cases.\nPyPy provides an RPython version to"
},
{
"path": "third_party/pypy/datetime.py",
"chars": 74032,
"preview": "\"\"\"Concrete date/time and related types -- prototype implemented in Python.\n\nSee http://www.zope.org/Members/fdrake/Date"
},
{
"path": "third_party/pythonparser/LICENSE.txt",
"chars": 1095,
"preview": "Copyright (c) 2015 whitequark <whitequark@whitequark.org>\n\nMIT License\n\nPermission is hereby granted, free of charge, to"
},
{
"path": "third_party/pythonparser/README.md",
"chars": 211,
"preview": "The source code in this directory is forked from\n[github.com/m-labs/pythonparser](https://github.com/m-labs/pythonparser"
},
{
"path": "third_party/pythonparser/__init__.py",
"chars": 2511,
"preview": "from __future__ import absolute_import, division, print_function, unicode_literals\nimport sys\nfrom . import source as py"
},
{
"path": "third_party/pythonparser/algorithm.py",
"chars": 4164,
"preview": "\"\"\"\nThe :mod:`Diagnostic` module provides several commonly useful\nalgorithms that operate on abstract syntax trees.\n\"\"\"\n"
},
{
"path": "third_party/pythonparser/ast.py",
"chars": 26701,
"preview": "# encoding: utf-8\n\n\"\"\"\nThe :mod:`ast` module contains the classes comprising the Python abstract syntax tree.\n\nAll attri"
},
{
"path": "third_party/pythonparser/diagnostic.py",
"chars": 6705,
"preview": "\"\"\"\nThe :mod:`Diagnostic` module concerns itself with processing\nand presentation of diagnostic messages.\n\"\"\"\n\nfrom __fu"
},
{
"path": "third_party/pythonparser/lexer.py",
"chars": 25013,
"preview": "\"\"\"\nThe :mod:`lexer` module concerns itself with tokenizing Python source.\n\"\"\"\n\nfrom __future__ import absolute_import, "
},
{
"path": "third_party/pythonparser/parser.py",
"chars": 84004,
"preview": "# encoding:utf-8\n\n\"\"\"\nThe :mod:`parser` module concerns itself with parsing Python source.\n\"\"\"\n\nfrom __future__ import a"
},
{
"path": "third_party/pythonparser/source.py",
"chars": 10647,
"preview": "\"\"\"\nThe :mod:`source` module concerns itself with manipulating\nbuffers of source code: creating ranges of characters cor"
},
{
"path": "third_party/stdlib/LICENSE",
"chars": 12749,
"preview": "A. HISTORY OF THE SOFTWARE\n==========================\n\nPython was created in the early 1990s by Guido van Rossum at Stic"
},
{
"path": "third_party/stdlib/Queue.py",
"chars": 8584,
"preview": "\"\"\"A multi-producer, multi-consumer queue.\"\"\"\n\nfrom time import time as _time\n#try:\nimport threading as _threading\n#exce"
},
{
"path": "third_party/stdlib/README.md",
"chars": 210,
"preview": "Canonical versions of the files in this folder come from the\n[Lib](https://github.com/python/cpython/tree/2.7/Lib) direc"
},
{
"path": "third_party/stdlib/StringIO.py",
"chars": 10684,
"preview": "r\"\"\"File-like objects that read from or write to a string buffer.\n\nThis implements (nearly) all stdio methods.\n\nf = Stri"
},
{
"path": "third_party/stdlib/UserDict.py",
"chars": 7156,
"preview": "\"\"\"A more or less complete user-defined wrapper around dictionary objects.\"\"\"\n\nclass UserDict(object):\n def __init__("
},
{
"path": "third_party/stdlib/UserList.py",
"chars": 3644,
"preview": "\"\"\"A more or less complete user-defined wrapper around list objects.\"\"\"\n\nimport collections\n\nclass UserList(collections."
},
{
"path": "third_party/stdlib/UserString.py",
"chars": 9768,
"preview": "#!/usr/bin/env python\n## vim:ts=4:et:nowrap\n\"\"\"A user-defined wrapper around string objects\n\nNote: string objects have g"
},
{
"path": "third_party/stdlib/_abcoll.py",
"chars": 18807,
"preview": "# Copyright 2007 Google, Inc. All Rights Reserved.\n# Licensed to PSF under a Contributor Agreement.\n\n\"\"\"Abstract Base Cl"
},
{
"path": "third_party/stdlib/_weakrefset.py",
"chars": 5933,
"preview": "# Access WeakSet through the weakref module.\n# This code is separated-out because it is needed\n# by abc.py to load every"
},
{
"path": "third_party/stdlib/abc.py",
"chars": 7175,
"preview": "# Copyright 2007 Google, Inc. All Rights Reserved.\n# Licensed to PSF under a Contributor Agreement.\n\n\"\"\"Abstract Base Cl"
},
{
"path": "third_party/stdlib/argparse.py",
"chars": 93498,
"preview": "# Author: Steven J. Bethard <steven.bethard@gmail.com>.\n\n\"\"\"Command-line parsing library\n\nThis module is an optparse-ins"
},
{
"path": "third_party/stdlib/base64.py",
"chars": 11834,
"preview": "#! /usr/bin/env python\n\n\"\"\"RFC 3548: Base16, Base32, Base64 Data Encodings\"\"\"\n\n# Modified 04-Oct-1995 by Jack Jansen to "
}
]
// ... and 95 more files (download for full content)
About this extraction
This page contains the full source code of the google/grumpy GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 295 files (3.3 MB), approximately 869.2k tokens, and a symbol index with 6017 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.